# LactCurveModels

<!-- badges: start -->
![CRAN status](https://www.r-pkg.org/badges/version/LactCurveModels)
![License: GPL-3](https://img.shields.io/badge/License-GPL3-blue.svg)
![R](https://img.shields.io/badge/R-%3E%3D4.0-brightgreen)
<!-- badges: end -->

## Overview

**LactCurveModels** is an R package for fitting, comparing, and visualising
nonlinear lactation curve models for dairy animals. It fits up to **20
published lactation curve models** simultaneously to daily milk yield data,
produces publication-ready diagnostic figures, and generates comprehensive
goodness-of-fit tables -- all from a single function call.

The package supports **batch processing** of multiple animals from one CSV
file, with flexible options to analyse all animals or a selected subset, and
to fit all 20 models or any chosen combination.

---

## The 20 Lactation Curve Models

| No. | Model Name | Reference |
|-----|------------|-----------|
| 1  | Brody (1923)            | Brody, 1923                  |
| 2  | Brody (1924)            | Brody, 1924                  |
| 3  | Parabolic Exponential   | Sikka, 1950                  |
| 4  | Wood                    | Wood, 1967                   |
| 5  | Wood-Dhanoa             | Dhanoa, 1981                 |
| 6  | Cobby and Le Du         | Cobby and Le Du, 1978        |
| 7  | Quadratic               | Dave, 1971                   |
| 8  | Mixed Log               | Guo and Swalve, 1995         |
| 9  | Khandekar               | Khandekar, 1993              |
| 10 | Wilmink (k = 0.05)      | Wilmink, 1987                |
| 11 | Wilmink (k estimated)   | Wilmink, 1987                |
| 12 | Ali and Schaeffer       | Ali and Schaeffer, 1987      |
| 13 | Cappio-Borlino          | Cappio-Borlino et al., 1995  |
| 14 | Papajcsik and Bodero 1  | Papajcsik and Bodero, 1988   |
| 15 | Papajcsik and Bodero 2  | Papajcsik and Bodero, 1988   |
| 16 | Papajcsik and Bodero 3  | Papajcsik and Bodero, 1988   |
| 17 | Inverse Polynomial      | Nelder, 1966                 |
| 18 | Log-Quadratic           | Adediran et al., 2012        |
| 19 | Morant and Gnanasakthy  | Morant and Gnanasakthy, 1989 |
| 20 | Pollott Multiplicative  | Pollott, 2000                |

---

## Installation

### From CRAN (once published)

```r
install.packages("LactCurveModels")
```

### From GitHub (development version)

```r
# install.packages("devtools")
devtools::install_github("VenkatesanRaja/LactCurveModels")
```

---

## Input Data Format

The package reads a CSV file with exactly **three columns** (column order does
not matter):

| Column    | Type      | Description                                           |
|-----------|-----------|-------------------------------------------------------|
| animal_id | character | Unique identifier for each animal                     |
| dim       | integer   | Days-in-milk time index (fortnightly: 1, 2, ..., 20)  |
| dmy       | numeric   | Daily milk yield (kg/day)                             |

**Example CSV layout:**

```
animal_id,dim,dmy
Animal_A,1,9.265
Animal_A,2,9.957
Animal_A,3,10.421
Animal_B,1,8.100
Animal_B,2,8.750
```

---

## Usage

### Analyse all animals with all 20 models

```r
library(LactCurveModels)

results <- run_lactation_analysis(
  input_csv_path = "C:/data/myanimals.csv"
)
```

### Analyse selected animals only

```r
results <- run_lactation_analysis(
  input_csv_path   = "C:/data/myanimals.csv",
  selected_animals = c("Animal_A", "Animal_B")
)
```

### Fit selected models only

```r
results <- run_lactation_analysis(
  input_csv_path  = "C:/data/myanimals.csv",
  selected_models = c("Wood_1967", "Wilmink_k005", "Ali_Schaeffer")
)
```

### Combine both selections with a custom output folder

```r
results <- run_lactation_analysis(
  input_csv_path   = "C:/data/myanimals.csv",
  selected_models  = c("Wood_1967", "Wilmink_k005", "Ali_Schaeffer",
                       "Pollott_Multiplicative"),
  selected_animals = c("Animal_A", "Animal_C"),
  out_dir          = "C:/results/lactation_analysis"
)
```

### Fit models directly (advanced use)

```r
# Build the data frame manually
animal_df <- data.frame(
  x = 1:20,
  y = c(9.3, 9.9, 10.2, 10.4, 10.3, 10.1, 9.9, 9.6, 9.3, 9.0,
        8.7, 8.4, 8.1,  7.8,  7.5,  7.2,  6.9, 6.6, 6.3, 6.0),
  z = (1:20) / 365
)

fits <- fit_lactation_models(animal_df, selected_models = "all")

# Extract results for Wood (1967)
fits[["Wood_1967"]]$metrics
fits[["Wood_1967"]]$predictions
coef(fits[["Wood_1967"]]$model)
```

---

## Outputs

For **each animal**, the following are saved in a dedicated sub-folder:

### CSV Tables (4 files per animal)

| File | Contents |
|------|----------|
| AnimalID_parameter_estimates.csv         | Fitted parameters and standard errors for all models  |
| AnimalID_summary_metrics.csv             | R2, Adjusted R2, AIC, BIC, RMSE, Durbin-Watson        |
| AnimalID_actual_and_predicted_values.csv | Observed vs predicted milk yield at each time point   |
| AnimalID_residuals.csv                   | Residuals (predicted minus actual) at each time point |

### Diagnostic Figures (15 PNG files per animal)

| Figure | Description |
|--------|-------------|
| Fig01  | All fitted models overlaid on observed data                     |
| Fig02  | 4-panel ranked model fits (best to worst R2)                    |
| Fig03  | Best 3 vs Worst 3 models                                        |
| Fig04  | Models grouped by mathematical family                           |
| Fig05  | Residual diagnostics for top 4 models (4 sub-plots each)        |
| Fig06  | Residual bubble chart across all models and time points         |
| Fig07  | R2 and Adjusted R2 bar chart                                    |
| Fig08  | RMSE bar chart                                                  |
| Fig09  | AIC and BIC bar chart                                           |
| Fig10  | Durbin-Watson statistic bar chart                               |
| Fig11  | R2 vs RMSE performance bubble chart (coloured by model family)  |
| Fig12  | Multi-metric ranking dot-plot (6 metrics simultaneously)        |
| Fig13  | Predicted vs actual scatter plots (one panel per model)         |
| Fig14  | Pearson correlation heatmap of model predictions                |
| Fig15  | Predicted peak yield and time-to-peak bar charts                |

### Combined Cross-Animal Outputs (produced when more than 1 animal is analysed)

| File | Contents |
|------|----------|
| COMBINED_summary_metrics_all_animals.csv     | All metrics for all animals and models      |
| COMBINED_parameter_estimates_all_animals.csv | All parameter estimates across animals      |
| COMBINED_best_model_per_animal.csv           | Best fitting model for each animal          |
| COMBINED_Fig_R2_CrossAnimal.png              | R2 comparison across all animals            |
| COMBINED_Fig_RMSE_CrossAnimal.png            | RMSE comparison across all animals          |
| COMBINED_Fig_BestModel_Overlay.png           | Best-fit curves for all animals on one plot |

---

## Output Folder Structure

```
lactation_results/
|-- Animal_A/
|   |-- Animal_A_parameter_estimates.csv
|   |-- Animal_A_summary_metrics.csv
|   |-- Animal_A_actual_and_predicted_values.csv
|   |-- Animal_A_residuals.csv
|   |-- Fig01_All_Models_Overlay.png
|   |-- Fig02_Ranked_Panels.png
|   |-- Fig03_Best_vs_Worst.png
|   |-- Fig04_Family_Panels.png
|   |-- Fig05_Residuals_ModelName.png
|   |-- Fig06_Residual_BubbleChart.png
|   |-- Fig07_R2_AdjR2.png
|   |-- Fig08_RMSE.png
|   |-- Fig09_AIC_BIC.png
|   |-- Fig10_DurbinWatson.png
|   |-- Fig11_R2_RMSE_Bubble.png
|   |-- Fig12_ModelRanking.png
|   |-- Fig13_Pred_vs_Actual.png
|   |-- Fig14_Correlation_Heatmap.png
|   `-- Fig15_Peak_Yield_Time.png
|-- Animal_B/
|   `-- (same structure as Animal_A)
|-- COMBINED_summary_metrics_all_animals.csv
|-- COMBINED_parameter_estimates_all_animals.csv
|-- COMBINED_best_model_per_animal.csv
|-- COMBINED_Fig_R2_CrossAnimal.png
|-- COMBINED_Fig_RMSE_CrossAnimal.png
`-- COMBINED_Fig_BestModel_Overlay.png
```

---

## Valid Model Names

Use these exact strings in the `selected_models` argument:

```r
"Brody_1923"             "Brody_1924"             "Parabolic_Exp_Sikka"
"Wood_1967"              "Wood_Dhanoa"             "Cobby_LeDu"
"Quadratic_Dave"         "Mixed_Log_GS"            "Khandekar"
"Wilmink_k005"           "Wilmink_k_estimated"     "Ali_Schaeffer"
"Cappio_Borlino"         "Papajcsik_Bodero1"       "Papajcsik_Bodero2"
"Papajcsik_Bodero3"      "Inverse_Poly_Nelder"     "Log_Quadratic_Adediran"
"Morant_Gnanasakthy"     "Pollott_Multiplicative"
```

---

## Goodness-of-Fit Metrics

The package computes and reports the following metrics for every fitted model:

| Metric                         | Symbol  | Interpretation                               |
|--------------------------------|---------|----------------------------------------------|
| Coefficient of Determination   | R2      | Higher is better (maximum = 1)               |
| Adjusted R2                    | Adj. R2 | Penalises extra parameters; higher is better |
| Root Mean Square Error         | RMSE    | Lower is better (units: kg/day)              |
| Akaike Information Criterion   | AIC     | Lower is better                              |
| Bayesian Information Criterion | BIC     | Lower is better                              |
| Durbin-Watson Statistic        | DW      | Ideal = 2.0; range 1.5 to 2.5 is acceptable |

---

## Authors

| Name             | Role               | Email                              |
|------------------|--------------------|------------------------------------|
| Raja TV          | Author, Maintainer | venkatesanraja09@gmail.com         |
| Lalremruati PC   | Author             | lalremruatichalthleng221@gmail.com |
| Priyadharshini P | Author             | priyapandian733@gmail.com          |
| Nidhishree NS    | Author             | nidhishreens9216@gmail.com         |
| Dheeraj Gurjar   | Author             | dheeraj.gurjar.singh@gmail.com     |
| Rani Alex        | Author             | ranialex01vet@gmail.com            |
| Vikas Vohra      | Author             | vohravikas@gmail.com               |

---

## License

This package is licensed under the **GNU General Public License v3.0**.
See [GPL-3.0 License](https://www.gnu.org/licenses/gpl-3.0.html) for details.

---

## Citation

If you use **LactCurveModels** in your research, please cite it as:

```
Raja TV, Lalremruati PC, Priyadharshini P, Nidhishree NS, Gurjar D,
Alex R, Vohra V (2025). LactCurveModels: Lactation Curve Model Fitting
for Dairy Animals. R package version 0.1.0.
https://github.com/VenkatesanRaja/LactCurveModels
```

To get the citation from within R:

```r
citation("LactCurveModels")
```

---

## Bug Reports and Contributions

- **Bug reports:** https://github.com/VenkatesanRaja/LactCurveModels/issues
- **Pull requests** are welcome for new models, additional figure types, or
  performance improvements.
