lactationcurve.characteristics
1from . import ( 2 best_predict, 3 interpolation_using_standard_lactation_curves, 4 lactation_curve_characteristics, 5 method_test_interval, 6) 7from .best_predict import ( 8 best_predict_method, 9 best_predict_method_single_lactation, 10 build_covariance_matrix, 11 center_lactation_data, 12 fit_autocorrelation_matrix, 13 fit_standard_lc, 14 pivot_milk_recordings_to_matrix, 15 preprocess_measured_data, 16) 17from .centering_date_method import centering_date_method, centering_date_method_single_lactation 18from .interpolation_using_standard_lactation_curves import ( 19 ISLC_method, 20 ISLC_method_single_lactation, 21 ISLC_original_method, 22 ISLC_original_method_single_lactation, 23 create_standard_lc_representation, 24 interpolation_standard_lc, 25 linear_interpd_all_to_grid, 26 linear_interpd_closest_to_grid, 27) 28from .lactation_curve_characteristics import ( 29 calculate_characteristic, 30 lactation_curve_characteristic_function, 31 numeric_cumulative_yield, 32 numeric_peak_yield, 33 numeric_time_to_peak, 34 persistency_fitted_curve, 35 persistency_milkbot, 36 persistency_wood, 37) 38from .method_test_interval import test_interval_method 39 40__all__ = [ 41 "interpolation_using_standard_lactation_curves", 42 "ISLC_method", 43 "ISLC_method_single_lactation", 44 "ISLC_original_method", 45 "ISLC_original_method_single_lactation", 46 "best_predict", 47 "best_predict_method", 48 "best_predict_method_single_lactation", 49 "build_covariance_matrix", 50 "calculate_characteristic", 51 "center_lactation_data", 52 "centering_date_method", 53 "centering_date_method_single_lactation", 54 "create_standard_lc_representation", 55 "fit_autocorrelation_matrix", 56 "fit_standard_lc", 57 "interpolation_standard_lc", 58 "lactation_curve_characteristics", 59 "lactation_curve_characteristic_function", 60 "linear_interpd_all_to_grid", 61 "linear_interpd_closest_to_grid", 62 "method_test_interval", 63 "numeric_cumulative_yield", 64 "numeric_peak_yield", 65 "numeric_time_to_peak", 66 "persistency_fitted_curve", 67 "persistency_milkbot", 68 "persistency_wood", 69 "pivot_milk_recordings_to_matrix", 70 "preprocess_measured_data", 71 "test_interval_method", 72]
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.
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.
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.
499def best_predict_method( 500 df: pd.DataFrame, 501 standard_lc: np.ndarray = STANDARD_CURVE, 502 days_in_milk_col: str | None = None, 503 milking_yield_col: str | None = None, 504 test_id_col: str | None = None, 505 default_test_id: int = 0, 506 covariance_matrix: np.ndarray | None = COV_MATRIX, 507 fit_standard_lc_from_data: bool = False, 508 reference_df: pd.DataFrame | None = None, 509) -> pd.DataFrame: 510 """Apply best prediction to one or more lactations. 511 512 By default this function uses the package-provided standard curve and covariance matrix. 513 But it is also possible to provide your own standard curve and covariance matrix, 514 for example when you want to fit these ingredients from your own reference population. 515 This can be done in two ways: either by fitting the covariance matrix and standard curve 516 directly from a reference dataset by providing a pandas dataframe at 'reference_df =' 517 when ``fit_standard_lc_from_data`` is True. 518 Alternative for customization is to set standard_lc_305 and covariance_matrix 519 directly in the function call. 520 521 Args: 522 df: Input observations. If ``TestId`` is missing, all rows are treated 523 as one lactation. 524 standard_lc: Expected daily milk yield lactation curve on days 1..305. 525 If not provided, the package's default curve is used. 526 Or fit your own standard curve from a reference dataset by 527 providing a pandas dataframe at 'reference_df =' 528 when ``fit_standard_lc_from_data`` is True. 529 days_in_milk_col: Optional input column name for days in milk. If 530 provided, it is mapped to ``DaysInMilk``. 531 milking_yield_col: Optional input column name for milk yield. If 532 provided, it is mapped to ``MilkingYield``. 533 test_id_col: Optional input column name for lactation/test identifier. 534 If provided, it is mapped to ``TestId``. 535 default_test_id: Fallback test id used when no test-id column is 536 available. 537 covariance_matrix: Optional prefit covariance matrix. If omitted, 538 the default matrix is used or 539 ``reference_df`` can be used to fit one for your own data. 540 fit_standard_lc_from_data: Whether to fit covariance information from 541 ``reference_df`` instead of using a provided covariance matrix. 542 reference_df: Reference dataframe used when ``covariance_matrix`` and 543 ``standard_lc`` are not provided and ``fit_standard_lc_from_data`` 544 is True. 545 546 Returns: 547 Dataframe with columns ``TestId`` and ``LactationMilkYield``. 548 549 Raises: 550 ValueError: If neither ``covariance_matrix`` nor ``reference_df`` is 551 provided. 552 """ 553 # Standardize columns and filter DIM <= 305 554 df = standardize_lactation_columns( 555 df, 556 days_in_milk_col=days_in_milk_col, 557 milking_yield_col=milking_yield_col, 558 test_id_col=test_id_col, 559 default_test_id=default_test_id, 560 max_dim=305, 561 ) 562 563 # Fit covariance if not provided 564 if fit_standard_lc_from_data: 565 if reference_df is None: 566 raise ValueError("Provide reference_df to fit your own standard lactation curve.") 567 if not isinstance(reference_df, pd.DataFrame): 568 raise TypeError("reference_df must be a pandas DataFrame.") 569 reference_df = standardize_lactation_columns( 570 reference_df, 571 days_in_milk_col=days_in_milk_col, 572 milking_yield_col=milking_yield_col, 573 test_id_col=test_id_col, 574 default_test_id=default_test_id, 575 max_dim=305, 576 ) 577 covariance_matrix = cast( 578 np.ndarray, fit_autocorrelation_matrix(reference_df, standard_lc)["B_hat"] 579 ) 580 581 covariance_matrix_array = cast(np.ndarray, covariance_matrix) 582 583 df = df.copy() 584 585 results = [] 586 587 for test_id, lactation in df.groupby("TestId"): 588 pred = best_predict_method_single_lactation( 589 lactation, 590 standard_lc, 591 covariance_matrix_array, 592 ) 593 results.append({"TestId": test_id, "LactationMilkYield": pred}) 594 595 return pd.DataFrame(results)
Apply best prediction to one or more lactations.
By default this function uses the package-provided standard curve and covariance matrix.
But it is also possible to provide your own standard curve and covariance matrix,
for example when you want to fit these ingredients from your own reference population.
This can be done in two ways: either by fitting the covariance matrix and standard curve
directly 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 and covariance_matrix
directly in the function call.
Arguments:
- df: Input observations. If
TestIdis missing, all rows are treated as one lactation. - standard_lc: Expected daily milk yield lactation curve on days 1..305.
If not provided, the package's default curve is used.
Or fit your own standard curve from a reference dataset by
providing a pandas dataframe at 'reference_df ='
when
fit_standard_lc_from_datais True. - days_in_milk_col: Optional input column name for days in milk. If
provided, it is mapped to
DaysInMilk. - milking_yield_col: Optional input column name for milk yield. If
provided, it is mapped to
MilkingYield. - test_id_col: Optional input column name for lactation/test identifier.
If provided, it is mapped to
TestId. - default_test_id: Fallback test id used when no test-id column is available.
- covariance_matrix: Optional prefit covariance matrix. If omitted,
the default matrix is used or
reference_dfcan be used to fit one for your own data. - fit_standard_lc_from_data: Whether to fit covariance information from
reference_dfinstead of using a provided covariance matrix. - reference_df: Reference dataframe used when
covariance_matrixandstandard_lcare not provided andfit_standard_lc_from_datais True.
Returns:
Dataframe with columns
TestIdandLactationMilkYield.
Raises:
- ValueError: If neither
covariance_matrixnorreference_dfis provided.
429def best_predict_method_single_lactation( 430 lactation: pd.DataFrame, 431 standard_lc: np.ndarray = STANDARD_CURVE, 432 covariance_matrix: np.ndarray = COV_MATRIX, 433) -> float: 434 """Predict 305-day cumulative yield for one lactation. 435 436 Observed test-day deviations are projected over all 305 days using the 437 covariance structure and then added to the baseline cumulative standard 438 curve. 439 440 By default this function uses the package-provided standard curve and covariance matrix. 441 But it is also possible to provide your own standard curve and covariance matrix, 442 for example when you want to fit these ingredients from your own reference population. 443 444 445 Args: 446 lactation: Observed records for one lactation. 447 standard_lc: Population mean daily yield profile. 448 covariance_matrix: Day-to-day covariance matrix on the 305-day grid. 449 450 Returns: 451 Predicted cumulative 305-day milk yield. 452 453 Notes: 454 Duplicate day records are resolved with ``keep="last"`` before 455 prediction. If no valid observations remain in days 1..305, the method 456 returns the cumulative standard curve. 457 """ 458 filtered_lactation = lactation.loc[ 459 (lactation["DaysInMilk"] >= 1) & (lactation["DaysInMilk"] <= 305) 460 ].copy() 461 filtered_lactation = filtered_lactation.drop_duplicates(subset=["DaysInMilk"], keep="last") 462 filtered_lactation = filtered_lactation.sort_values("DaysInMilk") 463 464 corrected_series = preprocess_measured_data( 465 filtered_lactation, 466 standard_lc=standard_lc, 467 ) 468 469 if filtered_lactation.empty: 470 return float(np.sum(standard_lc)) 471 472 obs_idx_1based = filtered_lactation["DaysInMilk"].to_numpy(dtype=int) # DaysInMilk: 1-305 473 obs_idx_0based = obs_idx_1based - 1 # Convert to 0-based matrix indices: 0-304 474 y_obs = corrected_series.loc[obs_idx_1based].to_numpy( 475 dtype=float 476 ) # corrected_series is indexed by DaysInMilk (1-305) 477 478 # Extract covariance blocks 479 B_oo = covariance_matrix[ 480 np.ix_(obs_idx_0based, obs_idx_0based) 481 ] # Use 0-based indices for matrix 482 B_mo = covariance_matrix[:, obs_idx_0based] # Use 0-based indices for matrix 483 484 # solve 485 c, lower = cho_factor(B_oo) 486 alpha = cho_solve((c, lower), y_obs) 487 488 # Predict full deviation curve 489 y_estimate = B_mo @ alpha 490 491 # Total milk = baseline + deviation 492 deviation = np.sum(y_estimate) 493 494 total = np.sum(standard_lc) + deviation 495 496 return total
Predict 305-day cumulative yield for one lactation.
Observed test-day deviations are projected over all 305 days using the covariance structure and then added to the baseline cumulative standard curve.
By default this function uses the package-provided standard curve and covariance matrix. But it is also possible to provide your own standard curve and covariance matrix, for example when you want to fit these ingredients from your own reference population.
Arguments:
- lactation: Observed records for one lactation.
- standard_lc: Population mean daily yield profile.
- covariance_matrix: Day-to-day covariance matrix on the 305-day grid.
Returns:
Predicted cumulative 305-day milk yield.
Notes:
Duplicate day records are resolved with
keep="last"before prediction. If no valid observations remain in days 1..305, the method returns the cumulative standard curve.
276def build_covariance_matrix(rho: float, size: int) -> np.ndarray: 277 """Construct a covariance matrix. 278 279 Cole et al. (2007) estimated correlations among test-day yields using a 280 simplified model with an identity matrix (I) for daily measurement error 281 and an autoregressive matrix (E) for biological change. E is defined as 282 ``Eij = r ** |i-j|`` where ``i`` and ``j`` are test-day DIM and 283 ``0 < r < 1``. 284 285 Element ``(i, j)`` is ``rho ** abs(i - j)``. 286 287 Args: 288 rho: AR(1) correlation parameter. 289 size: Matrix dimension. 290 291 Returns: 292 A ``(size, size)`` AR(1) correlation matrix. 293 """ 294 idx = np.arange(size) 295 M = np.abs(idx[:, None] - idx[None, :]) 296 return rho**M
Construct a covariance matrix.
Cole et al. (2007) estimated correlations among test-day yields using a
simplified model with an identity matrix (I) for daily measurement error
and an autoregressive matrix (E) for biological change. E is defined as
Eij = r ** |i-j| where i and j are test-day DIM and
0 < r < 1.
Element (i, j) is rho ** abs(i - j).
Arguments:
- rho: AR(1) correlation parameter.
- size: Matrix dimension.
Returns:
A
(size, size)AR(1) correlation matrix.
323def calculate_characteristic( 324 dim, 325 milkrecordings, 326 model="wood", 327 characteristic="cumulative_milk_yield", 328 fitting="frequentist", 329 key=None, 330 parity=3, 331 breed="H", 332 continent="USA", 333 custom_priors=None, 334 milk_unit="kg", 335 persistency_method="derived", 336 lactation_length=305, 337) -> float | None: 338 """Evaluate a lactation curve characteristic from observed test-day data. 339 340 This function fits the requested model (frequentist or Bayesian via MilkBot), 341 retrieves model parameters, and evaluates the requested characteristic using the 342 symbolic expression (if available), falling back to numeric methods when needed. 343 344 Args: 345 dim (Int): Days in milk (DIM). 346 milkrecordings (Float): Milk recordings (kg or lbs) for each DIM. 347 model (str): Model name. Supported for this function: 348 'milkbot', 'wood', 'wilmink', 'ali_schaeffer', 'fischer'. 349 characteristic (str): One of 'time_to_peak', 'peak_yield', 350 'cumulative_milk_yield', 'persistency'. 351 fitting (str): 'frequentist' (default) or 'bayesian'. 352 key (str | None): API key for MilkBot Bayesian fitting. 353 parity (Int): Parity of the cow; values above 3 are considered as 3 (Bayesian). 354 breed (str): 'H' (Holstein) or 'J' (Jersey) (Bayesian). 355 custom_priors: provide your own priors for Bayesian fitting. 356 provide as dictionary using build_prior() function 357 to create the priors in the right format. 358 Alternative use priors from the literature provided by the string command 'CHEN' 359 milk_unit: Unit of milk recordings ('kg' or 'lb') for Bayesian fitting. 360 continent (str): 'USA' or 'EU' (Bayesian). 361 persistency_method (str): 'derived' (average slope after peak; default) or 'literature' 362 (only for Wood and MilkBot). 363 lactation_length (Int | str): Horizon for persistency calculation: 364 305 (default), 'max' (use max DIM in data), or an integer. 365 366 Returns: 367 float | None: The requested characteristic value. 368 Or None if value is negative (except persistency) 369 or cannot be computed symbolically. 370 371 Raises: 372 Exception: If inputs are invalid, the model/characteristic is unsupported, 373 an API key is missing for Bayesian fitting, or the characteristic cannot be computed. 374 """ 375 # check and prepare input 376 inputs = validate_and_prepare_inputs( 377 dim, 378 milkrecordings, 379 model=model, 380 fitting=fitting, 381 breed=breed, 382 parity=parity, 383 continent=continent, 384 custom_priors=custom_priors, 385 milk_unit=milk_unit, 386 persistency_method=persistency_method, 387 lactation_length=lactation_length, 388 ) 389 390 dim = inputs.dim 391 milkrecordings = inputs.milkrecordings 392 model = inputs.model 393 fitting = inputs.fitting 394 breed = inputs.breed 395 parity = inputs.parity 396 continent = inputs.continent 397 custom_priors = inputs.custom_priors 398 milk_unit = inputs.milk_unit 399 persistency_method = inputs.persistency_method 400 lactation_length = inputs.lactation_length 401 402 # After validation, these fields are guaranteed non-None for the paths below 403 assert model is not None 404 assert fitting is not None 405 406 if model not in ["milkbot", "wood", "wilmink", "ali_schaeffer", "fischer"]: 407 msg = ( 408 "this function currently only works for" 409 " the milkbot, wood, wilmink," 410 " ali_schaeffer and fischer models" 411 ) 412 raise Exception(msg) 413 414 characteristic_options: list[str] = [ 415 "time_to_peak", 416 "peak_yield", 417 "cumulative_milk_yield", 418 "persistency", 419 ] 420 421 if characteristic in characteristic_options: 422 if fitting == "frequentist": 423 # Get fitted parameters from your fitting function 424 fitted_params = get_lc_parameters(dim, milkrecordings, model) 425 assert fitted_params is not None 426 427 if characteristic != "persistency": 428 # Try symbolic formula first 429 assert isinstance(lactation_length, int) 430 try: 431 expr, params, fn = lactation_curve_characteristic_function( 432 model, characteristic, lactation_length 433 ) 434 with np.errstate( 435 divide="ignore", invalid="ignore" 436 ): # get rid of warnings for invalid operations 437 value = fn(*fitted_params) 438 except Exception: 439 value = None 440 441 # If symbolic formula fails or is invalid (use numeric approach) 442 if ( 443 value is None 444 or not np.isfinite(value) 445 or (characteristic == "time_to_peak" and value <= 0) 446 ): 447 assert parity is not None 448 assert breed is not None 449 assert continent is not None 450 if characteristic == "time_to_peak": 451 value = numeric_time_to_peak( 452 dim, 453 milkrecordings, 454 model, 455 fitting=fitting, 456 key=key, 457 parity=parity, 458 breed=breed, 459 continent=continent, 460 ) 461 elif characteristic == "peak_yield": 462 value = numeric_peak_yield( 463 dim, 464 milkrecordings, 465 model, 466 fitting=fitting, 467 key=key, 468 parity=parity, 469 breed=breed, 470 continent=continent, 471 ) 472 elif characteristic == "cumulative_milk_yield": 473 value = numeric_cumulative_yield( 474 dim, 475 milkrecordings, 476 model, 477 fitting=fitting, 478 lactation_length=lactation_length, 479 key=key, 480 parity=parity, 481 breed=breed, 482 continent=continent, 483 ) 484 485 else: 486 if persistency_method == "derived": 487 # find lactation length from data 488 if lactation_length == "max": 489 lactation_length = max(dim) 490 elif isinstance(lactation_length, int): 491 lactation_length = lactation_length 492 else: 493 lactation_length = 305 494 value = persistency_fitted_curve( 495 dim, 496 milkrecordings, 497 model, 498 fitting="frequentist", 499 lactation_length=lactation_length, 500 ) 501 502 else: 503 if model == "wood": 504 value = persistency_wood(fitted_params[1], fitted_params[2]) 505 506 elif model == "milkbot": 507 assert len(fitted_params) >= 4 508 value = persistency_milkbot(fitted_params[3]) 509 510 else: 511 msg = ( 512 "Currently only the Wood model" 513 " and MilkBot model have a" 514 " separate model function from" 515 " the literature integrated for" 516 " persistency. if" 517 ' persistency="derived" is' 518 " selected, persistency can be" 519 " calculated for every model as" 520 " the average slope of the" 521 " lactation after the peak." 522 ) 523 raise Exception(msg) 524 try: 525 if value is None: 526 return None 527 if characteristic != "persistency" and value < 0: 528 return None 529 return float(value) 530 except ValueError: 531 raise Exception("Could not compute characteristic") 532 533 else: 534 if model == "milkbot": 535 if key is None: 536 raise Exception("Key needed to use Bayesian fitting engine MilkBot") 537 else: 538 assert parity is not None 539 assert breed is not None 540 assert continent is not None 541 assert isinstance(milk_unit, str) 542 fitted_params_bayes = bayesian_fit_milkbot_single_lactation( 543 dim, 544 milkrecordings, 545 key=key, 546 parity=parity, 547 breed=breed, 548 custom_priors=custom_priors, 549 continent=continent, 550 milk_unit=milk_unit, 551 ) 552 fitted_params_bayes = ( 553 fitted_params_bayes["scale"], 554 fitted_params_bayes["ramp"], 555 fitted_params_bayes["offset"], 556 fitted_params_bayes["decay"], 557 ) 558 559 if characteristic != "persistency": 560 # Get the symbolic expression and model parameters 561 try: 562 expr, param_symbols, fn = lactation_curve_characteristic_function( 563 model, characteristic 564 ) 565 with np.errstate(divide="ignore", invalid="ignore"): 566 value = fn(*fitted_params_bayes) 567 except Exception: 568 value = None 569 570 if ( 571 value is None 572 or not np.isfinite(value) 573 or (characteristic == "time_to_peak" and value <= 0) 574 ): 575 if characteristic == "time_to_peak": 576 value = numeric_time_to_peak( 577 dim, 578 milkrecordings, 579 model, 580 fitting=fitting, 581 key=key, 582 parity=parity, 583 breed=breed, 584 custom_priors=custom_priors, 585 milk_unit=milk_unit, 586 continent=continent, 587 ) 588 elif characteristic == "peak_yield": 589 value = numeric_peak_yield( 590 dim, 591 milkrecordings, 592 model, 593 fitting=fitting, 594 key=key, 595 parity=parity, 596 breed=breed, 597 custom_priors=custom_priors, 598 milk_unit=milk_unit, 599 continent=continent, 600 ) 601 elif characteristic == "cumulative_milk_yield": 602 if lactation_length == "max": 603 numeric_lactation_length = max(dim) 604 elif isinstance(lactation_length, int): 605 numeric_lactation_length = lactation_length 606 else: 607 numeric_lactation_length = 305 608 value = numeric_cumulative_yield( 609 dim, 610 milkrecordings, 611 model, 612 fitting=fitting, 613 lactation_length=numeric_lactation_length, 614 key=key, 615 parity=parity, 616 breed=breed, 617 custom_priors=custom_priors, 618 milk_unit=milk_unit, 619 continent=continent, 620 ) 621 622 else: 623 if persistency_method == "derived": 624 # find lactation length from data 625 if lactation_length == "max": 626 lactation_length = max(dim) 627 elif isinstance(lactation_length, int): 628 lactation_length = lactation_length 629 else: 630 lactation_length = 305 631 assert isinstance(milk_unit, str) 632 value = persistency_fitted_curve( 633 dim, 634 milkrecordings, 635 model, 636 fitting="bayesian", 637 key=key, 638 parity=parity, 639 breed=breed, 640 custom_priors=custom_priors, 641 milk_unit=milk_unit, 642 continent=continent, 643 lactation_length=lactation_length, 644 ) 645 646 else: 647 value = persistency_milkbot(fitted_params_bayes[3]) 648 649 try: 650 if value is None: 651 return None 652 if characteristic != "persistency" and value < 0: 653 return None 654 return float(value) 655 except ValueError: 656 raise Exception("Could not compute characteristic") 657 else: 658 raise Exception("Bayesian fitting is currently only implemented for MilkBot models") 659 660 else: 661 raise Exception("Unknown characteristic")
Evaluate a lactation curve characteristic from observed test-day data.
This function fits the requested model (frequentist or Bayesian via MilkBot), retrieves model parameters, and evaluates the requested characteristic using the symbolic expression (if available), falling back to numeric methods when needed.
Arguments:
- dim (Int): Days in milk (DIM).
- milkrecordings (Float): Milk recordings (kg or lbs) for each DIM.
- model (str): Model name. Supported for this function: 'milkbot', 'wood', 'wilmink', 'ali_schaeffer', 'fischer'.
- characteristic (str): One of 'time_to_peak', 'peak_yield', 'cumulative_milk_yield', 'persistency'.
- fitting (str): 'frequentist' (default) or 'bayesian'.
- key (str | None): API key for MilkBot Bayesian fitting.
- parity (Int): Parity of the cow; values above 3 are considered as 3 (Bayesian).
- breed (str): 'H' (Holstein) or 'J' (Jersey) (Bayesian).
- custom_priors: provide your own priors for Bayesian fitting. provide as dictionary using build_prior() function to create the priors in the right format. Alternative use priors from the literature provided by the string command 'CHEN'
- milk_unit: Unit of milk recordings ('kg' or 'lb') for Bayesian fitting.
- continent (str): 'USA' or 'EU' (Bayesian).
- persistency_method (str): 'derived' (average slope after peak; default) or 'literature' (only for Wood and MilkBot).
- lactation_length (Int | str): Horizon for persistency calculation: 305 (default), 'max' (use max DIM in data), or an integer.
Returns:
float | None: The requested characteristic value. Or None if value is negative (except persistency) or cannot be computed symbolically.
Raises:
- Exception: If inputs are invalid, the model/characteristic is unsupported, an API key is missing for Bayesian fitting, or the characteristic cannot be computed.
247def center_lactation_data( 248 milk_matrix: np.ndarray, 249 standard_lc: np.ndarray, 250 day_mean_method: str = "standard_lc", 251) -> np.ndarray: 252 """Center lactation yields before covariance estimation. 253 254 Args: 255 milk_matrix: Yield matrix with lactations in rows and days in columns. 256 standard_lc: Expected day-wise milk yield profile. 257 day_mean_method: Mean-centering strategy. Supported values are 258 ``"standard_lc"`` (default) and ``"data"``. 259 260 Returns: 261 A centered matrix with the same shape as ``milk_matrix``. 262 263 Raises: 264 ValueError: If ``day_mean_method`` is not supported. 265 """ 266 if day_mean_method == "standard_lc": 267 day_mean = standard_lc 268 elif day_mean_method == "data": 269 day_mean = np.nanmean(milk_matrix, axis=0) 270 else: 271 raise ValueError("day_mean_method must be 'standard_lc' or 'data'.") 272 273 return milk_matrix - day_mean
Center lactation yields before covariance estimation.
Arguments:
- milk_matrix: Yield matrix with lactations in rows and days in columns.
- standard_lc: Expected day-wise milk yield profile.
- day_mean_method: Mean-centering strategy. Supported values are
"standard_lc"(default) and"data".
Returns:
A centered matrix with the same shape as
milk_matrix.
Raises:
- ValueError: If
day_mean_methodis not supported.
198def centering_date_method( 199 df: pd.DataFrame, 200 days_in_milk_col: str | None = None, 201 milking_yield_col: str | None = None, 202 test_id_col: str | None = None, 203 test_calender_date_col: str | None = None, 204 default_test_id: int = 0, 205 lactation_length: int = 305, 206 lactation_start_grace_period: int = 0, 207) -> pd.DataFrame: 208 """Compute total lactation milk yield using the centering date method for each test id. 209 210 The method applies: 211 212 213 Args: 214 df (pd.DataFrame): Input DataFrame with at least DaysInMilk and 215 MilkingYield columns, plus an optional TestId column. Column names 216 can be provided explicitly or matched via known aliases. 217 days_in_milk_col (str | None): Optional column name override for 218 DaysInMilk. 219 milking_yield_col (str | None): Optional column name override for 220 MilkingYield. 221 test_id_col (str | None): Optional column name override for TestId. 222 test_calender_date_col (str | None): Optional column name override for 223 TestCalendarDate. 224 default_test_id (int): Value used to create a default TestId column if 225 one is missing. 226 lactation_length (int): Lactation length used to calculate cumulative 227 production. The default is 305 days. 228 Records with DIM > lactation_length are excluded. 229 lactation_start_grace_period (int): Number of days after calving that 230 are not considered for cumulative yield becuase the colostrum is 231 not representative for the lactation. The default is 0 days. 232 233 Returns: 234 pd.DataFrame: Two-column DataFrame with 235 - "TestId": identifier per lactation, 236 - "LactationMilkYield": computed total milk yield over the 237 specified window. 238 239 Raises: 240 ValueError: If required columns (DaysInMilk or MilkingYield) cannot be found. 241 ValueError: If there are fewer than two data points per TestId. 242 243 """ 244 245 # Standardize columns and filter DIM <= lactation_length 246 df = standardize_lactation_columns( 247 df, 248 days_in_milk_col=days_in_milk_col, 249 milking_yield_col=milking_yield_col, 250 test_id_col=test_id_col, 251 test_calender_date_col=test_calender_date_col, 252 default_test_id=default_test_id, 253 max_dim=lactation_length, 254 lactation_start_grace_period=lactation_start_grace_period, 255 ) 256 257 result = [] 258 259 # Iterate over each lactation 260 for lactation in df["TestId"].unique(): 261 lactation_df = pd.DataFrame(df[df["TestId"] == lactation]) 262 263 if len(lactation_df) < 2: 264 print(f"Skipping TestId {lactation}: not enough data points for interpolation.") 265 continue 266 267 # Check that the date column is datetime and convert it if needed. 268 if not pd.api.types.is_datetime64_any_dtype(lactation_df["TestCalendarDate"]): 269 lactation_df["TestCalendarDate"] = pd.to_datetime(lactation_df["TestCalendarDate"]) 270 271 # Calculate total milk yield for this lactation 272 total_milk_yield = centering_date_method_single_lactation( 273 lactation_df, 274 lactation_start_grace_period=lactation_start_grace_period, 275 lactation_length=lactation_length, 276 ) 277 278 result.append({"TestId": lactation, "LactationMilkYield": total_milk_yield}) 279 280 return pd.DataFrame(result, columns=pd.Index(["TestId", "LactationMilkYield"]))
Compute total lactation milk yield using the centering date method for each test id.
The method applies:
Arguments:
- df (pd.DataFrame): Input DataFrame with at least DaysInMilk and MilkingYield columns, plus an optional TestId column. Column names can be provided explicitly or matched via known aliases.
- days_in_milk_col (str | None): Optional column name override for DaysInMilk.
- milking_yield_col (str | None): Optional column name override for MilkingYield.
- test_id_col (str | None): Optional column name override for TestId.
- test_calender_date_col (str | None): Optional column name override for
- TestCalendarDate.
- default_test_id (int): Value used to create a default TestId column if one is missing.
- lactation_length (int): Lactation length used to calculate cumulative production. The default is 305 days. Records with DIM > lactation_length are excluded.
- lactation_start_grace_period (int): Number of days after calving that are not considered for cumulative yield becuase the colostrum is not representative for the lactation. The default is 0 days.
Returns:
pd.DataFrame: Two-column DataFrame with - "TestId": identifier per lactation, - "LactationMilkYield": computed total milk yield over the specified window.
Raises:
- ValueError: If required columns (DaysInMilk or MilkingYield) cannot be found.
- ValueError: If there are fewer than two data points per TestId.
149def centering_date_method_single_lactation( 150 lactation_df: pd.DataFrame, 151 lactation_length: int = 305, 152 lactation_start_grace_period: int = 0, 153) -> float: 154 """Compute total lactation milk yield using the centering date method. 155 156 Args: 157 lactation_df (pd.DataFrame): Input DataFrame that contains all milk 158 recordings of a single lactation 159 with at least TestCalendarDate,DaysInMilk and MilkingYield columns. 160 Column names can be provided explicitly or matched via known aliases. 161 lactation_length (int): Lactation length used to calculate cumulative 162 production. The default is 305 days. 163 Records with DIM > lactation_length are excluded. 164 If dry dates are known it is recommended to use the actual lactation 165 length instead of the default 305 days. 166 lactation_start_grace_period (int): Number of days after calving that 167 are not considered for cumulative yield becuase the colostrum is 168 not representative for the lactation. The default is 0 days. 169 170 Returns: 171 float: The computed total milk yield over the lactation for a single cow. 172 173 """ 174 df = lactation_df.sort_values("TestCalendarDate") 175 176 # One yield per calendar month (if a month has several tests, take their mean) 177 month = df["TestCalendarDate"].dt.to_period("M") 178 y = cast(pd.Series, df.groupby(month)["MilkingYield"].mean()) 179 180 # Full monthly range from first to last test; missing months become NaN 181 full_range = pd.period_range(y.index.min(), y.index.max(), freq="M") 182 y = y.reindex(full_range) 183 184 # Missing month = average of the nearest test before and the nearest test after 185 y = y.fillna(y.ffill().add(y.bfill()).div(2)) 186 187 # Weights: days in each month, with the first and last month adjusted 188 w = np.array([period.days_in_month for period in full_range], dtype=float) 189 d_first = df["DaysInMilk"].iloc[0] - lactation_start_grace_period 190 d_last = df["DaysInMilk"].iloc[-1] 191 w[0] = d_first + w[0] / 2 192 w[-1] = lactation_length - d_last + w[-1] / 2 193 194 total_milk_yield = (w * y).sum() 195 return total_milk_yield
Compute total lactation milk yield using the centering date method.
Arguments:
- lactation_df (pd.DataFrame): Input DataFrame that contains all milk recordings of a single lactation with at least TestCalendarDate,DaysInMilk and MilkingYield columns. Column names can be provided explicitly or matched via known aliases.
- lactation_length (int): Lactation length used to calculate cumulative production. The default is 305 days. Records with DIM > lactation_length are excluded. If dry dates are known it is recommended to use the actual lactation length instead of the default 305 days.
- lactation_start_grace_period (int): Number of days after calving that are not considered for cumulative yield becuase the colostrum is not representative for the lactation. The default is 0 days.
Returns:
float: The computed total milk yield over the lactation for a single cow.
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.
299def fit_autocorrelation_matrix( 300 df: pd.DataFrame, standard_lc: np.ndarray 301) -> dict[str, np.ndarray | float]: 302 """Estimate covariance parameters for best prediction. 303 304 The model is ``B = b1 * I + b2 * E`` where ``E`` is an AR(1) correlation 305 matrix. Parameters are optimized in transformed space and mapped back to 306 enforce ``b1 > 0``, ``b2 > 0``, and ``0 < rho < 1``. 307 308 Args: 309 df: Reference milk-recording dataframe. 310 standard_lc: Population mean curve used for centering. 311 312 Returns: 313 Dictionary with: 314 - ``"B_hat"``: fitted covariance matrix. 315 - ``"R_hat"``: correlation matrix derived from ``B_hat``. 316 - ``"b1"``, ``"b2"``, ``"rho"``: fitted scalar parameters. 317 """ 318 milk_matrix = pivot_milk_recordings_to_matrix(df) 319 centered_matrix = center_lactation_data(milk_matrix, standard_lc) 320 n_lactations, n_days = centered_matrix.shape 321 observed_indices = [np.where(~np.isnan(centered_matrix[i]))[0] for i in range(n_lactations)] 322 323 def negative_log_likelihood(params: np.ndarray) -> float: 324 p_b1, p_b2, p_rho = params 325 b1 = float(np.exp(p_b1)) 326 b2 = float(np.exp(p_b2)) 327 rho = float(1 / (1 + np.exp(-p_rho))) # now rho in (0,1) 328 correlation_matrix = build_covariance_matrix(rho, n_days) 329 330 total = 0.0 331 for lactation_idx, day_indices in enumerate(observed_indices): 332 observation_count = len(day_indices) 333 if observation_count == 0: 334 continue 335 336 observations = centered_matrix[lactation_idx, day_indices] 337 correlation_subset = correlation_matrix[np.ix_(day_indices, day_indices)] 338 sigma = b1 * np.eye(observation_count) + b2 * correlation_subset 339 340 # Numerical safeguards: try Cholesky and penalize non-PD parameters. 341 try: 342 cholesky_factor, lower = cho_factor(sigma, check_finite=False) 343 solution = cho_solve((cholesky_factor, lower), observations, check_finite=False) 344 except LinAlgError: 345 # penalty for non-PD 346 return float(1e12 + np.sum(np.abs(params))) 347 348 quadratic_form = float(observations @ solution) 349 log_determinant = 2.0 * np.sum(np.log(np.diag(cholesky_factor))) 350 total += 0.5 * ( 351 log_determinant + quadratic_form + observation_count * np.log(2 * np.pi) 352 ) 353 354 # return total negative log-likelihood 355 return float(total) 356 357 # initial guesses and optimization. A 50/50 split in variance is assumed as starting point 358 initial_variance = max(float(np.nanvar(centered_matrix)), 1e-6) 359 initial_params = [ 360 np.log(0.5 * initial_variance), 361 np.log(0.5 * initial_variance), 362 0.5, 363 ] 364 365 result = minimize( 366 negative_log_likelihood, 367 x0=initial_params, 368 method="L-BFGS-B", 369 options={"maxiter": 2000, "ftol": 1e-8}, 370 ) 371 372 if not result.success: 373 print(f"Optimization warning: {result.message}") 374 375 log_b1_hat, log_b2_hat, logit_rho_hat = result.x 376 b1_hat = float(np.exp(log_b1_hat)) 377 b2_hat = float(np.exp(log_b2_hat)) 378 rho_hat = float(1 / (1 + np.exp(-logit_rho_hat))) 379 correlation_matrix = build_covariance_matrix(rho_hat, n_days) 380 covariance_matrix = b1_hat * np.eye(n_days) + b2_hat * correlation_matrix 381 382 # convert to correlation matrix 383 std = np.sqrt(np.diag(covariance_matrix)) 384 correlation_matrix = covariance_matrix / np.outer(std, std) 385 386 return { 387 "B_hat": covariance_matrix, 388 "R_hat": correlation_matrix, 389 "b1": b1_hat, 390 "b2": b2_hat, 391 "rho": rho_hat, 392 }
Estimate covariance parameters for best prediction.
The model is B = b1 * I + b2 * E where E is an AR(1) correlation
matrix. Parameters are optimized in transformed space and mapped back to
enforce b1 > 0, b2 > 0, and 0 < rho < 1.
Arguments:
- df: Reference milk-recording dataframe.
- standard_lc: Population mean curve used for centering.
Returns:
Dictionary with:
"B_hat": fitted covariance matrix."R_hat": correlation matrix derived fromB_hat."b1","b2","rho": fitted scalar parameters.
216def fit_standard_lc(df: pd.DataFrame, lc_model: str = "Wood") -> np.ndarray: 217 """Fit a population-level standard lactation curve. 218 219 The curve is fit with the package's frequentist Wood model and returned on 220 the fixed day-1..305 grid. 221 222 Args: 223 df: Reference dataframe containing ``DaysInMilk`` and ``MilkingYield``. 224 lc_model: The lactation curve model to fit. 225 Default is the "Wood" lactation curve model. 226 227 Returns: 228 A NumPy array of expected daily milk yield for days 1..305. 229 230 Notes: 231 This mean curve acts as the baseline in best prediction. Individual 232 lactations are represented as deviations around this population profile. 233 """ 234 standard_lc = pd.Series( 235 fit_lactation_curve( 236 df["DaysInMilk"].values, 237 df["MilkingYield"].values, 238 model=lc_model, 239 fitting="frequentist", 240 ), 241 index=range(1, 306), 242 ) 243 244 return standard_lc.to_numpy(dtype=float)
Fit a population-level standard lactation curve.
The curve is fit with the package's frequentist Wood model and returned on the fixed day-1..305 grid.
Arguments:
- df: Reference dataframe containing
DaysInMilkandMilkingYield. - lc_model: The lactation curve model to fit.
- Default is the "Wood" lactation curve model.
Returns:
A NumPy array of expected daily milk yield for days 1..305.
Notes:
This mean curve acts as the baseline in best prediction. Individual lactations are represented as deviations around this population profile.
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].
95def lactation_curve_characteristic_function( 96 model="wood", characteristic=None, lactation_length=305 97) -> tuple: 98 """Build (or fetch from cache) a symbolic expression and fast numeric function for an LCC. 99 100 This function derives the requested **lactation curve characteristic** for a given 101 model using SymPy (derivative / root finding / integration). It returns the symbolic 102 expression, the tuple of parameter symbols (argument order), and a lambdified 103 numeric function that can be evaluated with numerical parameters. 104 105 The symbolic derivation and integration are done only once per (model, characteristic) 106 and then **cached** for reuse. 107 108 Args: 109 model (str): Model name. Options: 110 'milkbot', 'wood', 'wilmink', 'ali_schaeffer', 'fischer', 111 'brody', 'sikka', 'nelder', 'dhanoa', 'emmans', 'hayashi', 112 'rook', 'dijkstra', 'prasad'. 113 characteristic (str | None): Desired characteristic. Options: 114 'time_to_peak', 'peak_yield', 'cumulative_milk_yield', 'persistency'. 115 If `None` or unrecognized, a dict of all available characteristics is returned 116 (with `persistency` possibly `None` if derivation is not feasible). 117 lactation_length (int): Length of lactation in days used in persistency 118 and cumulative milk yield computation (default 305). 119 120 Returns: 121 tuple: 122 expr: SymPy expression (or dict of expressions if `characteristic` is None). 123 params: Tuple of SymPy symbols for model parameters (argument order). 124 func: Lambdified numeric function `f(*params)` (or dict of functions). 125 126 Raises: 127 Exception: If the model is unknown, or if no positive real solution for 128 peak timing/yield exists where required. In this case None is returned 129 for the characteristic, 130 and the function can be evaluated with numeric methods as a fallback. 131 """ 132 # check the cache 133 storage = (model, characteristic) 134 if storage in _LCC_CACHE: 135 return ( 136 _LCC_CACHE[storage]["expr"], 137 _LCC_CACHE[storage]["params"], 138 _LCC_CACHE[storage]["func"], 139 ) 140 141 # make sure model is all lowercase 142 model = model.lower() 143 144 # define functions 145 if model == "brody": 146 # === BRODY 1 === 147 a, b, k1, k2, t = symbols("a b k1 k2 t", real=True, positive=True) 148 function = a * exp(-k1 * t) - b * exp(-k2 * t) 149 150 elif model == "sikka": 151 # === SIKKA === 152 a, b, c, t = symbols("a b c t", real=True, positive=True) 153 function = a * exp(b * t - c * t**2) 154 155 elif model == "fischer": 156 # === FISCHER === 157 a, b, c, t = symbols("a b c t", real=True, positive=True) 158 function = a - b * t - a * exp(-c * t) 159 160 elif model == "nelder": 161 # === NELDER === 162 a, b, c, t = symbols("a b c t", real=True, positive=True) 163 function = t / (a + b * t + c * t**2) 164 165 elif model == "wood": 166 # === WOOD === 167 a, b, c, t = symbols("a b c t", real=True, positive=True) 168 function = a * t**b * exp(-c * t) 169 170 elif model == "dhanoa": 171 # === DHANOA === 172 a, b, c, t = symbols("a b c t", real=True, positive=True) 173 function = a * t ** (b * c) * exp(-c * t) 174 175 elif model == "emmans": 176 # === EMMANS === 177 a, b, c, d, t = symbols("a b c d t", real=True, positive=True) 178 function = a * exp(-exp(d - b * t)) * exp(-c * t) 179 180 elif model == "ali_schaeffer": 181 # ====ALI===== 182 a, b, c, d, k, t = symbols("a b c d k t", real=True) 183 184 t1 = t / 305 185 w1 = log(305 / t) 186 187 function = a + b * t1 + c * t1**2 + d * w1 + k * w1**2 188 189 elif model == "wilmink": 190 # === WILMINK === 191 a, c, k, t = symbols("a c k t", real=True, positive=True) 192 b = symbols("b", real=True) # b can be negative in Wilmink 193 function = a + b * exp(-k * t) - c * t 194 195 elif model == "hayashi": 196 # === HAYASHI === 197 a, b, c, t = symbols("a b c t", real=True, positive=True) 198 function = b * (exp(-t / c) - exp(-t / (a * c))) 199 200 elif model == "rook": 201 # === ROOK === 202 a, b, c, d, t = symbols("a b c d t", real=True, positive=True) 203 function = a * (1 / (1 + b / (c + t))) * exp(-d * t) 204 205 elif model == "dijkstra": 206 # === DIJKSTRA === 207 a, b, c, d, t = symbols("a b c d t", real=True, positive=True) 208 function = a * exp((b * (1 - exp(-c * t)) / c) - d * t) 209 210 elif model == "prasad": 211 # === PRASAD === 212 a, b, c, d, t = symbols("a b c d t", real=True, positive=True) 213 function = a + b * t + c * t**2 + d / t 214 215 elif model == "milkbot": 216 # === MILKBOT === 217 a, b, c, d, t = symbols("a b c d t", real=True, positive=True) 218 function = a * (1 - exp((c - t) / b) / 2) * exp(-d * t) 219 220 else: 221 raise Exception("Unknown model") 222 223 # solve derivative for when it is zero to find the function for time of peak 224 fdiff = diff(function, t) 225 226 tpeak = None # default 227 228 valid_roots = [] 229 230 try: 231 candidate_roots = solve(fdiff, t) 232 233 for r in candidate_roots: 234 r_simplified = simplify(r) 235 236 if r_simplified.is_real is not False: 237 valid_roots.append(r_simplified) 238 239 except Exception: 240 valid_roots = [] 241 242 tpeak = valid_roots[0] if valid_roots else None 243 244 # override to prevent sympy error 245 if model == "dijkstra": 246 tpeak = simplify(log(b / d) / c) 247 248 # define the end of lactation 249 T = lactation_length # days in milk 250 251 # Persistency = average slope after peak, does not work for all models so therefore try except 252 persistency = None 253 try: 254 if tpeak: 255 tmp = (function.subs(t, T) - function.subs(t, tpeak)) / (T - tpeak) 256 tmp = tmp.cancel() # light simplification 257 if is_valid_sympy_expr(tmp): 258 persistency = tmp 259 except Exception: 260 persistency = None 261 262 if characteristic != "cumulative_milk_yield": 263 if tpeak: # Check if the list is not empty 264 peak_expr = simplify(function.subs(t, tpeak)) 265 else: 266 raise Exception("No real solution for time to peak and peak yield found") 267 268 # find function for cumulative milk yield of the lactation. 269 # A lactation length of 305 is the default, but this value can 270 # also be provided as a parameter in the characteristic function. 271 cum_my_expr = integrate(function, (t, 0, lactation_length), meijerg=False) 272 273 if cum_my_expr == 0: 274 cum_my_expr = Integral(function, (t, 0, lactation_length)) 275 276 # Sorted parameter list (exclude t) 277 params = tuple( 278 sorted([s for s in function.free_symbols if s.name != "t"], key=lambda x: x.name) 279 ) 280 281 # ---------------------------------------------------- 282 # Select requested characteristic 283 # ---------------------------------------------------- 284 if characteristic == "time_to_peak": 285 expr = tpeak 286 elif characteristic == "peak_yield": 287 expr = peak_expr 288 elif characteristic == "cumulative_milk_yield": 289 expr = cum_my_expr 290 elif characteristic == "persistency": 291 if persistency is None: 292 raise Exception("Persistency could not be computed symbolically") 293 expr = persistency 294 else: 295 # Return all four if None or 'all' 296 expr = { 297 "time_to_peak": tpeak, 298 "peak_yield": peak_expr, 299 "persistency": persistency, # possibly None 300 "cumulative_milk_yield": cum_my_expr, 301 } 302 303 # ---------------------------------------------------- 304 # Build fast numeric function with lambdify 305 # ---------------------------------------------------- 306 if isinstance(expr, dict): 307 func = { 308 name: lambdify(params, ex, modules=["numpy", "scipy"]) 309 for name, ex in expr.items() 310 if ex is not None 311 } 312 else: 313 func = lambdify(params, expr, modules=["numpy", "scipy"]) 314 315 # ---------------------------------------------------- 316 # Store in cache 317 # ---------------------------------------------------- 318 _LCC_CACHE[storage] = {"expr": expr, "params": params, "func": func} 319 320 return expr, params, func
Build (or fetch from cache) a symbolic expression and fast numeric function for an LCC.
This function derives the requested lactation curve characteristic for a given model using SymPy (derivative / root finding / integration). It returns the symbolic expression, the tuple of parameter symbols (argument order), and a lambdified numeric function that can be evaluated with numerical parameters.
The symbolic derivation and integration are done only once per (model, characteristic) and then cached for reuse.
Arguments:
- model (str): Model name. Options: 'milkbot', 'wood', 'wilmink', 'ali_schaeffer', 'fischer', 'brody', 'sikka', 'nelder', 'dhanoa', 'emmans', 'hayashi', 'rook', 'dijkstra', 'prasad'.
- characteristic (str | None): Desired characteristic. Options:
'time_to_peak', 'peak_yield', 'cumulative_milk_yield', 'persistency'.
If
Noneor unrecognized, a dict of all available characteristics is returned (withpersistencypossiblyNoneif derivation is not feasible). - lactation_length (int): Length of lactation in days used in persistency and cumulative milk yield computation (default 305).
Returns:
tuple: expr: SymPy expression (or dict of expressions if
characteristicis None). params: Tuple of SymPy symbols for model parameters (argument order). func: Lambdified numeric functionf(*params)(or dict of functions).
Raises:
- Exception: If the model is unknown, or if no positive real solution for peak timing/yield exists where required. In this case None is returned for the characteristic, and the function can be evaluated with numeric methods as a fallback.
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.
720def numeric_cumulative_yield( 721 dim, milkrecordings, model, fitting="frequentist", lactation_length=305, **kwargs 722) -> float: 723 """Compute cumulative milk yield numerically over a given horizon. 724 725 Adds up the fitted milk yield for the first `lactation_length` days of the 726 predicted yield curve. 727 728 Args: 729 dim: DIM values. 730 milkrecordings: Milk recordings (kg). 731 model: Model name. 732 fitting: 'frequentist' or 'bayesian'. 733 lactation_length: Number of days to integrate (default 305). 734 **kwargs: Additional arguments forwarded to `fit_lactation_curve`. 735 736 Returns: 737 float: Cumulative milk yield over the specified horizon. 738 """ 739 y = fit_lactation_curve(dim, milkrecordings, model, fitting=fitting, **kwargs) 740 return float(np.trapezoid(y[:lactation_length], dx=1))
Compute cumulative milk yield numerically over a given horizon.
Adds up the fitted milk yield for the first lactation_length days of the
predicted yield curve.
Arguments:
- dim: DIM values.
- milkrecordings: Milk recordings (kg).
- model: Model name.
- fitting: 'frequentist' or 'bayesian'.
- lactation_length: Number of days to integrate (default 305).
- **kwargs: Additional arguments forwarded to
fit_lactation_curve.
Returns:
float: Cumulative milk yield over the specified horizon.
743def numeric_peak_yield( 744 dim, 745 milkrecordings, 746 model, 747 fitting="frequentist", 748 key=None, 749 parity=3, 750 breed="H", 751 custom_priors=None, 752 milk_unit="kg", 753 continent="USA", 754) -> float: 755 """Compute peak yield numerically from the fitted curve. 756 757 Args: 758 dim: DIM values. 759 milkrecordings: Milk recordings (kg). 760 model: Model name. 761 fitting: 'frequentist' or 'bayesian'. 762 key: API key for MilkBot (Bayesian). 763 parity: Parity for Bayesian fitting. 764 breed: Breed for Bayesian fitting ('H' or 'J'). 765 continent: Prior source for Bayesian ('USA', 'EU', 'CHEN'). 766 767 Returns: 768 float: Maximum predicted milk yield. 769 """ 770 # Fit the curve to get predicted milk yields 771 yields = fit_lactation_curve( 772 dim, 773 milkrecordings, 774 model, 775 fitting=fitting, 776 key=key, 777 parity=parity, 778 breed=breed, 779 custom_priors=custom_priors, 780 milk_unit=milk_unit, 781 continent=continent, 782 ) 783 # Find the peak yield 784 peak_yield = np.max(yields) 785 return peak_yield
Compute peak yield numerically from the fitted curve.
Arguments:
- dim: DIM values.
- milkrecordings: Milk recordings (kg).
- model: Model name.
- fitting: 'frequentist' or 'bayesian'.
- key: API key for MilkBot (Bayesian).
- parity: Parity for Bayesian fitting.
- breed: Breed for Bayesian fitting ('H' or 'J').
- continent: Prior source for Bayesian ('USA', 'EU', 'CHEN').
Returns:
float: Maximum predicted milk yield.
665def numeric_time_to_peak( 666 dim, 667 milkrecordings, 668 model, 669 fitting="frequentist", 670 key=None, 671 parity=3, 672 breed="H", 673 custom_priors=None, 674 milk_unit="kg", 675 continent="USA", 676) -> int: 677 """Compute time to peak using a numeric approach. 678 679 Fits the curve (frequentist or Bayesian), evaluates the predicted yields, 680 and returns the DIM corresponding to the maximum predicted yield. 681 682 Args: 683 dim: DIM values. 684 milkrecordings: Milk recordings (kg). 685 model: Model name. 686 fitting: 'frequentist' or 'bayesian'. 687 key: API key for MilkBot (Bayesian). 688 parity: Parity for Bayesian fitting. 689 breed: Breed for Bayesian fitting ('H' or 'J'). 690 custom_priors: provide your own priors for Bayesian fitting. 691 provide as dictionary using build_prior() function to set 692 the priors in the right format. Alternative use priors from 693 the literature provided by the string command 'CHEN' 694 milk_unit: Unit of milk recordings ('kg' or 'lb') for Bayesian fitting. 695 continent: Prior source for Bayesian ('USA', 'EU'). 696 697 698 Returns: 699 int: DIM at which the curve attains its maximum (1-indexed). 700 """ 701 # Fit the curve to get predicted milk yields 702 yields = fit_lactation_curve( 703 dim, 704 milkrecordings, 705 model, 706 fitting=fitting, 707 key=key, 708 parity=parity, 709 breed=breed, 710 custom_priors=custom_priors, 711 milk_unit=milk_unit, 712 continent=continent, 713 ) 714 # Find the index of the peak yield 715 peak_idx = np.argmax(yields) 716 # Return the corresponding DIM 717 return int(peak_idx + 1) # +1 because DIM starts at 1, not 0
Compute time to peak using a numeric approach.
Fits the curve (frequentist or Bayesian), evaluates the predicted yields, and returns the DIM corresponding to the maximum predicted yield.
Arguments:
- dim: DIM values.
- milkrecordings: Milk recordings (kg).
- model: Model name.
- fitting: 'frequentist' or 'bayesian'.
- key: API key for MilkBot (Bayesian).
- parity: Parity for Bayesian fitting.
- breed: Breed for Bayesian fitting ('H' or 'J').
- custom_priors: provide your own priors for Bayesian fitting. provide as dictionary using build_prior() function to set the priors in the right format. Alternative use priors from the literature provided by the string command 'CHEN'
- milk_unit: Unit of milk recordings ('kg' or 'lb') for Bayesian fitting.
- continent: Prior source for Bayesian ('USA', 'EU').
Returns:
int: DIM at which the curve attains its maximum (1-indexed).
813def persistency_fitted_curve( 814 dim, 815 milkrecordings, 816 model, 817 fitting="frequentist", 818 key=None, 819 parity=3, 820 breed="H", 821 custom_priors=None, 822 milk_unit="kg", 823 continent="USA", 824 lactation_length=305, 825) -> float: 826 """Persistency as the average slope after peak until end of lactation (numeric). 827 828 This is the default approach because symbolic derivation is not feasible for 829 all models. It computes: 830 `(yield_at_end - yield_at_peak) / (lactation_length - time_to_peak)` 831 832 Args: 833 dim: DIM values. 834 milkrecordings: Milk recordings (kg). 835 model: Model name. Options include 'milkbot' (Bayesian or frequentist), 836 'wood', 'wilmink', 'ali_schaeffer', 'fischer'. 837 fitting: 'frequentist' or 'bayesian'. 838 key: API key (only for Bayesian fitting). 839 parity: Parity of the cow; values above 3 treated as 3 (Bayesian). 840 breed: 'H' or 'J' (Bayesian). 841 custom_priors: provide your own priors for Bayesian fitting. 842 provide as dictionary using build_prior() function to 843 create the priors in the right format. Alternative use 844 priors from the literature provided by the string 845 command 'CHEN' 846 milk_unit: Unit of milk recordings ('kg' or 'lb') for Bayesian fitting. 847 continent: 'USA', 'EU', or 'CHEN' (Bayesian). 848 lactation_length (int | str): 305 (default), 'max' (use max DIM), or integer. 849 850 Returns: 851 float: Average slope after the peak until end of lactation. 852 """ 853 # calculate time to peak 854 t_peak = numeric_time_to_peak( 855 dim, 856 milkrecordings, 857 model, 858 fitting=fitting, 859 key=key, 860 parity=parity, 861 breed=breed, 862 custom_priors=custom_priors, 863 milk_unit=milk_unit, 864 continent=continent, 865 ) 866 867 # determine lactation length 868 if lactation_length == "max": 869 lactation_length = max(dim) 870 elif isinstance(lactation_length, int): 871 lactation_length = lactation_length 872 else: 873 lactation_length = 305 874 875 # calculate milk yield at peak 876 yields = fit_lactation_curve( 877 dim, 878 milkrecordings, 879 model, 880 fitting=fitting, 881 key=key, 882 parity=parity, 883 breed=breed, 884 custom_priors=custom_priors, 885 milk_unit=milk_unit, 886 continent=continent, 887 ) 888 peak_yield = yields[int(t_peak) - 1] # -1 to prevent index error 889 # calculate milk yield at end of lactation 890 end_yield = yields[int(lactation_length) - 1] # -1 to prevent index error 891 892 # calculate persistency 893 persistency = (end_yield - peak_yield) / (lactation_length - t_peak) 894 return persistency
Persistency as the average slope after peak until end of lactation (numeric).
This is the default approach because symbolic derivation is not feasible for
all models. It computes:
(yield_at_end - yield_at_peak) / (lactation_length - time_to_peak)
Arguments:
- dim: DIM values.
- milkrecordings: Milk recordings (kg).
- model: Model name. Options include 'milkbot' (Bayesian or frequentist), 'wood', 'wilmink', 'ali_schaeffer', 'fischer'.
- fitting: 'frequentist' or 'bayesian'.
- key: API key (only for Bayesian fitting).
- parity: Parity of the cow; values above 3 treated as 3 (Bayesian).
- breed: 'H' or 'J' (Bayesian).
- custom_priors: provide your own priors for Bayesian fitting. provide as dictionary using build_prior() function to create the priors in the right format. Alternative use priors from the literature provided by the string command 'CHEN'
- milk_unit: Unit of milk recordings ('kg' or 'lb') for Bayesian fitting.
- continent: 'USA', 'EU', or 'CHEN' (Bayesian).
- lactation_length (int | str): 305 (default), 'max' (use max DIM), or integer.
Returns:
float: Average slope after the peak until end of lactation.
801def persistency_milkbot(d) -> float: 802 """Persistency from the MilkBot model (Ehrlich, 2013): `Persistency = 0.693 / d`. 803 804 Args: 805 d (float): Parameter `d` of the MilkBot model. 806 807 Returns: 808 float: Persistency value from the MilkBot formula. 809 """ 810 return 0.693 / d
Persistency from the MilkBot model (Ehrlich, 2013): Persistency = 0.693 / d.
Arguments:
- d (float): Parameter
dof the MilkBot model.
Returns:
float: Persistency value from the MilkBot formula.
788def persistency_wood(b, c) -> float: 789 """Persistency from Wood et al. (1984): `Persistency = -(b + 1) * ln(c)`. 790 791 Args: 792 b (float): Parameter `b` of the Wood model. 793 c (float): Parameter `c` of the Wood model. 794 795 Returns: 796 float: Persistency value from the Wood formula. 797 """ 798 return float(-(b + 1) * ln(c))
Persistency from Wood et al. (1984): Persistency = -(b + 1) * ln(c).
Arguments:
- b (float): Parameter
bof the Wood model. - c (float): Parameter
cof the Wood model.
Returns:
float: Persistency value from the Wood formula.
188def pivot_milk_recordings_to_matrix(df: pd.DataFrame) -> np.ndarray: 189 """Convert long-format recordings to a fixed 305-day matrix. 190 191 Rows represent lactations (``TestId``) and columns represent days in milk 192 from 1 through 305. Missing observations are kept as ``NaN``. 193 194 Args: 195 df: Dataframe with ``TestId``, ``DaysInMilk``, and ``MilkingYield``. 196 197 Returns: 198 A NumPy array of shape ``(n_lactations, 305)``. 199 """ 200 # ensure sorting 201 df = df.sort_values(["TestId", "DaysInMilk"]) 202 203 # pivot to wide format 204 milk_recordings_pivot = df.pivot_table( 205 index="TestId", columns="DaysInMilk", values="MilkingYield" 206 ) 207 208 # enforce fixed 305-day grid alignment used by best-prediction 209 milk_recordings_pivot = milk_recordings_pivot.reindex(columns=range(1, 306)) 210 211 # convert to numpy matrix 212 Y = milk_recordings_pivot.to_numpy() 213 return Y
Convert long-format recordings to a fixed 305-day matrix.
Rows represent lactations (TestId) and columns represent days in milk
from 1 through 305. Missing observations are kept as NaN.
Arguments:
- df: Dataframe with
TestId,DaysInMilk, andMilkingYield.
Returns:
A NumPy array of shape
(n_lactations, 305).
398def preprocess_measured_data(lactation: pd.DataFrame, standard_lc: np.ndarray) -> pd.Series: 399 """Build a 305-day deviation vector for a single lactation. 400 401 For observed days, this computes ``MilkingYield - standard_lc[day]``. 402 The result is reindexed to days 1..305 with unobserved days filled as zero. 403 404 Args: 405 lactation: Single-lactation dataframe with ``DaysInMilk`` and 406 ``MilkingYield``. 407 standard_lc: Expected daily milk yield profile. 408 409 Returns: 410 A Series indexed by day 1..305 containing milk-yield deviations. 411 """ 412 413 # calculate the difference between the expected (population mean) and measured milk yield 414 415 # extract the expected milk yields for the measured DaysInMilk in the df 416 day_idx = lactation["DaysInMilk"].to_numpy(dtype=int) - 1 417 expected = np.asarray(standard_lc, dtype=float)[day_idx] 418 419 # Subtract 420 lactation["MilkDifference"] = lactation["MilkingYield"].to_numpy(dtype=float) - expected 421 422 # Create a Series of length 305 with missing values = 0 423 milk_difference = cast(pd.Series, lactation.set_index("DaysInMilk")["MilkDifference"]) 424 corrected_series = milk_difference.reindex(range(1, 306), fill_value=0) 425 426 return corrected_series
Build a 305-day deviation vector for a single lactation.
For observed days, this computes MilkingYield - standard_lc[day].
The result is reindexed to days 1..305 with unobserved days filled as zero.
Arguments:
- lactation: Single-lactation dataframe with
DaysInMilkandMilkingYield. - standard_lc: Expected daily milk yield profile.
Returns:
A Series indexed by day 1..305 containing milk-yield deviations.
90def test_interval_method( 91 df: pd.DataFrame, 92 days_in_milk_col: str | None = None, 93 milking_yield_col: str | None = None, 94 test_id_col: str | None = None, 95 default_test_id: int = 0, 96 max_dim: int = 305, 97) -> pd.DataFrame: 98 """Compute total lactation milk yield using the ICAR Test Interval Method. 99 100 The method applies: 101 - First test day milk yield from calving to the first test day, 102 - Trapezoidal integration between consecutive test days, 103 - Last test day milk yield from the last test day to DIM = max_dim (default = 305). 104 105 Args: 106 df (pd.DataFrame): Input DataFrame with at least DaysInMilk and 107 MilkingYield columns, plus an optional TestId column. Column names 108 can be provided explicitly or matched via known aliases. 109 days_in_milk_col (str | None): Optional column name override for 110 DaysInMilk. 111 milking_yield_col (str | None): Optional column name override for 112 MilkingYield. 113 test_id_col (str | None): Optional column name override for TestId. 114 default_test_id (int): Value used to create a default TestId column if 115 one is missing. 116 max_dim (int): Lactation length used to calculate cumulative 117 production. The default is 305 days. 118 Records with DIM > max_dim are excluded. 119 120 Returns: 121 pd.DataFrame: Two-column DataFrame with 122 - "TestId": identifier per lactation, 123 - "LactationMilkYield": computed total milk yield over the 124 specified window. 125 126 Raises: 127 ValueError: If required columns (DaysInMilk or MilkingYield) cannot be found. 128 129 Notes: 130 - Records with DIM > max_dim are dropped before computation. 131 - At least two data points per TestId are required for trapezoidal integration; 132 otherwise the lactation is skipped. 133 """ 134 135 # Standardize columns and filter DIM <= max_dim 136 df = standardize_lactation_columns( 137 df, 138 days_in_milk_col=days_in_milk_col, 139 milking_yield_col=milking_yield_col, 140 test_id_col=test_id_col, 141 default_test_id=default_test_id, 142 max_dim=max_dim, 143 ) 144 145 result = [] 146 147 # Iterate over each lactation 148 for lactation in df["TestId"].unique(): 149 lactation_df = pd.DataFrame(df[df["TestId"] == lactation]) 150 151 # Sort by DaysInMilk ascending 152 lactation_df.sort_values(by="DaysInMilk", ascending=True, inplace=True) 153 154 if len(lactation_df) < 2: 155 print(f"Skipping TestId {lactation}: not enough data points for interpolation.") 156 continue 157 158 # Start and end points 159 start = lactation_df.iloc[0] 160 end = lactation_df.iloc[-1] 161 162 # Start contribution 163 MY0 = start["DaysInMilk"] * start["MilkingYield"] 164 165 # End contribution 166 MYend = (max_dim + 1 - end["DaysInMilk"]) * end["MilkingYield"] 167 168 # Intermediate trapezoidal contributions 169 lactation_df["width"] = lactation_df["DaysInMilk"].diff().shift(-1) 170 lactation_df["avg_yield"] = ( 171 lactation_df["MilkingYield"] + lactation_df["MilkingYield"].shift(-1) 172 ) / 2 173 lactation_df["trapezoid_area"] = lactation_df["width"] * lactation_df["avg_yield"] 174 175 total_intermediate = lactation_df["trapezoid_area"].sum() 176 177 total_yield = MY0 + total_intermediate + MYend 178 result.append((lactation, total_yield)) 179 180 return pd.DataFrame(result, columns=pd.Index(["TestId", "LactationMilkYield"]))
Compute total lactation milk yield using the ICAR Test Interval Method.
The method applies:
- First test day milk yield from calving to the first test day,
- Trapezoidal integration between consecutive test days,
- Last test day milk yield from the last test day to DIM = max_dim (default = 305).
Arguments:
- df (pd.DataFrame): Input DataFrame with at least DaysInMilk and MilkingYield columns, plus an optional TestId column. Column names can be provided explicitly or matched via known aliases.
- days_in_milk_col (str | None): Optional column name override for DaysInMilk.
- milking_yield_col (str | None): Optional column name override for MilkingYield.
- test_id_col (str | None): Optional column name override for TestId.
- default_test_id (int): Value used to create a default TestId column if one is missing.
- max_dim (int): Lactation length used to calculate cumulative production. The default is 305 days. Records with DIM > max_dim are excluded.
Returns:
pd.DataFrame: Two-column DataFrame with - "TestId": identifier per lactation, - "LactationMilkYield": computed total milk yield over the specified window.
Raises:
- ValueError: If required columns (DaysInMilk or MilkingYield) cannot be found.
Notes:
- Records with DIM > max_dim are dropped before computation.
- At least two data points per TestId are required for trapezoidal integration; otherwise the lactation is skipped.