lactationcurve.preprocessing
1from .validate_and_standardize import ( 2 LACTATION_COLUMN_ALIASES, 3 PreparedInputs, 4 normalize_lactation_column_name, 5 resolve_lactation_column_mapping, 6 standardize_lactation_columns, 7 validate_and_prepare_inputs, 8) 9 10__all__ = [ 11 "LACTATION_COLUMN_ALIASES", 12 "PreparedInputs", 13 "normalize_lactation_column_name", 14 "resolve_lactation_column_mapping", 15 "standardize_lactation_columns", 16 "validate_and_prepare_inputs", 17]
211@dataclass 212class PreparedInputs: 213 """Normalized, ready‑to‑fit inputs. 214 215 This container is returned by `validate_and_prepare_inputs` and is the single 216 hand‑off object expected by the fitting routines. Arrays are finite and 1‑dimensional; 217 categorical fields are lower/upper‑cased as appropriate and may be `None` if omitted. 218 219 Attributes: 220 dim: 1D NumPy array of day‑in‑milk values (finite; same length as `milkrecordings`). 221 milkrecordings: 1D NumPy array of test‑day milk yields aligned to `dim`. 222 model: Lowercased model identifier or `None` if not provided. 223 fitting: `"frequentist"` or `"bayesian"` (lowercased) or `None`. 224 breed: `"H"` or `"J"` or `None`. 225 parity: Lactation number as `int`, if provided; otherwise `None`. 226 continent: Prior source for MilkBot API (`"USA"`, `"EU"`), or `None`. 227 persistency_method: Either `"derived"` or `"literature"`, or `None`. 228 lactation_length: Integer horizon (e.g., 305), the string `"max"`, or `None`. 229 milk_unit: Either `"kg"` or `"lb"`, defaulting to `"kg"`. 230 custom_priors: Either a dict of priors, the string `"CHEN"` to use Chen et al. priors, 231 or `None` if not provided. 232 """ 233 234 dim: np.ndarray 235 milkrecordings: np.ndarray 236 model: str | None = None 237 fitting: str | None = None 238 breed: str | None = None 239 parity: int | None = None 240 continent: str | None = None 241 persistency_method: str | None = None 242 lactation_length: int | str | None = None 243 milk_unit: str | None = None 244 custom_priors: MilkBotPriors | str | None = None
Normalized, ready‑to‑fit inputs.
This container is returned by validate_and_prepare_inputs and is the single
hand‑off object expected by the fitting routines. Arrays are finite and 1‑dimensional;
categorical fields are lower/upper‑cased as appropriate and may be None if omitted.
Attributes:
- dim: 1D NumPy array of day‑in‑milk values (finite; same length as
milkrecordings). - milkrecordings: 1D NumPy array of test‑day milk yields aligned to
dim. - model: Lowercased model identifier or
Noneif not provided. - fitting:
"frequentist"or"bayesian"(lowercased) orNone. - breed:
"H"or"J"orNone. - parity: Lactation number as
int, if provided; otherwiseNone. - continent: Prior source for MilkBot API (
"USA","EU"), orNone. - persistency_method: Either
"derived"or"literature", orNone. - lactation_length: Integer horizon (e.g., 305), the string
"max", orNone. - milk_unit: Either
"kg"or"lb", defaulting to"kg". - custom_priors: Either a dict of priors, the string
"CHEN"to use Chen et al. priors, orNoneif not provided.
139def normalize_lactation_column_name(column: str) -> str: 140 """Normalize a lactation-data column label for alias matching.""" 141 return re.sub(r"[^a-z0-9]+", "", str(column).strip().lower())
Normalize a lactation-data column label for alias matching.
155def resolve_lactation_column_mapping( 156 columns: Sequence[str], 157 *, 158 days_in_milk_col: str | None = None, 159 milking_yield_col: str | None = None, 160 test_id_col: str | None = None, 161 test_calender_date_col: str | None = None, 162 require_test_id: bool = False, 163) -> dict[str, str]: 164 """Resolve flexible lactation-data headers to canonical column names. 165 166 The returned mapping is ``canonical name -> original uploaded column``. 167 ``DaysInMilk`` and ``MilkingYield`` are required because the lactation 168 calculations cannot run without them. ``TestId`` is optional by default so 169 callers can choose whether to create a single-lactation fallback. 170 """ 171 172 columns_by_normalized_name: dict[str, str] = {} 173 for column in columns: 174 normalized = normalize_lactation_column_name(column) 175 if normalized and normalized not in columns_by_normalized_name: 176 columns_by_normalized_name[normalized] = column 177 178 resolved: dict[str, str] = {} 179 requested_columns = { 180 "DaysInMilk": days_in_milk_col, 181 "MilkingYield": milking_yield_col, 182 "TestId": test_id_col, 183 "TestCalendarDate": test_calender_date_col, 184 } 185 186 for canonical, requested in requested_columns.items(): 187 if requested: 188 match = columns_by_normalized_name.get(normalize_lactation_column_name(requested)) 189 if match is None: 190 raise ValueError(f"Column '{requested}' was not found.") 191 else: 192 match = _first_matching_column( 193 columns_by_normalized_name, LACTATION_COLUMN_ALIASES[canonical] 194 ) 195 196 if match is not None: 197 resolved[canonical] = match 198 199 missing_required = [ 200 canonical for canonical in ("DaysInMilk", "MilkingYield") if canonical not in resolved 201 ] 202 if require_test_id and "TestId" not in resolved: 203 missing_required.append("TestId") 204 if missing_required: 205 expected = ", ".join(missing_required) 206 raise ValueError(f"No lactation column found for: {expected}.") 207 208 return resolved
Resolve flexible lactation-data headers to canonical column names.
The returned mapping is canonical name -> original uploaded column.
DaysInMilk and MilkingYield are required because the lactation
calculations cannot run without them. TestId is optional by default so
callers can choose whether to create a single-lactation fallback.
407def standardize_lactation_columns( 408 df: pd.DataFrame, 409 *, 410 days_in_milk_col: str | None = None, 411 milking_yield_col: str | None = None, 412 test_id_col: str | None = None, 413 test_calender_date_col: str | None = None, 414 default_test_id=0, 415 max_dim: int | str = 305, 416 lactation_start_grace_period: int = 0, 417) -> pd.DataFrame: 418 """ 419 Standardize column names and structure for lactation data. 420 421 Returns 422 ------- 423 df_out : pd.DataFrame 424 Copy of df with standardized columns: 425 - DaysInMilk 426 - MilkingYield 427 - TestId 428 - TestCalendarDate (if provided) 429 """ 430 431 if not isinstance(df, pd.DataFrame): 432 raise TypeError("df must be a pandas DataFrame.") 433 434 df = df.copy() 435 mapping = resolve_lactation_column_mapping( 436 [str(col) for col in df.columns], 437 days_in_milk_col=days_in_milk_col, 438 milking_yield_col=milking_yield_col, 439 test_id_col=test_id_col, 440 test_calender_date_col=test_calender_date_col, 441 ) 442 dim_col = mapping["DaysInMilk"] 443 yield_col = mapping["MilkingYield"] 444 id_col = mapping.get("TestId") 445 test_calender_date_col = mapping.get("TestCalendarDate") 446 447 # Create TestId if missing 448 if not id_col: 449 df["TestId"] = default_test_id 450 id_col = "TestId" 451 452 # Rename to standardized names 453 df = df.rename( 454 columns={ 455 dim_col: "DaysInMilk", 456 yield_col: "MilkingYield", 457 id_col: "TestId", 458 test_calender_date_col: "TestCalendarDate" if test_calender_date_col else None, 459 } 460 ) 461 462 # Filter DIM 463 if isinstance(max_dim, str) and max_dim.lower() == "max": 464 df = pd.DataFrame(df) 465 else: 466 df = pd.DataFrame(df[df["DaysInMilk"] <= int(max_dim)]) 467 468 return df
Standardize column names and structure for lactation data.
Returns
df_out : pd.DataFrame Copy of df with standardized columns: - DaysInMilk - MilkingYield - TestId - TestCalendarDate (if provided)
247def validate_and_prepare_inputs( 248 dim, 249 milkrecordings, 250 model=None, 251 fitting=None, 252 *, 253 breed=None, 254 parity=None, 255 continent=None, 256 persistency_method=None, 257 lactation_length=None, 258 milk_unit="kg", 259 custom_priors=None, 260) -> PreparedInputs: 261 """ 262 Validate, normalize, and clean input data for lactation curve fitting. 263 264 This function performs basic consistency checks on the provided 265 days-in-milk (DIM) and milk recording data, normalizes optional 266 categorical parameters, and removes observations with missing or 267 non-finite values. The cleaned and validated inputs are returned 268 in a structured :class:`PreparedInputs` object. 269 270 Parameters 271 ---------- 272 dim : array-like 273 Days in milk corresponding to each milk recording. 274 milkrecordings : array-like 275 Milk yield measurements corresponding to `dim`. 276 model : str or None, optional 277 Name of the lactation curve model. If provided, the name is 278 stripped of whitespace and converted to lowercase. 279 fitting : str or None, optional 280 Fitting approach to be used. Must be either ``"frequentist"`` 281 or ``"bayesian"`` if provided. 282 breed : str or None, optional 283 Cow breed identifier. Must be ``"H"`` (Holstein) or ``"J"`` 284 (Jersey) if provided. Case-insensitive. 285 parity : int or None, optional 286 Lactation number (parity). If provided, it is coerced to an 287 integer. 288 continent : str or None, optional 289 Geographic region identifier. Must be one of ``"USA"`` or 290 ``"EU"`` if provided. Case-insensitive. 291 milk_unit : str, optional 292 Unit of milk yield measurements. Must be either ``"kg"`` or ``"lb"``. Default is ``"kg"``. 293 custom_priors : dict or str or None, optional 294 Custom prior distributions for Bayesian fitting. If a dict is provided, 295 it must be a dictionary of prior distributions for each parameter in the model. 296 If the string ``"CHEN"`` is provided, the default Chen et al. priors are used. 297 298 Extra input for persistency calculation: 299 persistency_method (String): way of calculating 300 persistency, options: 'derived' which gives the 301 average slope of the lactation after the peak until 302 the end of lactation (default) or 'literature' for 303 the wood and milkbot model. 304 Lactation_length: string or int: length of the lactation 305 in days to calculate persistency over, options: 306 305 = default or 'max' uses the maximum DIM in the 307 data, or an integer value to set the desired 308 lactation length. 309 310 Returns 311 ------- 312 PreparedInputs 313 A dataclass containing the cleaned numeric arrays (`dim`, 314 `milkrecordings`) and the normalized optional parameters. 315 316 Raises 317 ------ 318 ValueError 319 If input arrays have different lengths, contain insufficient 320 valid observations, or if categorical parameters are invalid. 321 322 Notes 323 ----- 324 Observations with missing or non-finite values in either `dim` or 325 `milkrecordings` are removed prior to model fitting. At least two 326 valid observations are required to proceed. 327 """ 328 if len(dim) != len(milkrecordings): 329 raise ValueError("dim and milkrecordings must have the same length") 330 331 model = model.strip().lower() if model else None 332 333 if parity is not None: 334 parity = int(parity) 335 336 if fitting is not None: 337 fitting = fitting.lower() 338 if fitting not in {"frequentist", "bayesian"}: 339 raise ValueError("Fitting method must be either frequentist or bayesian") 340 341 if breed is not None: 342 breed = breed.upper() 343 if breed not in {"H", "J"}: 344 raise ValueError("Breed must be either Holstein = 'H' or Jersey 'J'") 345 346 if continent is not None: 347 continent = continent.upper() 348 if continent not in {"USA", "EU"}: 349 raise ValueError("continent must be 'USA' or 'EU'") 350 351 dim = np.asarray(dim, dtype=float) 352 milkrecordings = np.asarray(milkrecordings, dtype=float) 353 354 mask = np.isfinite(dim) & np.isfinite(milkrecordings) 355 dim = dim[mask] 356 milkrecordings = milkrecordings[mask] 357 358 if len(dim) < 2: 359 raise ValueError("At least two non missing points are required to fit a lactation curve") 360 361 if persistency_method is not None: 362 persistency_method = persistency_method.lower() 363 if persistency_method not in {"derived", "literature"}: 364 raise ValueError("persistency_method must be either 'derived' or 'literature'") 365 366 if lactation_length is not None: 367 if isinstance(lactation_length, str): 368 if lactation_length.lower() != "max": 369 raise ValueError("lactation_length string option must be 'max'") 370 else: 371 lactation_length = int(lactation_length) 372 373 if milk_unit not in ["kg", "lb"]: 374 raise ValueError("milk_unit must be 'kg' or 'lb'") 375 376 if custom_priors is not None and not isinstance(custom_priors, (dict, str)): 377 raise ValueError("custom_priors must be a dict, a string, or None") 378 379 if isinstance(custom_priors, str): 380 custom_priors = custom_priors.upper() 381 if custom_priors != "CHEN": 382 raise ValueError( 383 "custom_priors string option must be" 384 " 'CHEN', self defined priors can be" 385 " provided as a dictionary through" 386 " the build_prior function" 387 ) 388 389 if isinstance(custom_priors, dict): 390 custom_priors = cast(MilkBotPriors, custom_priors) 391 392 return PreparedInputs( 393 dim=dim, 394 milkrecordings=milkrecordings, 395 model=model or None, 396 fitting=fitting, 397 breed=breed, 398 parity=parity, 399 continent=continent, 400 persistency_method=persistency_method, 401 lactation_length=lactation_length, 402 milk_unit=milk_unit, 403 custom_priors=custom_priors, 404 )
Validate, normalize, and clean input data for lactation curve fitting.
This function performs basic consistency checks on the provided
days-in-milk (DIM) and milk recording data, normalizes optional
categorical parameters, and removes observations with missing or
non-finite values. The cleaned and validated inputs are returned
in a structured PreparedInputs object.
Parameters
dim : array-like
Days in milk corresponding to each milk recording.
milkrecordings : array-like
Milk yield measurements corresponding to dim.
model : str or None, optional
Name of the lactation curve model. If provided, the name is
stripped of whitespace and converted to lowercase.
fitting : str or None, optional
Fitting approach to be used. Must be either "frequentist"
or "bayesian" if provided.
breed : str or None, optional
Cow breed identifier. Must be "H" (Holstein) or "J"
(Jersey) if provided. Case-insensitive.
parity : int or None, optional
Lactation number (parity). If provided, it is coerced to an
integer.
continent : str or None, optional
Geographic region identifier. Must be one of "USA" or
"EU" if provided. Case-insensitive.
milk_unit : str, optional
Unit of milk yield measurements. Must be either "kg" or "lb". Default is "kg".
custom_priors : dict or str or None, optional
Custom prior distributions for Bayesian fitting. If a dict is provided,
it must be a dictionary of prior distributions for each parameter in the model.
If the string "CHEN" is provided, the default Chen et al. priors are used.
Extra input for persistency calculation:
persistency_method (String): way of calculating persistency, options: 'derived' which gives the average slope of the lactation after the peak until the end of lactation (default) or 'literature' for the wood and milkbot model. Lactation_length: string or int: length of the lactation in days to calculate persistency over, options: 305 = default or 'max' uses the maximum DIM in the data, or an integer value to set the desired lactation length.
Returns
PreparedInputs
A dataclass containing the cleaned numeric arrays (dim,
milkrecordings) and the normalized optional parameters.
Raises
ValueError If input arrays have different lengths, contain insufficient valid observations, or if categorical parameters are invalid.
Notes
Observations with missing or non-finite values in either dim or
milkrecordings are removed prior to model fitting. At least two
valid observations are required to proceed.