lactationcurve.characteristics.interpolation_using_standard_lactation_curves
Interpolation using Standard Lactation Curves (ISLC).
Purpose
The Interpolation using Standard Lactation Curves (ISLC) method estimates lactation yield from intermittent test-day records by predicting deviations from an expected lactation curve. The method uses standard lactation curves that represent the expected course of lactation for specific cow subgroups, such as breed or parity.
By incorporating these standard curves, ISLC accounts for the typical lactation pattern in which milk yield increases after calving, reaches a peak, and subsequently declines. Daily yields are estimated at fixed lactation days (e.g., 0, 10, 30, 50) and used to calculate accumulated lactation production.
This module implements the ISLC family of methods following the CRV/ICAR approach described in ICAR Procedure 2, Section 2 (Computing Accumulated Lactation Yield). The implementation is based on Wilmink-type standard lactation curves combined with correlation-based deviation corrections.
Method Summary
ISLC methods estimate total lactation yield by first interpolating test-day yields onto a predefined dim grid, then integrating the resulting days with a test-interval style summation.
Key Entry Points
ISLC_method_single_lactation: compute a single lactation's estimated 305-d yield from interpolated grid measurements.ISLC_method: applyISLC_methodperTestIdin a pandas DataFrame.ISLC_original_method_single_lactation: compute a single lactation's estimated 305-d yield using the technique described in the original paper. Wilmink et al. (1987) "Comparison of different methods of predicting 305-day milk yield using means calculated from within-herd lactation curves"ISLC_original: applyISLC_original_methodperTestIdin a pandas DataFrame.interpolation_standard_lc: interpolate measured test-day yields onto the dim grid using the standard lactation curve to guide slopes.linear_interpd_all_to_gridandlinear_interpd_closest_to_grid: Linear interpolation alternatives.
Column Flexibility
The functions accept several case-insensitive column name aliases and can
create a default TestId if one is missing. Recognized aliases:
- Days in Milk:
["daysinmilk", "dim", "testday"] - Milk Yield:
["milkingyield", "testdaymilkyield", "milkyield", "yield"] - Test Id:
["animalid", "testid", "id"]
It is also possible to provide your own column names so the function can be applied to dataframes with different column naming conventions.
Returns a DataFrame with columns: ["TestId", "LactationMilkYield"].
Defaults
STANDARD_CURVE: Baseline expected lactation curve for days 1..305 (Wilmink lactation curve model).CORR_MATRIX: Default day-to-day correlation structure used for projection.STDs: Standard deviations for each grid day, empirically estimated.
Notes
- Milk samples are often recorded on non-grid dim values. Interpolation is therefore used to map measurements to grid days.
- Three interpolation variants are implemented.
interpolation_standard_lcis recommended because it is the most consistent with the original method. interpolation_standard_lcrequires a standard lactation curve. You can fit one with thelactationcurvepackage or use the default lactation curve.- The method can be applied to lactations without any measurements, in which case the result will be the population mean from the standard curve.
- Predicted milk yields have less variance than true milk yields. With TIM, estimated yields have more variance than true yields. The reason is that predicted yields are regressed toward the mean unless all 305 daily yields are observed.
- The main ISLC method in this package is not the same as the original method
described in the paper by Wilmink.
The original method is implemented in
ISLC_original_methodandISLC_original. The difference in the new method is that the grid is extended to include day 1 and day 305. ALso the measured test days are taken into account in the final summation to lactation yield, while in the original method only the interpolated values on the grid are used. The new method can also be applied to lactation extending beyond 305 days, while the original method is strictly for 305-day yield estimation. - The method currently assumes that the standard curves are the same for all lactations, but future updates may allow using different standard curves and covariance structures for different subgroups of lactations (e.g., by breed or parity).
- ISLC's strenght is that its caclulation is broken up in multiple steps, which makes it more computer memory friendly than the best predict method, which requires the inversion of a large covariance matrix. Because of the integration of standard lactation curves it takes into account the shape of the lactation curve, which can lead to more accurate estimates of total yield, especially for lactations with few test days or irregular patterns.
- ISLC's main disadvantage is that because of the many in between steps, it is relatively complex to implement and understand, making it less transparant. The best results are obtained when the standard curve and covariance matrix are from the same population as the data, which can be a barrier for users without access to a large reference dataset. This also causes inconsistencies in cumulative milk yield results depending on which standard curves are used. A cow with the exact same test-day records can have a different cumulative milk yield estimates depending on the standard curve used, which can be considered unfair.
References
Wilmink, J. B. M. (1987). Comparison of different methods of predicting 305-day milk yield using means calculated from within-herd lactation curves. Livestock Production Science, 17, 1-17.
Wilmink, J. B. M. (1987). Adjustment of test-day milk, fat and protein yield for age, season and stage of lactation. Livestock Production Science, 16(4), 335-348.
Handbook NRS © CR Delta chapter E1 and E2 02-98
Author: Meike van Leerdam Date: 20 October 2025 Last update: 21 May 2026
1"""Interpolation using Standard Lactation Curves (ISLC). 2 3Purpose 4------- 5The Interpolation using Standard Lactation Curves (ISLC) method estimates 6lactation yield from intermittent test-day records by predicting 7deviations from an expected lactation curve. 8The method uses standard lactation curves that represent the expected 9course of lactation for specific cow subgroups, such 10as breed or parity. 11 12By incorporating these standard curves, ISLC accounts for the typical 13lactation pattern in which milk yield increases after calving, reaches a 14peak, and subsequently declines. Daily yields are estimated at fixed 15lactation days (e.g., 0, 10, 30, 50) and used to calculate accumulated 16lactation production. 17 18This module implements the ISLC family of methods following the CRV/ICAR 19approach described in ICAR Procedure 2, Section 2 (Computing Accumulated 20Lactation Yield). The implementation is based on Wilmink-type standard 21lactation curves combined with correlation-based deviation corrections. 22 23 24Method Summary 25-------------- 26ISLC methods estimate total lactation yield by first interpolating test-day 27yields onto a predefined dim grid, then integrating the resulting days with 28a test-interval style summation. 29 30Key Entry Points 31---------------- 32- ``ISLC_method_single_lactation``: compute a single lactation's estimated 305-d yield from 33 interpolated grid measurements. 34- ``ISLC_method``: apply ``ISLC_method`` per ``TestId`` in a pandas DataFrame. 35- ``ISLC_original_method_single_lactation``: compute a single lactation's estimated 36 305-d yield using the technique described in the original paper. 37 Wilmink et al. (1987) 38 "Comparison of different methods of predicting 305-day milk yield 39 using means calculated from within-herd lactation curves" 40- ``ISLC_original``: apply ``ISLC_original_method`` per ``TestId`` 41 in a pandas DataFrame. 42- ``interpolation_standard_lc``: interpolate measured test-day yields onto 43 the dim grid using the standard lactation curve to guide slopes. 44- ``linear_interpd_all_to_grid`` and ``linear_interpd_closest_to_grid``: 45 Linear interpolation alternatives. 46 47Column Flexibility 48------------------ 49The functions accept several case-insensitive column name aliases and can 50create a default ``TestId`` if one is missing. Recognized aliases: 51 52- Days in Milk: `["daysinmilk", "dim", "testday"]` 53- Milk Yield: `["milkingyield", "testdaymilkyield", "milkyield", "yield"]` 54- Test Id: `["animalid", "testid", "id"]` 55 56It is also possible to provide your own column names so the function 57can be applied to dataframes with different column naming conventions. 58 59Returns a DataFrame with columns: ``["TestId", "LactationMilkYield"]``. 60 61Defaults 62-------- 63- ``STANDARD_CURVE``: Baseline expected lactation curve for days 1..305 64 (Wilmink lactation curve model). 65- ``CORR_MATRIX``: Default day-to-day correlation structure used for projection. 66- ``STDs``: Standard deviations for each grid day, empirically estimated. 67 68Notes 69----- 70- Milk samples are often recorded on non-grid dim values. 71 Interpolation is therefore used to map measurements to grid days. 72- Three interpolation variants are implemented. 73 ``interpolation_standard_lc`` is recommended because it is the most 74 consistent with the original method. 75- ``interpolation_standard_lc`` requires a standard lactation curve. 76 You can fit one with the ``lactationcurve`` package 77 or use the default lactation curve. 78- The method can be applied to lactations without any measurements, 79 in which case the result will be the population mean from the standard curve. 80- Predicted milk yields have less variance than true milk yields. With TIM, 81 estimated yields have more variance than true yields. The reason is that predicted yields are 82 regressed toward the mean unless all 305 daily yields are observed. 83- The main ISLC method in this package is not the same as the original method 84 described in the paper by Wilmink. 85 The original method is implemented in ``ISLC_original_method`` and ``ISLC_original``. 86 The difference in the new method is that the grid is extended to include day 1 and day 305. 87 ALso the measured test days are taken into account in the final summation to lactation yield, 88 while in the original method only the interpolated values on the grid are used. 89 The new method can also be applied to lactation extending beyond 305 days, 90 while the original method is strictly for 305-day yield estimation. 91- The method currently assumes that the standard curves are the same 92 for all lactations, 93 but future updates may allow using different standard curves and covariance structures for 94 different subgroups of lactations (e.g., by breed or parity). 95- ISLC's strenght is that its caclulation is broken up in multiple steps, 96 which makes it more computer memory friendly than the best predict method, 97 which requires the inversion of a large covariance matrix. 98 Because of the integration of standard lactation curves 99 it takes into account the shape of the lactation curve, 100 which can lead to more accurate estimates of total yield, 101 especially for lactations with few test days or irregular patterns. 102- ISLC's main disadvantage is that because of the many in between steps, 103 it is relatively complex to implement and understand, making it less transparant. 104 The best results are obtained when the standard curve and covariance matrix 105 are from the same population as the data, 106 which can be a barrier for users without access to a large reference dataset. 107 This also causes inconsistencies in cumulative milk yield results 108 depending on which standard curves are used. 109 A cow with the exact same test-day records 110 can have a different cumulative milk yield estimates depending 111 on the standard curve used, which can be considered unfair. 112 113References 114--------- 115Wilmink, J. B. M. (1987). 116Comparison of different methods of predicting 305-day milk yield using means 117calculated from within-herd lactation curves. Livestock Production Science, 11817, 1-17. 119 120Wilmink, J. B. M. (1987). 121Adjustment of test-day milk, fat and protein yield for age, 122season and stage of lactation. Livestock Production Science, 16(4), 335-348. 123 124Handbook NRS © CR Delta chapter E1 and E2 02-98 125 126 127Author: Meike van Leerdam 128Date: 20 October 2025 129Last update: 21 May 2026 130""" 131 132# Import packages 133import inspect 134from pathlib import Path 135from typing import Any, Protocol, cast 136 137import numpy as np 138import numpy.typing as npt 139import pandas as pd 140from scipy.interpolate import interp1d 141 142from lactationcurve.fitting import fit_lactation_curve 143from lactationcurve.preprocessing import standardize_lactation_columns 144 145DATA_DIR = Path(__file__).resolve().parent / "data" 146GRID_DAYS = [10, 30, 50, 70, 90, 110, 130, 150, 170, 190, 210, 230, 250, 270, 290] 147 148"""ISLC takes information from a standard lactation curve. 149Ideally this lactation curve is fitted to the same population as the data to be scored. 150To make sure this method can be used out of the box, 151we provide a default standard lactation curve, correlation matrix and standard deviations 152per grid day that were fitted on a group of cows in the Benelux. 153They are stored in the data directory and can be retrieved using the following code:""" 154CORR_MATRIX = cast(pd.DataFrame, pd.read_pickle(DATA_DIR / "corr_matrix.pkl")) 155STDs = np.load(DATA_DIR / "std_per_grid_day.npy") 156STANDARD_CURVE = np.load(DATA_DIR / "standard_lc_grid.npy") 157 158# add a day zero (that equals day 1) to the standard curve to prevent an index shift 159STANDARD_CURVE = np.insert(STANDARD_CURVE, 0, STANDARD_CURVE[0]) 160 161 162""" The following functions are mostly internal functions that are used by the ISLC method. 163They are not meant to be used directly by the user, 164but they can be useful for understanding the method and for debugging.""" 165 166 167class _DocDefault: 168 """Lightweight repr-only wrapper for cleaner generated signatures.""" 169 170 def __init__(self, label: str) -> None: 171 self.label = label 172 173 def __repr__(self) -> str: 174 return self.label 175 176 177_DOC_STANDARD_CURVE = _DocDefault("STANDARD_CURVE") 178_DOC_CORR_MATRIX = _DocDefault("CORR_MATRIX") 179_DOC_STDS = _DocDefault("STDs") 180 181 182def _curve_to_series(curve: pd.Series | npt.NDArray[np.float64]) -> pd.Series: 183 """Normalize standard lactation curve input to a Series.""" 184 if isinstance(curve, pd.Series): 185 return curve 186 return pd.Series(curve) 187 188 189def _curve_value(curve: pd.Series, day: int) -> float: 190 """Return curve value for a day in milk, supporting both label and positional indexing.""" 191 if day in curve.index: 192 return float(curve.loc[day]) 193 return float(curve.iloc[day]) 194 195 196def _calculation_grid(calculation_end: int) -> list[int]: 197 """Build the unique ISLC calculation grid for an integration endpoint.""" 198 grid = [0] + [day for day in GRID_DAYS if day < calculation_end] 199 if calculation_end not in grid: 200 grid.append(calculation_end) 201 return grid 202 203 204class InterpolationMethod(Protocol): 205 """Protocol for milk-yield interpolation methods. 206 207 Defines the signature expected by functions that interpolate test-day 208 yields onto a predefined dim grid. 209 """ 210 211 def __call__( 212 self, 213 group: pd.DataFrame, 214 days_in_milk_col: str, 215 milking_yield_col: str, 216 standard_lc: pd.Series | npt.NDArray[np.float64] | None = None, 217 small_grid: bool = False, 218 ) -> pd.DataFrame: 219 """Interpolate yields for a single lactation onto the dim grid. 220 221 Args: 222 group: Test-day records for a single animal. 223 days_in_milk_col: Column name containing days in milk (dim). 224 milking_yield_col: Column name containing milk yields. 225 standard_lc: Optional standard lactation curve to guide 226 interpolation (method-dependent). 227 small_grid: If True, interpolate only on GRID_DAYS; 228 otherwise use [0] + GRID_DAYS + [305]. 229 230 Returns: 231 A DataFrame with interpolated yields, typically including 232 columns ``GridDay`` and ``MilkYieldInterp``. 233 """ 234 ... 235 236 237""" This is the function that is called by the user to apply the ISLC method 238to a dataframe with test-day records. 239It groups the dataframe by TestId and applies the ISLC_method to each group. 240It returns a dataframe with the estimated lactation milk yield for each TestId.""" 241 242 243def ISLC_method( 244 df: pd.DataFrame, 245 days_in_milk_col: str | None = None, 246 milking_yield_col: str | None = None, 247 test_id_col: str | None = None, 248 default_test_id: int = 0, 249 standard_lc_305: pd.Series | npt.NDArray[np.float64] = STANDARD_CURVE, 250 correlation_matrix: pd.DataFrame = CORR_MATRIX, 251 std_per_grid_day: npt.NDArray[np.float64] = STDs, 252 max_dim: int | str = 305, 253 fit_standard_lc_from_data: bool = False, 254 reference_df: pd.DataFrame | None = None, 255) -> pd.DataFrame: 256 """Estimate cumulative lactation yield per TestId using ISLC. 257 258 This variant applies :func:`ISLC_method` to standardized lactation records. 259 By default it uses the package-provided standard curve, correlation matrix, 260 and per-grid day standard deviations. Optionally, these assets can be refit 261 from a reference dataset by providing a pandas dataframe at 'reference_df =' 262 when ``fit_standard_lc_from_data`` is True. 263 Alternative for customization is to set standard_lc_305, 264 correlation_matrix, and std_per_grid_day directly. 265 266 Args: 267 df: Input test-day records. 268 days_in_milk_col: Name of dim column in ``df``. 269 milking_yield_col: Name of milk-yield column in ``df``. 270 test_id_col: Name of lactation identifier column in ``df``. 271 default_test_id: Fallback TestId value when ``test_id_col`` is absent. 272 standard_lc_305: Standard lactation curve values used by ISLC. 273 correlation_matrix: Correlation matrix aligned with ISLC grid. 274 std_per_grid_day: Standard deviations aligned with ISLC grid. 275 max_dim: Maximum dim to include 276 (or ``"max"`` so highest test day dim is considered the final lactation day). 277 fit_standard_lc_from_data: If True, fit representation from ``reference_df``. 278 reference_df: Reference records used when fitting curve and covariance. 279 280 Returns: 281 DataFrame with columns ``TestId`` and ``LactationMilkYield``. 282 283 Raises: 284 ValueError: If required columns are missing or fit mode has no reference data. 285 """ 286 # Standardize columns and filter dim <= 305 287 df = standardize_lactation_columns( 288 df, 289 days_in_milk_col=days_in_milk_col, 290 milking_yield_col=milking_yield_col, 291 test_id_col=test_id_col, 292 default_test_id=default_test_id, 293 max_dim=max_dim, 294 ) 295 296 # Fit covariance/standard_lc if requested 297 if fit_standard_lc_from_data is True: 298 if reference_df is None: 299 raise ValueError("Provide reference_df to fit your own standard lactation curve.") 300 reference_df = standardize_lactation_columns( 301 reference_df, 302 days_in_milk_col=days_in_milk_col, 303 milking_yield_col=milking_yield_col, 304 test_id_col=test_id_col, 305 default_test_id=default_test_id, 306 max_dim=305, 307 ) 308 dim = reference_df["DaysInMilk"] 309 milk_yield = reference_df["MilkingYield"] 310 standard_full_lc_305 = fit_lactation_curve(dim, milkrecordings=milk_yield, model="wilmink") 311 # convert to pandas series 312 standard_full_lc_305 = pd.Series(standard_full_lc_305) 313 314 # fit matrix 315 ( 316 correlation_matrix, 317 std_per_grid_day, 318 standard_curve_fitted, 319 ) = create_standard_lc_representation( 320 df=reference_df, 321 standard_lactation_curve=pd.Series(standard_full_lc_305), 322 # reference_df is standardized above, so fixed names are required here 323 days_in_milk_col="DaysInMilk", 324 milking_yield_col="MilkingYield", 325 interpolation_method=interpolation_standard_lc, 326 small_grid=False, 327 ) 328 329 # Align fitted curve with default internal convention (day 0 equals day 1). 330 standard_lc_305 = np.insert( 331 np.asarray(standard_curve_fitted, dtype=float), 332 0, 333 float(standard_curve_fitted.iloc[0]), 334 ) 335 336 rows: list[dict[str, Any]] = [] 337 for test_id, group in df.groupby("TestId", sort=False): 338 if group.empty: 339 rows.append({"TestId": test_id, "LactationMilkYield": np.nan}) 340 continue 341 342 try: 343 cumulative_yield = ISLC_method_single_lactation( 344 df=group, 345 standard_lc=standard_lc_305, 346 correlation_matrix=correlation_matrix, 347 std_per_grid_day=std_per_grid_day, 348 days_in_milk_col="DaysInMilk", 349 milking_yield_col="MilkingYield", 350 max_dim=max_dim, 351 ) 352 except ValueError: 353 cumulative_yield = np.nan 354 355 rows.append({"TestId": test_id, "LactationMilkYield": cumulative_yield}) 356 357 return pd.DataFrame(rows, columns=pd.Index(["TestId", "LactationMilkYield"])) 358 359 360""" This is the core function taht implements the ISLC method for a single lactation. 361It predicts missing grid-day yields using the ICAR-style relation and integrates 362the complete grid profile to estimate total lactation yield. """ 363 364 365def ISLC_method_single_lactation( 366 df: pd.DataFrame, 367 standard_lc: pd.Series | npt.NDArray[np.float64], 368 correlation_matrix: pd.DataFrame, 369 std_per_grid_day: npt.NDArray[np.float64], 370 days_in_milk_col: str = "DaysInMilk", 371 milking_yield_col: str = "MilkingYield", 372 max_dim: int | str = 305, 373) -> float: 374 """Estimate total lactation yield by predicting missing grid days, then integrating. 375 376 The method fills missing grid-day yields with the ICAR-style relation: 377 378 yp = gp + b* (yi - gi) 379 380 where for each missing day p, the nearest measured day i is used and 381 b* = corr(i,p) * std(p) / std(i). The resulting complete grid profile is 382 integrated with the test-interval style weighting used elsewhere in this 383 package. 384 385 Notes: 386 The integration is performed over the days present after merging 387 measured and predicted points. If the input contains dim beyond 305, 388 total yield can reflect that extended horizon if ``max_dim`` is set accordingly. 389 """ 390 dim_col = days_in_milk_col 391 yield_col = milking_yield_col 392 393 # Use the requested horizon, or the last observed day for ``"max"``. 394 if max_dim == "max": 395 observed_dim = df[dim_col].to_numpy(dtype=float) 396 calculation_end = int(np.max(observed_dim)) 397 else: 398 calculation_end = int(max_dim) 399 400 grid = _calculation_grid(calculation_end) 401 required_asset_size = len(grid) 402 std_size = np.asarray(std_per_grid_day).shape[0] 403 if std_size < required_asset_size: 404 raise ValueError( 405 "std_per_grid_day must contain one value per calculation-grid position " 406 f"(expected at least {required_asset_size}, got {std_size})." 407 ) 408 if ( 409 correlation_matrix.shape[0] < required_asset_size 410 or correlation_matrix.shape[1] < required_asset_size 411 ): 412 raise ValueError( 413 "correlation_matrix must contain one row and column per calculation-grid position " 414 f"(expected at least {required_asset_size}, got {correlation_matrix.shape})." 415 ) 416 417 standard_lc_series = _curve_to_series(standard_lc) 418 419 # Extract the measured days 420 measured_days = df[dim_col].to_numpy() 421 if measured_days.size == 0: 422 raise ValueError("Input df must contain at least one measured day.") 423 424 # interpolate the measured days to the grid using the standard lactation curve 425 interpolated_df = interpolation_standard_lc( 426 group=df, 427 days_in_milk_col=dim_col, 428 milking_yield_col=yield_col, 429 standard_lc=standard_lc_series, 430 ) 431 432 # drop unnecessary columns 433 interpolated_df = interpolated_df.drop(columns=[dim_col, yield_col]) 434 435 # rename grid colum 436 interpolated_df = interpolated_df.rename( 437 columns={"GridDay": dim_col, "MilkYieldInterp": yield_col} 438 )[[dim_col, yield_col]] 439 440 measured_subset = cast(pd.DataFrame, df.loc[:, [dim_col, yield_col]]) 441 interpolated_subset = cast(pd.DataFrame, interpolated_df.loc[:, [dim_col, yield_col]]) 442 443 # join the interpolated values with the original measurements, keeping all measurements 444 merged_df = cast( 445 pd.DataFrame, 446 pd.merge( 447 measured_subset, 448 interpolated_subset, 449 on=dim_col, 450 how="outer", 451 suffixes=("_meas", "_interp"), 452 ), 453 ) 454 meas_series = cast(pd.Series, merged_df[f"{yield_col}_meas"]) 455 interp_series = cast(pd.Series, merged_df[f"{yield_col}_interp"]) 456 merged_df[yield_col] = cast(pd.Series, meas_series.combine_first(interp_series)) 457 df = cast( 458 pd.DataFrame, 459 merged_df.loc[:, [dim_col, yield_col]].sort_values(by=dim_col), 460 ) 461 462 # days missing from measurement → need prediction 463 days_to_predict = [day for day in grid if day not in df[dim_col].values] 464 465 predicted_rows: list[dict[str, float | int]] = [] 466 467 for day in days_to_predict: 468 # identify closest measured day 469 dim_series = cast(pd.Series, interpolated_df[dim_col]) 470 grid_vals = np.asarray(dim_series.to_numpy(dtype=float), dtype=float) 471 closest_idx = int(np.argmin(np.abs(grid_vals - float(day)))) 472 closest_day = int(dim_series.iloc[closest_idx]) 473 474 # extract mean milk yield from the standard lactation curve for the day to predict 475 expected_yield_grid_day = _curve_value(standard_lc_series, day) 476 expected_yield_measured_day = _curve_value(standard_lc_series, closest_day) 477 478 # calculate difference between measured and expected yield at closest measured day 479 diff = ( 480 interpolated_df.loc[interpolated_df[dim_col] == closest_day, yield_col].iloc[0] 481 - expected_yield_measured_day 482 ) 483 484 # calculate the correlation-based correction factor b* 485 # b* = corr(i,p) * std(p) / std(i) 486 pi = list(grid).index(closest_day) 487 qi = list(grid).index(day) 488 bpj = correlation_matrix.iloc[pi, qi] 489 std_q = std_per_grid_day[qi] 490 std_p = std_per_grid_day[pi] 491 b_star = 0.0 if std_p == 0 else float(bpj * std_q / std_p) 492 493 # predict the yield for the missing day 494 predicted_yield = expected_yield_grid_day + b_star * diff 495 predicted_rows.append({dim_col: int(day), yield_col: float(predicted_yield)}) 496 497 if predicted_rows: 498 df = pd.concat([df, pd.DataFrame(predicted_rows)], ignore_index=True) 499 500 # apply the test interval method to calculate total milk yield over 305 days 501 # sort the dataframe by days in milk and keep one value per day 502 df = df.drop_duplicates(subset=[dim_col], keep="last") 503 df = df.sort_values(by=dim_col) 504 # Trapezoidal contributions 505 df["width"] = df[dim_col].diff().shift(-1) 506 df["avg_yield"] = (df[yield_col] + df[yield_col].shift(-1)) / 2 507 df["trapezoid_area"] = df["width"] * df["avg_yield"] 508 509 trapezoid_values = np.asarray(pd.to_numeric(df["trapezoid_area"], errors="coerce"), dtype=float) 510 total_yield = float(np.nansum(trapezoid_values)) 511 512 return total_yield 513 514 515""" This method implements the original ISLC method as 516described in the paper by Wilmink et al. (1987). """ 517 518 519def ISLC_original_method_single_lactation( 520 df: pd.DataFrame, 521 standard_lc: pd.Series | npt.NDArray[np.float64], 522 correlation_matrix: pd.DataFrame, 523 std_per_grid_day: npt.NDArray[np.float64], 524) -> float: 525 """Estimate 305-day milk yield for a single interpolated lactation 526 from the original paper by Dr. Wilmink in 1987. 527 528 This function computes an estimated 305-day yield by combining three 529 components: known production from interpolated measurements, the 530 population mean for missing grid days (from ``standard_lc``), and a 531 correlation-based deviation correction derived from ``correlation_matrix``. 532 533 Args: 534 df: DataFrame containing at least the columns ``GridDay`` and 535 ``MilkYieldInterp`` (values already interpolated onto the grid). 536 standard_lc: Standard lactation curve values indexed by grid day. 537 correlation_matrix: Correlation coefficients between grid-day yields 538 (matrix-like, rows/columns ordered as the grid). 539 std_per_grid_day: 1-D array of standard deviations for each grid day. 540 541 Returns: 542 A float with the estimated 305-day milk yield. 543 544 Raises: 545 ValueError: if any measured day in ``df`` is not present in the 546 expected global ``grid``. 547 548 Notes: 549 - The routine assumes fixed recording intervals of 20 days, except 550 that the final interval (if day 290 is present) is 25 days. 551 - The implementation expects a global ``grid`` variable to be 552 defined and aligned with ``standard_lc`` and 553 ``std_per_grid_day``. 554 - The amount of estimated milk yields depends on the 555 availability of measured milk yields. 556 - Lactation yield is: 557 sum(known measurements (p) + estimated measurements (q)). 558 - In the implementation according to the CRV E2 document, 559 there should also be a correction factor for the difference between 560 the expected and actual complete lactation yield of the previous lactation. 561 However, this correction factor is not included in the current implementation 562 as it requires additional data (previous lactation yield) that is not always available. 563 """ 564 grid = GRID_DAYS 565 standard_lc_series = _curve_to_series(standard_lc) 566 567 # --- Validate that all measurements lie on the expected grid ------- 568 measured_days = df["GridDay"].values 569 if any(day not in grid for day in measured_days): 570 raise ValueError("At least one dim in the input df is not part of the grid.") 571 572 # --- Prepare basic components ------------------------------------- 573 df = df.sort_values("GridDay") 574 575 # days missing from measurement → need prediction 576 days_to_predict = [day for day in grid if day not in measured_days] 577 pred_idx = [list(grid).index(d) for d in days_to_predict] 578 579 # mean expected milk yield from standard curve 580 mean_lc = pd.Series([_curve_value(standard_lc_series, g) for g in grid], index=grid) 581 582 # --- Compute known production (sum of actual measurements) --------- 583 if 290 in measured_days: 584 # special last interval: 25 days 585 known_prod = df["MilkYieldInterp"][:-1].sum() * 20 + df["MilkYieldInterp"].iloc[-1] * 25 586 else: 587 known_prod = df["MilkYieldInterp"].sum() * 20 588 589 # --- Compute population mean for missing days ---------------------- 590 pop_mean_missing = mean_lc.loc[days_to_predict] 591 592 if 290 in pop_mean_missing.index: 593 population_mean = pop_mean_missing.iloc[:-1].sum() * 20 + pop_mean_missing.iloc[-1] * 25 594 else: 595 population_mean = pop_mean_missing.sum() * 20 596 597 # --- Compute correlation-based correction -------------------------- 598 days_to_predict_np = np.array(days_to_predict) 599 measured_days_np = np.array(measured_days) 600 601 # for each missing day: find closest measured day 602 closest_measured = [ 603 measured_days_np[np.argmin(np.abs(measured_days_np - g))] for g in days_to_predict_np 604 ] 605 closest_idx = [list(grid).index(d) for d in closest_measured] 606 607 b_star_list = [] 608 for pi, qi in zip(closest_idx, pred_idx): 609 bpj = correlation_matrix.iloc[pi, qi] 610 stdj = std_per_grid_day[qi] 611 stdp = std_per_grid_day[pi] 612 b_star_list.append(bpj * stdj / stdp) 613 614 # scale correction by interval lengths 615 if 290 in measured_days: 616 # last interval belongs to prediction group 617 correction_weighted = sum(b_star_list[:-1]) * 20 618 else: 619 correction_weighted = sum(b_star_list[:-1]) * 20 + b_star_list[-1] * 25 620 621 last_day = df["GridDay"].iloc[-1] 622 last_yield = df["MilkYieldInterp"].iloc[-1] 623 mean_last = mean_lc.loc[last_day] 624 625 correction = correction_weighted * (last_yield - mean_last) 626 627 # --- Final sum ----------------------------------------------------- 628 final_milk_yield = known_prod + population_mean + correction 629 return float(final_milk_yield) 630 631 632def ISLC_original_method( 633 df: pd.DataFrame, 634 days_in_milk_col: str | None = None, 635 milking_yield_col: str | None = None, 636 test_id_col: str | None = None, 637 default_test_id: int = 0, 638 standard_lc_305: pd.Series | npt.NDArray[np.float64] = STANDARD_CURVE, 639 correlation_matrix: pd.DataFrame = CORR_MATRIX, 640 std_per_grid_day: npt.NDArray[np.float64] = STDs, 641 fit_standard_lc_from_data: bool = False, 642 reference_df: pd.DataFrame | None = None, 643) -> pd.DataFrame: 644 """Compute estimated 305-day yields using the original grid-based ISLC variant 645 from the original paper by Dr. Wilmink in 1987. 646 647 The function groups standardized input by ``TestId``, interpolates to the 648 fixed GRID_DAYS grid, and applies :func:`ISLC_original_method` per lactation. 649 650 Args: 651 df: Input records with dim and milk yield columns. 652 days_in_milk_col: Name of dim column in ``df``. 653 milking_yield_col: Name of milk-yield column in ``df``. 654 test_id_col: Name of lactation identifier column in ``df``. 655 default_test_id: Fallback TestId when ``test_id_col`` is absent. 656 standard_lc_305: Standard lactation curve used for interpolation. 657 correlation_matrix: Correlation matrix over GRID_DAYS. 658 std_per_grid_day: Standard deviations per GRID_DAYS element. 659 fit_standard_lc_from_data: If True, refit standard curve and covariance 660 representation from ``reference_df`` before prediction. 661 reference_df: Reference population used when 662 ``fit_standard_lc_from_data=True``. The reference data is 663 standardized to ``DaysInMilk``/``MilkingYield`` and fit using 664 ``small_grid=True`` so correlation and standard-deviation assets are 665 aligned to ``GRID_DAYS``. 666 667 Returns: 668 DataFrame with columns ``LactationMilkYield`` and ``TestId``. 669 670 Raises: 671 ValueError: If required columns (DaysInMilk or MilkingYield) cannot be 672 found, or if ``fit_standard_lc_from_data=True`` and 673 ``reference_df`` is not provided. 674 675 Notes: 676 Records with dim > 305 are dropped before interpolation and scoring. 677 """ 678 # Standardize columns and filter dim <= 305 679 df = standardize_lactation_columns( 680 df, 681 days_in_milk_col=days_in_milk_col, 682 milking_yield_col=milking_yield_col, 683 test_id_col=test_id_col, 684 default_test_id=default_test_id, 685 max_dim=305, 686 ) 687 688 # Fit covariance/standard_lc if requested 689 if fit_standard_lc_from_data is True: 690 if reference_df is None: 691 raise ValueError("Provide reference_df to fit your own standard lactation curve.") 692 reference_df = standardize_lactation_columns( 693 reference_df, 694 days_in_milk_col=days_in_milk_col, 695 milking_yield_col=milking_yield_col, 696 test_id_col=test_id_col, 697 default_test_id=default_test_id, 698 max_dim=305, 699 ) 700 dim = reference_df["DaysInMilk"] 701 milk_yield = reference_df["MilkingYield"] 702 standard_full_lc_305 = fit_lactation_curve(dim, milkrecordings=milk_yield, model="wilmink") 703 standard_full_lc_305 = pd.Series(standard_full_lc_305) 704 705 # fit matrix 706 ( 707 correlation_matrix, 708 std_per_grid_day, 709 standard_curve_fitted, 710 ) = create_standard_lc_representation( 711 df=reference_df, 712 standard_lactation_curve=pd.Series(standard_full_lc_305), 713 # reference_df is standardized above, so fixed names are required here 714 days_in_milk_col="DaysInMilk", 715 milking_yield_col="MilkingYield", 716 interpolation_method=interpolation_standard_lc, 717 small_grid=True, 718 ) 719 720 # Align fitted curve with default internal convention (day 0 equals day 1). 721 standard_lc_305 = np.insert( 722 np.asarray(standard_curve_fitted, dtype=float), 723 0, 724 float(standard_curve_fitted.iloc[0]), 725 ) 726 rows: list[dict[str, Any]] = [] 727 for test_id, group in df.groupby("TestId", sort=False): 728 lactation = interpolation_standard_lc( 729 group, 730 days_in_milk_col="DaysInMilk", 731 milking_yield_col="MilkingYield", 732 standard_lc=standard_lc_305, 733 ) 734 if lactation.empty: 735 rows.append({"TestId": test_id, "305_milk_yield": np.nan}) 736 continue 737 738 cumulative_yield = ISLC_original_method_single_lactation( 739 df=lactation, 740 standard_lc=standard_lc_305, 741 correlation_matrix=correlation_matrix, 742 std_per_grid_day=std_per_grid_day, 743 ) 744 rows.append({"TestId": test_id, "LactationMilkYield": cumulative_yield}) 745 746 return pd.DataFrame(rows, columns=pd.Index(["TestId", "LactationMilkYield"])) 747 748 749""" 750Create your own standard lactation curve, correlation matrix, 751and standard deviations per grid day. 752 753step 1 interpolate to the days on the grid 754Based on the CRV E2 documents, interpolation is not linear and instead 755depends on the standard lactation curve. 756""" 757 758 759def interpolation_standard_lc( 760 group: pd.DataFrame, 761 days_in_milk_col: str, 762 milking_yield_col: str, 763 standard_lc: pd.Series | npt.NDArray[np.float64] | None = None, 764 small_grid: bool = False, 765) -> pd.DataFrame: 766 """Interpolate a single lactation onto the dim grid guided by a standard curve. 767 768 The function interpolates measured yields for one animal onto the 769 predefined grid of dim values. When a grid day coincides with a measured 770 dim the observed yield is used; otherwise the interpolation adjusts the 771 linear slope between neighboring measurements by the difference in the 772 standard curve, inspired by the CRV E2 approach. 773 774 The interpolation formula applied for a grid day ``gday`` between two 775 measured points (x1,y1) and (x2,y2) is:: 776 777 slope = ((y2 - y1) - (g2 - g1)) / (x2 - x1) 778 yi = gi + (slope * (gday - x1) + (y1 - g1)) 779 780 Args: 781 group: DataFrame with test-day records for a single animal. Must 782 contain columns named by ``days_in_milk_col`` and 783 ``milking_yield_col``. 784 days_in_milk_col: Name of the dim column in ``group``. 785 milking_yield_col: Name of the milk-yield column in ``group``. 786 standard_lc: A Series indexed by dim providing the expected yield on 787 each grid day; used to guide the interpolation shape. 788 small_grid: If True, interpolate on GRID_DAYS only; otherwise include 789 day 0 and day 305 in the interpolation target grid. 790 791 Returns: 792 A DataFrame with one row per interpolated grid day containing the 793 original identifying columns (from the first row of ``group``), plus 794 the columns ``GridDay`` and ``MilkYieldInterp``. 795 796 Notes: 797 - No interpolation is performed outside the range bounded by the 798 first and last measured dim for the lactation (those grid days are 799 skipped). 800 - No interpolation is performed for grid days where the right 801 neighboring measured dim is >= 305, because this lies outside the 802 intended standard-curve support. 803 - The implementation defines a local default ``grid`` of 804 [10, 30, ..., 290]. 805 806 807 """ 808 if small_grid: 809 grid = GRID_DAYS 810 else: 811 # add zero and 305 to the grid 812 grid = [0] + GRID_DAYS + [305] 813 814 if standard_lc is None: 815 raise ValueError("A standard lactation curve is required for interpolation_standard_lc.") 816 817 standard_lc_series = _curve_to_series(standard_lc) 818 819 # Sort and ensure unique dims 820 group = group.sort_values(days_in_milk_col).drop_duplicates(days_in_milk_col) 821 dims = group[days_in_milk_col].tolist() 822 823 rows = [] 824 825 # loop over the grid days 826 for gday in grid: 827 # --- CASE 1: Exact measured day --------------------------- 828 if gday in dims: 829 y_val = group.loc[group[days_in_milk_col] == gday, milking_yield_col].iloc[0] 830 831 row = group.iloc[0].to_dict() 832 row["GridDay"] = gday 833 row["MilkYieldInterp"] = float(y_val) 834 rows.append(row) 835 continue 836 837 # --- CASE 2: interpolate between measured days ------------- 838 before_df = cast(pd.DataFrame, group.loc[group[days_in_milk_col] < gday]) 839 after_df = cast(pd.DataFrame, group.loc[group[days_in_milk_col] > gday]) 840 before = before_df.tail(1) 841 after = after_df.head(1) 842 843 # CASE 3 No interpolation if grid day is outside the range of measured dim 844 if before.empty or after.empty: 845 continue 846 847 # CASE 4: No interpolation if the day after is day 305 or higher, 848 # as this is outside the range of the standard curve 849 if float(after.iloc[0][days_in_milk_col]) >= 305: 850 continue 851 852 x1 = float(before.iloc[0][days_in_milk_col]) 853 y1 = float(before.iloc[0][milking_yield_col]) 854 x2 = float(after.iloc[0][days_in_milk_col]) 855 y2 = float(after.iloc[0][milking_yield_col]) 856 857 # expected yields from standard lactation curve 858 g1 = _curve_value(standard_lc_series, int(x1)) 859 g2 = _curve_value(standard_lc_series, int(x2)) 860 gi = _curve_value(standard_lc_series, int(gday)) 861 862 # Wilmink-based interpolation formula 863 slope = ((y2 - y1) - (g2 - g1)) / (x2 - x1) 864 yi = gi + (slope * (gday - x1) + (y1 - g1)) 865 866 row = group.iloc[0].to_dict() 867 row["GridDay"] = gday 868 row["MilkYieldInterp"] = float(yi) 869 rows.append(row) 870 871 if not rows: 872 return pd.DataFrame( 873 columns=pd.Index([*group.columns.to_list(), "GridDay", "MilkYieldInterp"]) 874 ) 875 876 return pd.DataFrame(rows) 877 878 879def linear_interpd_all_to_grid( 880 group: pd.DataFrame, 881 days_in_milk_col: str, 882 milking_yield_col: str, 883 standard_lc: pd.Series | None = None, 884 small_grid: bool = False, 885) -> pd.DataFrame: 886 """Linearly interpolate all grid days for a lactation. 887 888 This helper uses linear interpolation (with extrapolation) to produce 889 milk-yield values for every grid day regardless of whether the grid day 890 lies between measured observations. 891 892 Args: 893 group: DataFrame containing measured dim and yield values for one 894 lactation. 895 days_in_milk_col: Name of the dim column. 896 milking_yield_col: Name of the milk-yield column. 897 small_grid: If True, interpolate on GRID_DAYS only; otherwise include 898 day 0 and day 305. 899 900 Returns: 901 A DataFrame with identifying columns copied from ``group``'s first 902 row and columns ``GridDay`` and ``MilkYieldInterp`` containing the 903 interpolated (or extrapolated) yields for every grid day. 904 """ 905 if small_grid: 906 grid = GRID_DAYS 907 else: 908 # add zero and 305 to the grid 909 grid = [0] + GRID_DAYS + [305] 910 911 group = group.sort_values(days_in_milk_col).drop_duplicates(subset=days_in_milk_col) 912 f = interp1d( 913 group[days_in_milk_col], 914 group[milking_yield_col], 915 kind="linear", 916 fill_value=cast(Any, "extrapolate"), 917 ) 918 919 base = { 920 col: group[col].iloc[0] 921 for col in group.columns 922 if col not in [days_in_milk_col, milking_yield_col] 923 } 924 base["GridDay"] = grid 925 base["MilkYieldInterp"] = f(grid) 926 927 return pd.DataFrame(base) 928 929 930# Create an interpolation function that only outputs grid days between two 931# milk measurements using linear interpolation. 932def linear_interpd_closest_to_grid( 933 group: pd.DataFrame, 934 days_in_milk_col: str, 935 milking_yield_col: str, 936 standard_lc: pd.Series | None = None, 937 small_grid: bool = False, 938) -> pd.DataFrame | None: 939 """Linearly interpolate grid days between measured observations. 940 941 This helper returns interpolated yields only for grid days that lie 942 between the first and last measured dim for the lactation. If no grid 943 days fall within the measured range the function returns ``None``. 944 945 Args: 946 group: DataFrame for a single lactation. 947 days_in_milk_col: Name of the dim column. 948 milking_yield_col: Name of the milk-yield column. 949 small_grid: If True, use GRID_DAYS only; otherwise include 950 day 0 and day 305. 951 952 Returns: 953 A DataFrame with identifying columns plus ``GridDay`` and 954 ``MilkYieldInterp``, or ``None`` if there are no grid days within 955 the measured range. 956 """ 957 if small_grid: 958 grid = GRID_DAYS 959 else: 960 # add zero and 305 to the grid 961 grid = [0] + GRID_DAYS + [305] 962 963 group = group.sort_values(days_in_milk_col).drop_duplicates(subset=days_in_milk_col) 964 965 # Find the range of interpolatable dim 966 min_dim = group[days_in_milk_col].min().item() 967 max_dim = group[days_in_milk_col].max().item() 968 grid_in_range = [g for g in grid if min_dim <= g <= max_dim] 969 970 # apply linear interpolation 971 if not grid_in_range: 972 return None 973 f = interp1d( 974 group[days_in_milk_col], 975 group[milking_yield_col], 976 kind="linear", 977 fill_value=cast(Any, np.nan), 978 ) 979 980 # create a new dataframe with the newly created columns 981 base = { 982 col: group[col].iloc[0] 983 for col in group.columns 984 if col not in [days_in_milk_col, milking_yield_col] 985 } 986 base["GridDay"] = grid_in_range 987 base["MilkYieldInterp"] = f(grid_in_range) 988 989 return pd.DataFrame(base) 990 991 992def create_standard_lc_representation( 993 df: pd.DataFrame, 994 standard_lactation_curve: pd.Series, 995 days_in_milk_col: str, 996 milking_yield_col: str, 997 interpolation_method: InterpolationMethod = interpolation_standard_lc, 998 lc_model: str = "Wilmink", 999 small_grid: bool = False, 1000) -> tuple[pd.DataFrame, npt.NDArray[np.float64], pd.Series]: 1001 """Create a standard lactation curve with correlation matrix from data. 1002 1003 This function estimates the correlation structure and standard deviations 1004 of milk yields across grid days, and refits a Wilmink lactation curve model to 1005 the interpolated data. The Wilmink model is hereby the default, 1006 but any model from the LC package can be used. 1007 The outputs can be used as inputs to the 1008 ``ISLC_method`` or ``ISLC_original`` functions for predicting 305-d yields. 1009 1010 The process standardizes yields per animal and computes row-wise 1011 (per-animal) statistics, then derives relationships across grid days. 1012 1013 Args: 1014 df: Input DataFrame containing test-day records. Must include a 1015 ``TestId`` column to identify unique lactations. Also requires 1016 columns specified by ``days_in_milk_col`` and ``milking_yield_col``. 1017 standard_lactation_curve: A Series providing a reference lactation 1018 curve (e.g., the fitted Wilmink curve on which to base 1019 interpolation). 1020 days_in_milk_col: Name of the column in ``df`` containing days in milk (dim). 1021 milking_yield_col: Name of the column in ``df`` containing measured 1022 milk yields. 1023 interpolation_method: An interpolation method conforming to 1024 ``InterpolationMethod`` protocol (default: ``interpolation_standard_lc``). 1025 Must be callable with signature 1026 (group, days_in_milk_col, milking_yield_col, standard_lc). 1027 lc_model: The lactation curve model to fit to the interpolated data. Default is "Wilmink". 1028 small_grid: If True, build representation on GRID_DAYS only. 1029 1030 Returns: 1031 A tuple of three elements: 1032 - corr (pd.DataFrame): Correlation matrix between grid-day yields. 1033 - std_per_grid_day (np.ndarray): Standard deviations of standardized 1034 yields per grid day. 1035 - standard_lactation_curve_grid (pd.Series): Refitted Wilmink model 1036 indexed by dim (1–305). 1037 1038 Notes: 1039 - Expects ``df`` to have a ``TestId`` column to group lactations. 1040 - Performs standardization per animal (row-wise), so output 1041 correlations and standard deviations reflect between-day variation 1042 within standardized animal profiles. 1043 - Uses ``fit_lactation_curve`` from the ``lactationcurve`` package 1044 with model='Wilmink' and fitting='frequentist'. 1045 However other models can be used by specifying the ``lc_model`` argument. 1046 """ 1047 1048 if "TestId" not in df.columns: 1049 raise ValueError("DataFrame must contain a 'TestId' column.") 1050 if days_in_milk_col not in df.columns or milking_yield_col not in df.columns: 1051 raise ValueError(f"Columns '{days_in_milk_col}' and '{milking_yield_col}' must be in df.") 1052 1053 interpolated_groups: list[pd.DataFrame] = [] 1054 for test_id, group in df.groupby("TestId", sort=False): 1055 try: 1056 interp_group = interpolation_method( 1057 group, 1058 days_in_milk_col=days_in_milk_col, 1059 milking_yield_col=milking_yield_col, 1060 standard_lc=standard_lactation_curve, 1061 small_grid=small_grid, 1062 ) 1063 except TypeError: 1064 # Backward compatibility for custom interpolation callables 1065 # that do not yet accept small_grid. 1066 interp_group = interpolation_method( 1067 group, 1068 days_in_milk_col=days_in_milk_col, 1069 milking_yield_col=milking_yield_col, 1070 standard_lc=standard_lactation_curve, 1071 ) 1072 if interp_group.empty: 1073 continue 1074 if "TestId" not in interp_group.columns: 1075 interp_group = interp_group.copy() 1076 interp_group["TestId"] = test_id 1077 interpolated_groups.append(interp_group) 1078 1079 if not interpolated_groups: 1080 raise ValueError("No interpolated rows were produced; cannot build representation.") 1081 1082 df_grid = pd.concat(interpolated_groups, ignore_index=True) 1083 1084 # define Znp 1085 # pivot df to make GridDay the columns 1086 # Z should be the unscaled pivot table (TestId × GridDay) 1087 Z = df_grid.pivot(index="TestId", columns="GridDay", values="MilkYieldInterp") 1088 representation_grid = GRID_DAYS if small_grid else [0] + GRID_DAYS + [305] 1089 Z = Z.reindex(columns=representation_grid) 1090 1091 # Standardize records per cow (so each row has mean=0, std=1) 1092 Z_std = (Z.sub(Z.mean(axis=1), axis=0)).div(Z.std(axis=1), axis=0) 1093 1094 # Convert to NumPy array 1095 Znp = Z_std.to_numpy() 1096 1097 # calculate correlation matrix 1098 corr = pd.DataFrame(Znp, columns=Z.columns).corr() 1099 corr = corr.reindex(index=Z.columns, columns=Z.columns) 1100 corr_values = np.nan_to_num(corr.to_numpy(dtype=float), nan=0.0) 1101 np.fill_diagonal(corr_values, 1.0) 1102 corr = pd.DataFrame(corr_values, index=Z.columns, columns=Z.columns) 1103 1104 # calculate standard deviations for each grid day from the Znp matrix 1105 std_per_grid_day = np.nan_to_num( 1106 np.nanstd(Znp, axis=0), 1107 nan=0.0, 1108 posinf=0.0, 1109 neginf=0.0, 1110 ) 1111 1112 # fit Wilmink model to get mean values and std for each cow 1113 standard_lactation_curve_grid = pd.Series( 1114 fit_lactation_curve( 1115 df_grid["GridDay"].values, 1116 df_grid["MilkYieldInterp"].values, 1117 model=lc_model, 1118 fitting="frequentist", 1119 ), 1120 index=range(1, 306), 1121 ) 1122 return corr, std_per_grid_day, standard_lactation_curve_grid 1123 1124 1125def _set_doc_signatures() -> None: 1126 """Override displayed defaults in docs without changing runtime behavior.""" 1127 doc_defaults = { 1128 "standard_lc_305": _DOC_STANDARD_CURVE, 1129 "correlation_matrix": _DOC_CORR_MATRIX, 1130 "std_per_grid_day": _DOC_STDS, 1131 } 1132 1133 for func in (ISLC_method, ISLC_original_method): 1134 signature = inspect.signature(func) 1135 params = [ 1136 param.replace(default=doc_defaults[param.name]) if param.name in doc_defaults else param 1137 for param in signature.parameters.values() 1138 ] 1139 func.__signature__ = signature.replace(parameters=params) 1140 1141 1142_set_doc_signatures()
ISLC takes information from a standard lactation curve. Ideally this lactation curve is fitted to the same population as the data to be scored. To make sure this method can be used out of the box, we provide a default standard lactation curve, correlation matrix and standard deviations per grid day that were fitted on a group of cows in the Benelux. They are stored in the data directory and can be retrieved using the following code:
The following functions are mostly internal functions that are used by the ISLC method. They are not meant to be used directly by the user, but they can be useful for understanding the method and for debugging.
205class InterpolationMethod(Protocol): 206 """Protocol for milk-yield interpolation methods. 207 208 Defines the signature expected by functions that interpolate test-day 209 yields onto a predefined dim grid. 210 """ 211 212 def __call__( 213 self, 214 group: pd.DataFrame, 215 days_in_milk_col: str, 216 milking_yield_col: str, 217 standard_lc: pd.Series | npt.NDArray[np.float64] | None = None, 218 small_grid: bool = False, 219 ) -> pd.DataFrame: 220 """Interpolate yields for a single lactation onto the dim grid. 221 222 Args: 223 group: Test-day records for a single animal. 224 days_in_milk_col: Column name containing days in milk (dim). 225 milking_yield_col: Column name containing milk yields. 226 standard_lc: Optional standard lactation curve to guide 227 interpolation (method-dependent). 228 small_grid: If True, interpolate only on GRID_DAYS; 229 otherwise use [0] + GRID_DAYS + [305]. 230 231 Returns: 232 A DataFrame with interpolated yields, typically including 233 columns ``GridDay`` and ``MilkYieldInterp``. 234 """ 235 ...
Protocol for milk-yield interpolation methods.
Defines the signature expected by functions that interpolate test-day yields onto a predefined dim grid.
1771def _no_init_or_replace_init(self, *args, **kwargs): 1772 cls = type(self) 1773 1774 if cls._is_protocol: 1775 raise TypeError('Protocols cannot be instantiated') 1776 1777 # Already using a custom `__init__`. No need to calculate correct 1778 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1779 if cls.__init__ is not _no_init_or_replace_init: 1780 return 1781 1782 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1783 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1784 # searches for a proper new `__init__` in the MRO. The new `__init__` 1785 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1786 # instantiation of the protocol subclass will thus use the new 1787 # `__init__` and no longer call `_no_init_or_replace_init`. 1788 for base in cls.__mro__: 1789 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1790 if init is not _no_init_or_replace_init: 1791 cls.__init__ = init 1792 break 1793 else: 1794 # should not happen 1795 cls.__init__ = object.__init__ 1796 1797 cls.__init__(self, *args, **kwargs)
244def ISLC_method( 245 df: pd.DataFrame, 246 days_in_milk_col: str | None = None, 247 milking_yield_col: str | None = None, 248 test_id_col: str | None = None, 249 default_test_id: int = 0, 250 standard_lc_305: pd.Series | npt.NDArray[np.float64] = STANDARD_CURVE, 251 correlation_matrix: pd.DataFrame = CORR_MATRIX, 252 std_per_grid_day: npt.NDArray[np.float64] = STDs, 253 max_dim: int | str = 305, 254 fit_standard_lc_from_data: bool = False, 255 reference_df: pd.DataFrame | None = None, 256) -> pd.DataFrame: 257 """Estimate cumulative lactation yield per TestId using ISLC. 258 259 This variant applies :func:`ISLC_method` to standardized lactation records. 260 By default it uses the package-provided standard curve, correlation matrix, 261 and per-grid day standard deviations. Optionally, these assets can be refit 262 from a reference dataset by providing a pandas dataframe at 'reference_df =' 263 when ``fit_standard_lc_from_data`` is True. 264 Alternative for customization is to set standard_lc_305, 265 correlation_matrix, and std_per_grid_day directly. 266 267 Args: 268 df: Input test-day records. 269 days_in_milk_col: Name of dim column in ``df``. 270 milking_yield_col: Name of milk-yield column in ``df``. 271 test_id_col: Name of lactation identifier column in ``df``. 272 default_test_id: Fallback TestId value when ``test_id_col`` is absent. 273 standard_lc_305: Standard lactation curve values used by ISLC. 274 correlation_matrix: Correlation matrix aligned with ISLC grid. 275 std_per_grid_day: Standard deviations aligned with ISLC grid. 276 max_dim: Maximum dim to include 277 (or ``"max"`` so highest test day dim is considered the final lactation day). 278 fit_standard_lc_from_data: If True, fit representation from ``reference_df``. 279 reference_df: Reference records used when fitting curve and covariance. 280 281 Returns: 282 DataFrame with columns ``TestId`` and ``LactationMilkYield``. 283 284 Raises: 285 ValueError: If required columns are missing or fit mode has no reference data. 286 """ 287 # Standardize columns and filter dim <= 305 288 df = standardize_lactation_columns( 289 df, 290 days_in_milk_col=days_in_milk_col, 291 milking_yield_col=milking_yield_col, 292 test_id_col=test_id_col, 293 default_test_id=default_test_id, 294 max_dim=max_dim, 295 ) 296 297 # Fit covariance/standard_lc if requested 298 if fit_standard_lc_from_data is True: 299 if reference_df is None: 300 raise ValueError("Provide reference_df to fit your own standard lactation curve.") 301 reference_df = standardize_lactation_columns( 302 reference_df, 303 days_in_milk_col=days_in_milk_col, 304 milking_yield_col=milking_yield_col, 305 test_id_col=test_id_col, 306 default_test_id=default_test_id, 307 max_dim=305, 308 ) 309 dim = reference_df["DaysInMilk"] 310 milk_yield = reference_df["MilkingYield"] 311 standard_full_lc_305 = fit_lactation_curve(dim, milkrecordings=milk_yield, model="wilmink") 312 # convert to pandas series 313 standard_full_lc_305 = pd.Series(standard_full_lc_305) 314 315 # fit matrix 316 ( 317 correlation_matrix, 318 std_per_grid_day, 319 standard_curve_fitted, 320 ) = create_standard_lc_representation( 321 df=reference_df, 322 standard_lactation_curve=pd.Series(standard_full_lc_305), 323 # reference_df is standardized above, so fixed names are required here 324 days_in_milk_col="DaysInMilk", 325 milking_yield_col="MilkingYield", 326 interpolation_method=interpolation_standard_lc, 327 small_grid=False, 328 ) 329 330 # Align fitted curve with default internal convention (day 0 equals day 1). 331 standard_lc_305 = np.insert( 332 np.asarray(standard_curve_fitted, dtype=float), 333 0, 334 float(standard_curve_fitted.iloc[0]), 335 ) 336 337 rows: list[dict[str, Any]] = [] 338 for test_id, group in df.groupby("TestId", sort=False): 339 if group.empty: 340 rows.append({"TestId": test_id, "LactationMilkYield": np.nan}) 341 continue 342 343 try: 344 cumulative_yield = ISLC_method_single_lactation( 345 df=group, 346 standard_lc=standard_lc_305, 347 correlation_matrix=correlation_matrix, 348 std_per_grid_day=std_per_grid_day, 349 days_in_milk_col="DaysInMilk", 350 milking_yield_col="MilkingYield", 351 max_dim=max_dim, 352 ) 353 except ValueError: 354 cumulative_yield = np.nan 355 356 rows.append({"TestId": test_id, "LactationMilkYield": cumulative_yield}) 357 358 return pd.DataFrame(rows, columns=pd.Index(["TestId", "LactationMilkYield"]))
Estimate cumulative lactation yield per TestId using ISLC.
This variant applies ISLC_method() to standardized lactation records.
By default it uses the package-provided standard curve, correlation matrix,
and per-grid day standard deviations. Optionally, these assets can be refit
from a reference dataset by providing a pandas dataframe at 'reference_df ='
when fit_standard_lc_from_data is True.
Alternative for customization is to set standard_lc_305,
correlation_matrix, and std_per_grid_day directly.
Arguments:
- df: Input test-day records.
- days_in_milk_col: Name of dim column in
df. - milking_yield_col: Name of milk-yield column in
df. - test_id_col: Name of lactation identifier column in
df. - default_test_id: Fallback TestId value when
test_id_colis absent. - standard_lc_305: Standard lactation curve values used by ISLC.
- correlation_matrix: Correlation matrix aligned with ISLC grid.
- std_per_grid_day: Standard deviations aligned with ISLC grid.
- max_dim: Maximum dim to include
(or
"max"so highest test day dim is considered the final lactation day). - fit_standard_lc_from_data: If True, fit representation from
reference_df. - reference_df: Reference records used when fitting curve and covariance.
Returns:
DataFrame with columns
TestIdandLactationMilkYield.
Raises:
- ValueError: If required columns are missing or fit mode has no reference data.
366def ISLC_method_single_lactation( 367 df: pd.DataFrame, 368 standard_lc: pd.Series | npt.NDArray[np.float64], 369 correlation_matrix: pd.DataFrame, 370 std_per_grid_day: npt.NDArray[np.float64], 371 days_in_milk_col: str = "DaysInMilk", 372 milking_yield_col: str = "MilkingYield", 373 max_dim: int | str = 305, 374) -> float: 375 """Estimate total lactation yield by predicting missing grid days, then integrating. 376 377 The method fills missing grid-day yields with the ICAR-style relation: 378 379 yp = gp + b* (yi - gi) 380 381 where for each missing day p, the nearest measured day i is used and 382 b* = corr(i,p) * std(p) / std(i). The resulting complete grid profile is 383 integrated with the test-interval style weighting used elsewhere in this 384 package. 385 386 Notes: 387 The integration is performed over the days present after merging 388 measured and predicted points. If the input contains dim beyond 305, 389 total yield can reflect that extended horizon if ``max_dim`` is set accordingly. 390 """ 391 dim_col = days_in_milk_col 392 yield_col = milking_yield_col 393 394 # Use the requested horizon, or the last observed day for ``"max"``. 395 if max_dim == "max": 396 observed_dim = df[dim_col].to_numpy(dtype=float) 397 calculation_end = int(np.max(observed_dim)) 398 else: 399 calculation_end = int(max_dim) 400 401 grid = _calculation_grid(calculation_end) 402 required_asset_size = len(grid) 403 std_size = np.asarray(std_per_grid_day).shape[0] 404 if std_size < required_asset_size: 405 raise ValueError( 406 "std_per_grid_day must contain one value per calculation-grid position " 407 f"(expected at least {required_asset_size}, got {std_size})." 408 ) 409 if ( 410 correlation_matrix.shape[0] < required_asset_size 411 or correlation_matrix.shape[1] < required_asset_size 412 ): 413 raise ValueError( 414 "correlation_matrix must contain one row and column per calculation-grid position " 415 f"(expected at least {required_asset_size}, got {correlation_matrix.shape})." 416 ) 417 418 standard_lc_series = _curve_to_series(standard_lc) 419 420 # Extract the measured days 421 measured_days = df[dim_col].to_numpy() 422 if measured_days.size == 0: 423 raise ValueError("Input df must contain at least one measured day.") 424 425 # interpolate the measured days to the grid using the standard lactation curve 426 interpolated_df = interpolation_standard_lc( 427 group=df, 428 days_in_milk_col=dim_col, 429 milking_yield_col=yield_col, 430 standard_lc=standard_lc_series, 431 ) 432 433 # drop unnecessary columns 434 interpolated_df = interpolated_df.drop(columns=[dim_col, yield_col]) 435 436 # rename grid colum 437 interpolated_df = interpolated_df.rename( 438 columns={"GridDay": dim_col, "MilkYieldInterp": yield_col} 439 )[[dim_col, yield_col]] 440 441 measured_subset = cast(pd.DataFrame, df.loc[:, [dim_col, yield_col]]) 442 interpolated_subset = cast(pd.DataFrame, interpolated_df.loc[:, [dim_col, yield_col]]) 443 444 # join the interpolated values with the original measurements, keeping all measurements 445 merged_df = cast( 446 pd.DataFrame, 447 pd.merge( 448 measured_subset, 449 interpolated_subset, 450 on=dim_col, 451 how="outer", 452 suffixes=("_meas", "_interp"), 453 ), 454 ) 455 meas_series = cast(pd.Series, merged_df[f"{yield_col}_meas"]) 456 interp_series = cast(pd.Series, merged_df[f"{yield_col}_interp"]) 457 merged_df[yield_col] = cast(pd.Series, meas_series.combine_first(interp_series)) 458 df = cast( 459 pd.DataFrame, 460 merged_df.loc[:, [dim_col, yield_col]].sort_values(by=dim_col), 461 ) 462 463 # days missing from measurement → need prediction 464 days_to_predict = [day for day in grid if day not in df[dim_col].values] 465 466 predicted_rows: list[dict[str, float | int]] = [] 467 468 for day in days_to_predict: 469 # identify closest measured day 470 dim_series = cast(pd.Series, interpolated_df[dim_col]) 471 grid_vals = np.asarray(dim_series.to_numpy(dtype=float), dtype=float) 472 closest_idx = int(np.argmin(np.abs(grid_vals - float(day)))) 473 closest_day = int(dim_series.iloc[closest_idx]) 474 475 # extract mean milk yield from the standard lactation curve for the day to predict 476 expected_yield_grid_day = _curve_value(standard_lc_series, day) 477 expected_yield_measured_day = _curve_value(standard_lc_series, closest_day) 478 479 # calculate difference between measured and expected yield at closest measured day 480 diff = ( 481 interpolated_df.loc[interpolated_df[dim_col] == closest_day, yield_col].iloc[0] 482 - expected_yield_measured_day 483 ) 484 485 # calculate the correlation-based correction factor b* 486 # b* = corr(i,p) * std(p) / std(i) 487 pi = list(grid).index(closest_day) 488 qi = list(grid).index(day) 489 bpj = correlation_matrix.iloc[pi, qi] 490 std_q = std_per_grid_day[qi] 491 std_p = std_per_grid_day[pi] 492 b_star = 0.0 if std_p == 0 else float(bpj * std_q / std_p) 493 494 # predict the yield for the missing day 495 predicted_yield = expected_yield_grid_day + b_star * diff 496 predicted_rows.append({dim_col: int(day), yield_col: float(predicted_yield)}) 497 498 if predicted_rows: 499 df = pd.concat([df, pd.DataFrame(predicted_rows)], ignore_index=True) 500 501 # apply the test interval method to calculate total milk yield over 305 days 502 # sort the dataframe by days in milk and keep one value per day 503 df = df.drop_duplicates(subset=[dim_col], keep="last") 504 df = df.sort_values(by=dim_col) 505 # Trapezoidal contributions 506 df["width"] = df[dim_col].diff().shift(-1) 507 df["avg_yield"] = (df[yield_col] + df[yield_col].shift(-1)) / 2 508 df["trapezoid_area"] = df["width"] * df["avg_yield"] 509 510 trapezoid_values = np.asarray(pd.to_numeric(df["trapezoid_area"], errors="coerce"), dtype=float) 511 total_yield = float(np.nansum(trapezoid_values)) 512 513 return total_yield
Estimate total lactation yield by predicting missing grid days, then integrating.
The method fills missing grid-day yields with the ICAR-style relation:
yp = gp + b* (yi - gi)
where for each missing day p, the nearest measured day i is used and
b* = corr(i,p) * std(p) / std(i). The resulting complete grid profile is
integrated with the test-interval style weighting used elsewhere in this
package.
Notes:
The integration is performed over the days present after merging measured and predicted points. If the input contains dim beyond 305, total yield can reflect that extended horizon if
max_dimis set accordingly.
520def ISLC_original_method_single_lactation( 521 df: pd.DataFrame, 522 standard_lc: pd.Series | npt.NDArray[np.float64], 523 correlation_matrix: pd.DataFrame, 524 std_per_grid_day: npt.NDArray[np.float64], 525) -> float: 526 """Estimate 305-day milk yield for a single interpolated lactation 527 from the original paper by Dr. Wilmink in 1987. 528 529 This function computes an estimated 305-day yield by combining three 530 components: known production from interpolated measurements, the 531 population mean for missing grid days (from ``standard_lc``), and a 532 correlation-based deviation correction derived from ``correlation_matrix``. 533 534 Args: 535 df: DataFrame containing at least the columns ``GridDay`` and 536 ``MilkYieldInterp`` (values already interpolated onto the grid). 537 standard_lc: Standard lactation curve values indexed by grid day. 538 correlation_matrix: Correlation coefficients between grid-day yields 539 (matrix-like, rows/columns ordered as the grid). 540 std_per_grid_day: 1-D array of standard deviations for each grid day. 541 542 Returns: 543 A float with the estimated 305-day milk yield. 544 545 Raises: 546 ValueError: if any measured day in ``df`` is not present in the 547 expected global ``grid``. 548 549 Notes: 550 - The routine assumes fixed recording intervals of 20 days, except 551 that the final interval (if day 290 is present) is 25 days. 552 - The implementation expects a global ``grid`` variable to be 553 defined and aligned with ``standard_lc`` and 554 ``std_per_grid_day``. 555 - The amount of estimated milk yields depends on the 556 availability of measured milk yields. 557 - Lactation yield is: 558 sum(known measurements (p) + estimated measurements (q)). 559 - In the implementation according to the CRV E2 document, 560 there should also be a correction factor for the difference between 561 the expected and actual complete lactation yield of the previous lactation. 562 However, this correction factor is not included in the current implementation 563 as it requires additional data (previous lactation yield) that is not always available. 564 """ 565 grid = GRID_DAYS 566 standard_lc_series = _curve_to_series(standard_lc) 567 568 # --- Validate that all measurements lie on the expected grid ------- 569 measured_days = df["GridDay"].values 570 if any(day not in grid for day in measured_days): 571 raise ValueError("At least one dim in the input df is not part of the grid.") 572 573 # --- Prepare basic components ------------------------------------- 574 df = df.sort_values("GridDay") 575 576 # days missing from measurement → need prediction 577 days_to_predict = [day for day in grid if day not in measured_days] 578 pred_idx = [list(grid).index(d) for d in days_to_predict] 579 580 # mean expected milk yield from standard curve 581 mean_lc = pd.Series([_curve_value(standard_lc_series, g) for g in grid], index=grid) 582 583 # --- Compute known production (sum of actual measurements) --------- 584 if 290 in measured_days: 585 # special last interval: 25 days 586 known_prod = df["MilkYieldInterp"][:-1].sum() * 20 + df["MilkYieldInterp"].iloc[-1] * 25 587 else: 588 known_prod = df["MilkYieldInterp"].sum() * 20 589 590 # --- Compute population mean for missing days ---------------------- 591 pop_mean_missing = mean_lc.loc[days_to_predict] 592 593 if 290 in pop_mean_missing.index: 594 population_mean = pop_mean_missing.iloc[:-1].sum() * 20 + pop_mean_missing.iloc[-1] * 25 595 else: 596 population_mean = pop_mean_missing.sum() * 20 597 598 # --- Compute correlation-based correction -------------------------- 599 days_to_predict_np = np.array(days_to_predict) 600 measured_days_np = np.array(measured_days) 601 602 # for each missing day: find closest measured day 603 closest_measured = [ 604 measured_days_np[np.argmin(np.abs(measured_days_np - g))] for g in days_to_predict_np 605 ] 606 closest_idx = [list(grid).index(d) for d in closest_measured] 607 608 b_star_list = [] 609 for pi, qi in zip(closest_idx, pred_idx): 610 bpj = correlation_matrix.iloc[pi, qi] 611 stdj = std_per_grid_day[qi] 612 stdp = std_per_grid_day[pi] 613 b_star_list.append(bpj * stdj / stdp) 614 615 # scale correction by interval lengths 616 if 290 in measured_days: 617 # last interval belongs to prediction group 618 correction_weighted = sum(b_star_list[:-1]) * 20 619 else: 620 correction_weighted = sum(b_star_list[:-1]) * 20 + b_star_list[-1] * 25 621 622 last_day = df["GridDay"].iloc[-1] 623 last_yield = df["MilkYieldInterp"].iloc[-1] 624 mean_last = mean_lc.loc[last_day] 625 626 correction = correction_weighted * (last_yield - mean_last) 627 628 # --- Final sum ----------------------------------------------------- 629 final_milk_yield = known_prod + population_mean + correction 630 return float(final_milk_yield)
Estimate 305-day milk yield for a single interpolated lactation from the original paper by Dr. Wilmink in 1987.
This function computes an estimated 305-day yield by combining three
components: known production from interpolated measurements, the
population mean for missing grid days (from standard_lc), and a
correlation-based deviation correction derived from correlation_matrix.
Arguments:
- df: DataFrame containing at least the columns
GridDayandMilkYieldInterp(values already interpolated onto the grid). - standard_lc: Standard lactation curve values indexed by grid day.
- correlation_matrix: Correlation coefficients between grid-day yields (matrix-like, rows/columns ordered as the grid).
- std_per_grid_day: 1-D array of standard deviations for each grid day.
Returns:
A float with the estimated 305-day milk yield.
Raises:
- ValueError: if any measured day in
dfis not present in the expected globalgrid.
Notes:
- The routine assumes fixed recording intervals of 20 days, except that the final interval (if day 290 is present) is 25 days.
- The implementation expects a global
gridvariable to be defined and aligned withstandard_lcandstd_per_grid_day.- The amount of estimated milk yields depends on the availability of measured milk yields.
- Lactation yield is: sum(known measurements (p) + estimated measurements (q)).
- In the implementation according to the CRV E2 document, there should also be a correction factor for the difference between the expected and actual complete lactation yield of the previous lactation. However, this correction factor is not included in the current implementation as it requires additional data (previous lactation yield) that is not always available.
633def ISLC_original_method( 634 df: pd.DataFrame, 635 days_in_milk_col: str | None = None, 636 milking_yield_col: str | None = None, 637 test_id_col: str | None = None, 638 default_test_id: int = 0, 639 standard_lc_305: pd.Series | npt.NDArray[np.float64] = STANDARD_CURVE, 640 correlation_matrix: pd.DataFrame = CORR_MATRIX, 641 std_per_grid_day: npt.NDArray[np.float64] = STDs, 642 fit_standard_lc_from_data: bool = False, 643 reference_df: pd.DataFrame | None = None, 644) -> pd.DataFrame: 645 """Compute estimated 305-day yields using the original grid-based ISLC variant 646 from the original paper by Dr. Wilmink in 1987. 647 648 The function groups standardized input by ``TestId``, interpolates to the 649 fixed GRID_DAYS grid, and applies :func:`ISLC_original_method` per lactation. 650 651 Args: 652 df: Input records with dim and milk yield columns. 653 days_in_milk_col: Name of dim column in ``df``. 654 milking_yield_col: Name of milk-yield column in ``df``. 655 test_id_col: Name of lactation identifier column in ``df``. 656 default_test_id: Fallback TestId when ``test_id_col`` is absent. 657 standard_lc_305: Standard lactation curve used for interpolation. 658 correlation_matrix: Correlation matrix over GRID_DAYS. 659 std_per_grid_day: Standard deviations per GRID_DAYS element. 660 fit_standard_lc_from_data: If True, refit standard curve and covariance 661 representation from ``reference_df`` before prediction. 662 reference_df: Reference population used when 663 ``fit_standard_lc_from_data=True``. The reference data is 664 standardized to ``DaysInMilk``/``MilkingYield`` and fit using 665 ``small_grid=True`` so correlation and standard-deviation assets are 666 aligned to ``GRID_DAYS``. 667 668 Returns: 669 DataFrame with columns ``LactationMilkYield`` and ``TestId``. 670 671 Raises: 672 ValueError: If required columns (DaysInMilk or MilkingYield) cannot be 673 found, or if ``fit_standard_lc_from_data=True`` and 674 ``reference_df`` is not provided. 675 676 Notes: 677 Records with dim > 305 are dropped before interpolation and scoring. 678 """ 679 # Standardize columns and filter dim <= 305 680 df = standardize_lactation_columns( 681 df, 682 days_in_milk_col=days_in_milk_col, 683 milking_yield_col=milking_yield_col, 684 test_id_col=test_id_col, 685 default_test_id=default_test_id, 686 max_dim=305, 687 ) 688 689 # Fit covariance/standard_lc if requested 690 if fit_standard_lc_from_data is True: 691 if reference_df is None: 692 raise ValueError("Provide reference_df to fit your own standard lactation curve.") 693 reference_df = standardize_lactation_columns( 694 reference_df, 695 days_in_milk_col=days_in_milk_col, 696 milking_yield_col=milking_yield_col, 697 test_id_col=test_id_col, 698 default_test_id=default_test_id, 699 max_dim=305, 700 ) 701 dim = reference_df["DaysInMilk"] 702 milk_yield = reference_df["MilkingYield"] 703 standard_full_lc_305 = fit_lactation_curve(dim, milkrecordings=milk_yield, model="wilmink") 704 standard_full_lc_305 = pd.Series(standard_full_lc_305) 705 706 # fit matrix 707 ( 708 correlation_matrix, 709 std_per_grid_day, 710 standard_curve_fitted, 711 ) = create_standard_lc_representation( 712 df=reference_df, 713 standard_lactation_curve=pd.Series(standard_full_lc_305), 714 # reference_df is standardized above, so fixed names are required here 715 days_in_milk_col="DaysInMilk", 716 milking_yield_col="MilkingYield", 717 interpolation_method=interpolation_standard_lc, 718 small_grid=True, 719 ) 720 721 # Align fitted curve with default internal convention (day 0 equals day 1). 722 standard_lc_305 = np.insert( 723 np.asarray(standard_curve_fitted, dtype=float), 724 0, 725 float(standard_curve_fitted.iloc[0]), 726 ) 727 rows: list[dict[str, Any]] = [] 728 for test_id, group in df.groupby("TestId", sort=False): 729 lactation = interpolation_standard_lc( 730 group, 731 days_in_milk_col="DaysInMilk", 732 milking_yield_col="MilkingYield", 733 standard_lc=standard_lc_305, 734 ) 735 if lactation.empty: 736 rows.append({"TestId": test_id, "305_milk_yield": np.nan}) 737 continue 738 739 cumulative_yield = ISLC_original_method_single_lactation( 740 df=lactation, 741 standard_lc=standard_lc_305, 742 correlation_matrix=correlation_matrix, 743 std_per_grid_day=std_per_grid_day, 744 ) 745 rows.append({"TestId": test_id, "LactationMilkYield": cumulative_yield}) 746 747 return pd.DataFrame(rows, columns=pd.Index(["TestId", "LactationMilkYield"]))
Compute estimated 305-day yields using the original grid-based ISLC variant from the original paper by Dr. Wilmink in 1987.
The function groups standardized input by TestId, interpolates to the
fixed GRID_DAYS grid, and applies ISLC_original_method() per lactation.
Arguments:
- df: Input records with dim and milk yield columns.
- days_in_milk_col: Name of dim column in
df. - milking_yield_col: Name of milk-yield column in
df. - test_id_col: Name of lactation identifier column in
df. - default_test_id: Fallback TestId when
test_id_colis absent. - standard_lc_305: Standard lactation curve used for interpolation.
- correlation_matrix: Correlation matrix over GRID_DAYS.
- std_per_grid_day: Standard deviations per GRID_DAYS element.
- fit_standard_lc_from_data: If True, refit standard curve and covariance
representation from
reference_dfbefore prediction. - reference_df: Reference population used when
fit_standard_lc_from_data=True. The reference data is standardized toDaysInMilk/MilkingYieldand fit usingsmall_grid=Trueso correlation and standard-deviation assets are aligned toGRID_DAYS.
Returns:
DataFrame with columns
LactationMilkYieldandTestId.
Raises:
- ValueError: If required columns (DaysInMilk or MilkingYield) cannot be
found, or if
fit_standard_lc_from_data=Trueandreference_dfis not provided.
Notes:
Records with dim > 305 are dropped before interpolation and scoring.
760def interpolation_standard_lc( 761 group: pd.DataFrame, 762 days_in_milk_col: str, 763 milking_yield_col: str, 764 standard_lc: pd.Series | npt.NDArray[np.float64] | None = None, 765 small_grid: bool = False, 766) -> pd.DataFrame: 767 """Interpolate a single lactation onto the dim grid guided by a standard curve. 768 769 The function interpolates measured yields for one animal onto the 770 predefined grid of dim values. When a grid day coincides with a measured 771 dim the observed yield is used; otherwise the interpolation adjusts the 772 linear slope between neighboring measurements by the difference in the 773 standard curve, inspired by the CRV E2 approach. 774 775 The interpolation formula applied for a grid day ``gday`` between two 776 measured points (x1,y1) and (x2,y2) is:: 777 778 slope = ((y2 - y1) - (g2 - g1)) / (x2 - x1) 779 yi = gi + (slope * (gday - x1) + (y1 - g1)) 780 781 Args: 782 group: DataFrame with test-day records for a single animal. Must 783 contain columns named by ``days_in_milk_col`` and 784 ``milking_yield_col``. 785 days_in_milk_col: Name of the dim column in ``group``. 786 milking_yield_col: Name of the milk-yield column in ``group``. 787 standard_lc: A Series indexed by dim providing the expected yield on 788 each grid day; used to guide the interpolation shape. 789 small_grid: If True, interpolate on GRID_DAYS only; otherwise include 790 day 0 and day 305 in the interpolation target grid. 791 792 Returns: 793 A DataFrame with one row per interpolated grid day containing the 794 original identifying columns (from the first row of ``group``), plus 795 the columns ``GridDay`` and ``MilkYieldInterp``. 796 797 Notes: 798 - No interpolation is performed outside the range bounded by the 799 first and last measured dim for the lactation (those grid days are 800 skipped). 801 - No interpolation is performed for grid days where the right 802 neighboring measured dim is >= 305, because this lies outside the 803 intended standard-curve support. 804 - The implementation defines a local default ``grid`` of 805 [10, 30, ..., 290]. 806 807 808 """ 809 if small_grid: 810 grid = GRID_DAYS 811 else: 812 # add zero and 305 to the grid 813 grid = [0] + GRID_DAYS + [305] 814 815 if standard_lc is None: 816 raise ValueError("A standard lactation curve is required for interpolation_standard_lc.") 817 818 standard_lc_series = _curve_to_series(standard_lc) 819 820 # Sort and ensure unique dims 821 group = group.sort_values(days_in_milk_col).drop_duplicates(days_in_milk_col) 822 dims = group[days_in_milk_col].tolist() 823 824 rows = [] 825 826 # loop over the grid days 827 for gday in grid: 828 # --- CASE 1: Exact measured day --------------------------- 829 if gday in dims: 830 y_val = group.loc[group[days_in_milk_col] == gday, milking_yield_col].iloc[0] 831 832 row = group.iloc[0].to_dict() 833 row["GridDay"] = gday 834 row["MilkYieldInterp"] = float(y_val) 835 rows.append(row) 836 continue 837 838 # --- CASE 2: interpolate between measured days ------------- 839 before_df = cast(pd.DataFrame, group.loc[group[days_in_milk_col] < gday]) 840 after_df = cast(pd.DataFrame, group.loc[group[days_in_milk_col] > gday]) 841 before = before_df.tail(1) 842 after = after_df.head(1) 843 844 # CASE 3 No interpolation if grid day is outside the range of measured dim 845 if before.empty or after.empty: 846 continue 847 848 # CASE 4: No interpolation if the day after is day 305 or higher, 849 # as this is outside the range of the standard curve 850 if float(after.iloc[0][days_in_milk_col]) >= 305: 851 continue 852 853 x1 = float(before.iloc[0][days_in_milk_col]) 854 y1 = float(before.iloc[0][milking_yield_col]) 855 x2 = float(after.iloc[0][days_in_milk_col]) 856 y2 = float(after.iloc[0][milking_yield_col]) 857 858 # expected yields from standard lactation curve 859 g1 = _curve_value(standard_lc_series, int(x1)) 860 g2 = _curve_value(standard_lc_series, int(x2)) 861 gi = _curve_value(standard_lc_series, int(gday)) 862 863 # Wilmink-based interpolation formula 864 slope = ((y2 - y1) - (g2 - g1)) / (x2 - x1) 865 yi = gi + (slope * (gday - x1) + (y1 - g1)) 866 867 row = group.iloc[0].to_dict() 868 row["GridDay"] = gday 869 row["MilkYieldInterp"] = float(yi) 870 rows.append(row) 871 872 if not rows: 873 return pd.DataFrame( 874 columns=pd.Index([*group.columns.to_list(), "GridDay", "MilkYieldInterp"]) 875 ) 876 877 return pd.DataFrame(rows)
Interpolate a single lactation onto the dim grid guided by a standard curve.
The function interpolates measured yields for one animal onto the predefined grid of dim values. When a grid day coincides with a measured dim the observed yield is used; otherwise the interpolation adjusts the linear slope between neighboring measurements by the difference in the standard curve, inspired by the CRV E2 approach.
The interpolation formula applied for a grid day gday between two
measured points (x1,y1) and (x2,y2) is::
slope = ((y2 - y1) - (g2 - g1)) / (x2 - x1)
yi = gi + (slope * (gday - x1) + (y1 - g1))
Arguments:
- group: DataFrame with test-day records for a single animal. Must
contain columns named by
days_in_milk_colandmilking_yield_col. - days_in_milk_col: Name of the dim column in
group. - milking_yield_col: Name of the milk-yield column in
group. - standard_lc: A Series indexed by dim providing the expected yield on each grid day; used to guide the interpolation shape.
- small_grid: If True, interpolate on GRID_DAYS only; otherwise include day 0 and day 305 in the interpolation target grid.
Returns:
A DataFrame with one row per interpolated grid day containing the original identifying columns (from the first row of
group), plus the columnsGridDayandMilkYieldInterp.
Notes:
- No interpolation is performed outside the range bounded by the first and last measured dim for the lactation (those grid days are skipped). - No interpolation is performed for grid days where the right neighboring measured dim is >= 305, because this lies outside the intended standard-curve support.
- The implementation defines a local default
gridof [10, 30, ..., 290].
880def linear_interpd_all_to_grid( 881 group: pd.DataFrame, 882 days_in_milk_col: str, 883 milking_yield_col: str, 884 standard_lc: pd.Series | None = None, 885 small_grid: bool = False, 886) -> pd.DataFrame: 887 """Linearly interpolate all grid days for a lactation. 888 889 This helper uses linear interpolation (with extrapolation) to produce 890 milk-yield values for every grid day regardless of whether the grid day 891 lies between measured observations. 892 893 Args: 894 group: DataFrame containing measured dim and yield values for one 895 lactation. 896 days_in_milk_col: Name of the dim column. 897 milking_yield_col: Name of the milk-yield column. 898 small_grid: If True, interpolate on GRID_DAYS only; otherwise include 899 day 0 and day 305. 900 901 Returns: 902 A DataFrame with identifying columns copied from ``group``'s first 903 row and columns ``GridDay`` and ``MilkYieldInterp`` containing the 904 interpolated (or extrapolated) yields for every grid day. 905 """ 906 if small_grid: 907 grid = GRID_DAYS 908 else: 909 # add zero and 305 to the grid 910 grid = [0] + GRID_DAYS + [305] 911 912 group = group.sort_values(days_in_milk_col).drop_duplicates(subset=days_in_milk_col) 913 f = interp1d( 914 group[days_in_milk_col], 915 group[milking_yield_col], 916 kind="linear", 917 fill_value=cast(Any, "extrapolate"), 918 ) 919 920 base = { 921 col: group[col].iloc[0] 922 for col in group.columns 923 if col not in [days_in_milk_col, milking_yield_col] 924 } 925 base["GridDay"] = grid 926 base["MilkYieldInterp"] = f(grid) 927 928 return pd.DataFrame(base)
Linearly interpolate all grid days for a lactation.
This helper uses linear interpolation (with extrapolation) to produce milk-yield values for every grid day regardless of whether the grid day lies between measured observations.
Arguments:
- group: DataFrame containing measured dim and yield values for one lactation.
- days_in_milk_col: Name of the dim column.
- milking_yield_col: Name of the milk-yield column.
- small_grid: If True, interpolate on GRID_DAYS only; otherwise include day 0 and day 305.
Returns:
A DataFrame with identifying columns copied from
group's first row and columnsGridDayandMilkYieldInterpcontaining the interpolated (or extrapolated) yields for every grid day.
933def linear_interpd_closest_to_grid( 934 group: pd.DataFrame, 935 days_in_milk_col: str, 936 milking_yield_col: str, 937 standard_lc: pd.Series | None = None, 938 small_grid: bool = False, 939) -> pd.DataFrame | None: 940 """Linearly interpolate grid days between measured observations. 941 942 This helper returns interpolated yields only for grid days that lie 943 between the first and last measured dim for the lactation. If no grid 944 days fall within the measured range the function returns ``None``. 945 946 Args: 947 group: DataFrame for a single lactation. 948 days_in_milk_col: Name of the dim column. 949 milking_yield_col: Name of the milk-yield column. 950 small_grid: If True, use GRID_DAYS only; otherwise include 951 day 0 and day 305. 952 953 Returns: 954 A DataFrame with identifying columns plus ``GridDay`` and 955 ``MilkYieldInterp``, or ``None`` if there are no grid days within 956 the measured range. 957 """ 958 if small_grid: 959 grid = GRID_DAYS 960 else: 961 # add zero and 305 to the grid 962 grid = [0] + GRID_DAYS + [305] 963 964 group = group.sort_values(days_in_milk_col).drop_duplicates(subset=days_in_milk_col) 965 966 # Find the range of interpolatable dim 967 min_dim = group[days_in_milk_col].min().item() 968 max_dim = group[days_in_milk_col].max().item() 969 grid_in_range = [g for g in grid if min_dim <= g <= max_dim] 970 971 # apply linear interpolation 972 if not grid_in_range: 973 return None 974 f = interp1d( 975 group[days_in_milk_col], 976 group[milking_yield_col], 977 kind="linear", 978 fill_value=cast(Any, np.nan), 979 ) 980 981 # create a new dataframe with the newly created columns 982 base = { 983 col: group[col].iloc[0] 984 for col in group.columns 985 if col not in [days_in_milk_col, milking_yield_col] 986 } 987 base["GridDay"] = grid_in_range 988 base["MilkYieldInterp"] = f(grid_in_range) 989 990 return pd.DataFrame(base)
Linearly interpolate grid days between measured observations.
This helper returns interpolated yields only for grid days that lie
between the first and last measured dim for the lactation. If no grid
days fall within the measured range the function returns None.
Arguments:
- group: DataFrame for a single lactation.
- days_in_milk_col: Name of the dim column.
- milking_yield_col: Name of the milk-yield column.
- small_grid: If True, use GRID_DAYS only; otherwise include day 0 and day 305.
Returns:
A DataFrame with identifying columns plus
GridDayandMilkYieldInterp, orNoneif there are no grid days within the measured range.
993def create_standard_lc_representation( 994 df: pd.DataFrame, 995 standard_lactation_curve: pd.Series, 996 days_in_milk_col: str, 997 milking_yield_col: str, 998 interpolation_method: InterpolationMethod = interpolation_standard_lc, 999 lc_model: str = "Wilmink", 1000 small_grid: bool = False, 1001) -> tuple[pd.DataFrame, npt.NDArray[np.float64], pd.Series]: 1002 """Create a standard lactation curve with correlation matrix from data. 1003 1004 This function estimates the correlation structure and standard deviations 1005 of milk yields across grid days, and refits a Wilmink lactation curve model to 1006 the interpolated data. The Wilmink model is hereby the default, 1007 but any model from the LC package can be used. 1008 The outputs can be used as inputs to the 1009 ``ISLC_method`` or ``ISLC_original`` functions for predicting 305-d yields. 1010 1011 The process standardizes yields per animal and computes row-wise 1012 (per-animal) statistics, then derives relationships across grid days. 1013 1014 Args: 1015 df: Input DataFrame containing test-day records. Must include a 1016 ``TestId`` column to identify unique lactations. Also requires 1017 columns specified by ``days_in_milk_col`` and ``milking_yield_col``. 1018 standard_lactation_curve: A Series providing a reference lactation 1019 curve (e.g., the fitted Wilmink curve on which to base 1020 interpolation). 1021 days_in_milk_col: Name of the column in ``df`` containing days in milk (dim). 1022 milking_yield_col: Name of the column in ``df`` containing measured 1023 milk yields. 1024 interpolation_method: An interpolation method conforming to 1025 ``InterpolationMethod`` protocol (default: ``interpolation_standard_lc``). 1026 Must be callable with signature 1027 (group, days_in_milk_col, milking_yield_col, standard_lc). 1028 lc_model: The lactation curve model to fit to the interpolated data. Default is "Wilmink". 1029 small_grid: If True, build representation on GRID_DAYS only. 1030 1031 Returns: 1032 A tuple of three elements: 1033 - corr (pd.DataFrame): Correlation matrix between grid-day yields. 1034 - std_per_grid_day (np.ndarray): Standard deviations of standardized 1035 yields per grid day. 1036 - standard_lactation_curve_grid (pd.Series): Refitted Wilmink model 1037 indexed by dim (1–305). 1038 1039 Notes: 1040 - Expects ``df`` to have a ``TestId`` column to group lactations. 1041 - Performs standardization per animal (row-wise), so output 1042 correlations and standard deviations reflect between-day variation 1043 within standardized animal profiles. 1044 - Uses ``fit_lactation_curve`` from the ``lactationcurve`` package 1045 with model='Wilmink' and fitting='frequentist'. 1046 However other models can be used by specifying the ``lc_model`` argument. 1047 """ 1048 1049 if "TestId" not in df.columns: 1050 raise ValueError("DataFrame must contain a 'TestId' column.") 1051 if days_in_milk_col not in df.columns or milking_yield_col not in df.columns: 1052 raise ValueError(f"Columns '{days_in_milk_col}' and '{milking_yield_col}' must be in df.") 1053 1054 interpolated_groups: list[pd.DataFrame] = [] 1055 for test_id, group in df.groupby("TestId", sort=False): 1056 try: 1057 interp_group = interpolation_method( 1058 group, 1059 days_in_milk_col=days_in_milk_col, 1060 milking_yield_col=milking_yield_col, 1061 standard_lc=standard_lactation_curve, 1062 small_grid=small_grid, 1063 ) 1064 except TypeError: 1065 # Backward compatibility for custom interpolation callables 1066 # that do not yet accept small_grid. 1067 interp_group = interpolation_method( 1068 group, 1069 days_in_milk_col=days_in_milk_col, 1070 milking_yield_col=milking_yield_col, 1071 standard_lc=standard_lactation_curve, 1072 ) 1073 if interp_group.empty: 1074 continue 1075 if "TestId" not in interp_group.columns: 1076 interp_group = interp_group.copy() 1077 interp_group["TestId"] = test_id 1078 interpolated_groups.append(interp_group) 1079 1080 if not interpolated_groups: 1081 raise ValueError("No interpolated rows were produced; cannot build representation.") 1082 1083 df_grid = pd.concat(interpolated_groups, ignore_index=True) 1084 1085 # define Znp 1086 # pivot df to make GridDay the columns 1087 # Z should be the unscaled pivot table (TestId × GridDay) 1088 Z = df_grid.pivot(index="TestId", columns="GridDay", values="MilkYieldInterp") 1089 representation_grid = GRID_DAYS if small_grid else [0] + GRID_DAYS + [305] 1090 Z = Z.reindex(columns=representation_grid) 1091 1092 # Standardize records per cow (so each row has mean=0, std=1) 1093 Z_std = (Z.sub(Z.mean(axis=1), axis=0)).div(Z.std(axis=1), axis=0) 1094 1095 # Convert to NumPy array 1096 Znp = Z_std.to_numpy() 1097 1098 # calculate correlation matrix 1099 corr = pd.DataFrame(Znp, columns=Z.columns).corr() 1100 corr = corr.reindex(index=Z.columns, columns=Z.columns) 1101 corr_values = np.nan_to_num(corr.to_numpy(dtype=float), nan=0.0) 1102 np.fill_diagonal(corr_values, 1.0) 1103 corr = pd.DataFrame(corr_values, index=Z.columns, columns=Z.columns) 1104 1105 # calculate standard deviations for each grid day from the Znp matrix 1106 std_per_grid_day = np.nan_to_num( 1107 np.nanstd(Znp, axis=0), 1108 nan=0.0, 1109 posinf=0.0, 1110 neginf=0.0, 1111 ) 1112 1113 # fit Wilmink model to get mean values and std for each cow 1114 standard_lactation_curve_grid = pd.Series( 1115 fit_lactation_curve( 1116 df_grid["GridDay"].values, 1117 df_grid["MilkYieldInterp"].values, 1118 model=lc_model, 1119 fitting="frequentist", 1120 ), 1121 index=range(1, 306), 1122 ) 1123 return corr, std_per_grid_day, standard_lactation_curve_grid
Create a standard lactation curve with correlation matrix from data.
This function estimates the correlation structure and standard deviations
of milk yields across grid days, and refits a Wilmink lactation curve model to
the interpolated data. The Wilmink model is hereby the default,
but any model from the LC package can be used.
The outputs can be used as inputs to the
ISLC_method or ISLC_original functions for predicting 305-d yields.
The process standardizes yields per animal and computes row-wise (per-animal) statistics, then derives relationships across grid days.
Arguments:
- df: Input DataFrame containing test-day records. Must include a
TestIdcolumn to identify unique lactations. Also requires columns specified bydays_in_milk_colandmilking_yield_col. - standard_lactation_curve: A Series providing a reference lactation curve (e.g., the fitted Wilmink curve on which to base interpolation).
- days_in_milk_col: Name of the column in
dfcontaining days in milk (dim). - milking_yield_col: Name of the column in
dfcontaining measured milk yields. - interpolation_method: An interpolation method conforming to
InterpolationMethodprotocol (default:interpolation_standard_lc). Must be callable with signature (group, days_in_milk_col, milking_yield_col, standard_lc). - lc_model: The lactation curve model to fit to the interpolated data. Default is "Wilmink".
- small_grid: If True, build representation on GRID_DAYS only.
Returns:
A tuple of three elements:
- corr (pd.DataFrame): Correlation matrix between grid-day yields.
- std_per_grid_day (np.ndarray): Standard deviations of standardized yields per grid day.
- standard_lactation_curve_grid (pd.Series): Refitted Wilmink model indexed by dim (1–305).
Notes:
- Expects
dfto have aTestIdcolumn to group lactations.- Performs standardization per animal (row-wise), so output correlations and standard deviations reflect between-day variation within standardized animal profiles.
- Uses
fit_lactation_curvefrom thelactationcurvepackage with model='Wilmink' and fitting='frequentist'. However other models can be used by specifying thelc_modelargument.