---
title: "Introduction to Dairy Life Cycle Assessment"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to Dairy Life Cycle Assessment}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  fig.alt = "Figura generada por la viñeta; ver texto para detalles.",
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5,
  warning = FALSE,
  message = FALSE
)

# Load required packages
library(cowfootR)
library(ggplot2)
library(dplyr)
```

# Introduction to Dairy Life Cycle Assessment

## Overview

The dairy industry plays a crucial role in global food security, but it also contributes significantly to greenhouse gas emissions. Understanding and quantifying the environmental impact of dairy production is essential for sustainable development and climate change mitigation.

The **cowfootR** package provides a comprehensive toolkit for calculating dairy farm carbon footprints following internationally recognized standards, specifically the International Dairy Federation (IDF) 2022 guidelines and IPCC 2019 methodologies.

## How to Use This Vignette

This vignette is designed as a step-by-step tutorial for new users of
**cowfootR**. It introduces the concepts of dairy life cycle assessment (LCA)
and demonstrates how to calculate greenhouse gas emissions for a single farm.

You can:
- Read it sequentially as a guided example, or
- Jump directly to the sections of interest (e.g., emissions, intensities, or visualization).

All examples use simplified, hypothetical data intended for learning purposes.

## Theoretical Background

### Life Cycle Assessment in Dairy Production

Life Cycle Assessment (LCA) is a systematic approach to evaluating the environmental impacts of a product or service throughout its entire life cycle. In dairy production, LCA helps quantify greenhouse gas emissions from various sources within the farm system.

### Key Emission Sources in Dairy Systems

Dairy farm emissions primarily originate from five main sources:

1. **Enteric Fermentation**: Methane (CH₄) produced during digestion in ruminants
2. **Manure Management**: CH₄ and nitrous oxide (N₂O) from manure storage and treatment
3. **Soil Emissions**: N₂O from nitrogen fertilizers and excreta deposition
4. **Energy Use**: Carbon dioxide (CO₂) from fossil fuel combustion and electricity
5. **Purchased Inputs**: Embodied emissions in feeds, fertilizers, and materials

### System Boundaries

System boundaries define which processes are included in the assessment:

- **Farm Gate**: Includes on-farm emissions only
- **Cradle-to-Farm Gate**: Includes upstream production of inputs
- **Partial**: Custom selection of emission sources

### Functional Units and Intensity Metrics

Results are expressed using functional units that allow meaningful comparisons:

- **kg CO₂eq per kg FPCM**: Fat and Protein Corrected Milk intensity
- **kg CO₂eq per hectare**: Land use intensity
- **Absolute emissions**: Total farm emissions in kg CO₂eq per year

## Getting Started with cowfootR

### Installation

```{r eval=FALSE}
# Install from CRAN (when available)
install.packages("cowfootR")

# Or install development version from GitHub
# devtools::install_github("yourusername/cowfootR")
```

### Loading the Package

```{r}
library(cowfootR)
```
### Input Data Structure

Most `cowfootR` functions expect farm information either as:
- Individual numeric arguments (e.g. number of animals, litres of milk), or
- A structured list containing farm characteristics.

In this vignette, we use a simple list (`farm_data`) to keep all farm-related
information together. This approach improves readability and makes it easier
to reuse the same data across multiple calculation steps.

Most emission functions return a **list** containing:
- Total emissions for that source (kg CO₂eq)
- A breakdown by gas or process
- Metadata describing the calculation method

### Basic Workflow

The typical cowfootR workflow involves four main steps:

1. **Define system boundaries**
2. **Calculate emissions by source**
3. **Aggregate total emissions**
4. **Calculate intensity metrics**


## Data Requirements: Required vs Optional

### Required Data

The following information is required to run the core cowfootR functions and
perform a basic farm-level carbon footprint assessment:

- Herd size and composition
- Annual milk production
- Total farm area
- Major nitrogen inputs (fertilizer or excreta)

### Optional but Recommended Data

Providing additional farm-specific information improves the accuracy and
interpretability of results:

- Detailed feed quantities and composition
- Animal productivity parameters (e.g. milk yield per cow)
- Energy use disaggregated by source
- Soil type and climate characteristics
- Allocation of land use by category

If some optional data are not available, cowfootR applies default values based
on IPCC and IDF guidance. However, users are encouraged to provide farm-specific
data whenever possible.

Let's walk through a simple example:

## Example: Basic Farm Assessment

### Step 1: Define System Boundaries

```{r}
# Define farm-gate boundaries (most common approach)
boundaries <- set_system_boundaries("farm_gate")
boundaries
```

### Step 2: Basic Farm Data

For this example, we'll use data from a typical dairy farm:

```{r}
# Farm characteristics
farm_data <- list(
  # Herd composition
  dairy_cows = 100,
  heifers = 30,
  calves = 25,

  # Production
  milk_litres = 600000, # Annual milk production
  milk_yield_per_cow = 6000, # kg/cow/year

  # Farm area
  total_area_ha = 120,
  productive_area_ha = 110,

  # Inputs
  concentrate_kg = 180000, # Annual concentrate use
  n_fertilizer_kg = 1500, # Nitrogen fertilizer
  diesel_litres = 8000, # Annual diesel consumption
  electricity_kwh = 35000 # Annual electricity use
)

farm_data
```

### Step 3: Calculate Emissions by Source

Now we calculate emissions from each source using the individual calculation functions:

#### Enteric Fermentation

Enteric fermentation is typically the largest source of emissions in dairy
systems. The function `calc_emissions_enteric()` estimates methane emissions
from ruminal fermentation based on animal numbers, productivity, and the
selected IPCC Tier.

In this example, we use Tier 2 to incorporate milk yield into the calculation.
```{r}
# Calculate enteric methane emissions
enteric_emissions <- calc_emissions_enteric(
  n_animals = farm_data$dairy_cows,
  cattle_category = "dairy_cows",
  avg_milk_yield = farm_data$milk_yield_per_cow,
  tier = 2, # Use Tier 2 for more accurate results
  boundaries = boundaries
)

enteric_emissions
```

#### Manure Management

Manure management emissions include both methane (CH₄) and nitrous oxide (N₂O)
released during manure storage, handling, and application. The function
`calc_emissions_manure()` estimates these emissions based on the number of
animals, manure management system, and the selected IPCC Tier.

Here, a pasture-based manure system is assumed, which is common in extensive
and mixed dairy systems.

```{r}
# Calculate manure management emissions
manure_emissions <- calc_emissions_manure(
  n_cows = farm_data$dairy_cows,
  manure_system = "pasture", # Typical for extensive systems
  tier = 2,
  include_indirect = TRUE,
  boundaries = boundaries
)

manure_emissions
```

#### Soil Emissions

Soil-related emissions are mainly associated with nitrous oxide (N₂O) released
from nitrogen inputs to agricultural soils. The function `calc_emissions_soil()`
estimates direct and indirect soil N₂O emissions resulting from synthetic
fertilizers and animal excreta deposited on pasture.

This example uses generalized assumptions for soil type and climate, which can
be refined when site-specific information is available.


```{r}
# Calculate soil N2O emissions
soil_emissions <- calc_emissions_soil(
  n_fertilizer_synthetic = farm_data$n_fertilizer_kg,
  n_excreta_pasture = farm_data$dairy_cows * 100, # Estimated N excretion
  area_ha = farm_data$total_area_ha,
  soil_type = "well_drained",
  climate = "temperate",
  include_indirect = TRUE,
  boundaries = boundaries
)

soil_emissions
```

#### Energy Use

Energy-related emissions originate from the combustion of fossil fuels and the
use of electricity on the farm. The function `calc_emissions_energy()` estimates
carbon dioxide (CO₂) emissions from diesel and electricity consumption, using
country- or region-specific emission factors when available.

In this example, electricity emissions are calculated using national grid
factors for Uruguay.


```{r}
# Calculate energy-related emissions
energy_emissions <- calc_emissions_energy(
  diesel_l = farm_data$diesel_litres,
  electricity_kwh = farm_data$electricity_kwh,
  country = "UY", # Uruguay electricity grid
  boundaries = boundaries
)

energy_emissions
```

#### Purchased Inputs

Purchased inputs include emissions embodied in externally produced goods such
as concentrates, fertilizers, and other materials used on the farm. The
function `calc_emissions_inputs()` accounts for these upstream emissions using
average emission factors.

This component is particularly relevant when system boundaries extend beyond
the farm gate to include upstream processes.


```{r}
# Calculate emissions from purchased inputs
input_emissions <- calc_emissions_inputs(
  conc_kg = farm_data$concentrate_kg,
  fert_n_kg = farm_data$n_fertilizer_kg,
  region = "global", # Use global emission factors
  boundaries = boundaries
)

input_emissions
```

### Step 4: Aggregate Total Emissions


After calculating emissions for each individual source, the function
`calc_total_emissions()` aggregates all components into a single result. The
output includes total farm emissions and a breakdown by source, which is useful
for identifying the main contributors to the carbon footprint.

```{r}
# Combine all emission sources
total_emissions <- calc_total_emissions(
  enteric_emissions,
  manure_emissions,
  soil_emissions,
  energy_emissions,
  input_emissions
)

total_emissions
```

### Step 5: Calculate Intensity Metrics


While absolute emissions provide information on the total environmental impact
of a farm, intensity metrics relate emissions to production or land use. These
metrics allow comparisons between farms of different sizes or production
levels.

#### Milk Intensity

```{r}
# Calculate emissions per kg of milk (FPCM)
milk_intensity <- calc_intensity_litre(
  total_emissions = total_emissions,
  milk_litres = farm_data$milk_litres,
  fat = 3.8, # Typical fat content
  protein = 3.2 # Typical protein content
)

milk_intensity
```

#### Area Intensity

```{r}
# Calculate emissions per hectare
area_intensity <- calc_intensity_area(
  total_emissions = total_emissions,
  area_total_ha = farm_data$total_area_ha,
  area_productive_ha = farm_data$productive_area_ha,
  area_breakdown = list(
    pasture_permanent = 80,
    pasture_temporary = 20,
    crops_feed = 15,
    infrastructure = 5
  )
)

area_intensity
```

## Visualizing Results

The primary goal of **cowfootR** is to calculate greenhouse gas emissions and
intensity metrics following standardized methodologies. The package does not
aim to provide a comprehensive visualization framework.

Instead, cowfootR outputs are designed to be easily extracted and converted
into standard R objects (such as numeric vectors, lists, or data frames), which
can then be visualized using external packages like **ggplot2**.

The examples below illustrate how users can manually transform cowfootR results
into data frames for exploratory visualization and reporting.

### Emission Source Breakdown

```{r}
# Create a data frame for plotting
emission_breakdown <- data.frame(
  Source = names(total_emissions$breakdown),
  Emissions = as.numeric(total_emissions$breakdown)
)

# Create pie chart
ggplot(emission_breakdown, aes(x = "", y = Emissions, fill = Source)) +
  geom_col(width = 1) +
  coord_polar("y", start = 0) +
  theme_void() +
  labs(
    title = "Farm Emissions by Source",
    subtitle = paste("Total:", round(total_emissions$total_co2eq), "kg CO₂eq/year")
  ) +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5)
  )
```

### Intensity Comparison

```{r}
# Create comparison chart
intensity_data <- data.frame(
  Metric = c(
    "Milk Intensity\n(kg CO₂eq/kg FPCM)",
    "Area Intensity\n(kg CO₂eq/ha)"
  ),
  Value = c(
    milk_intensity$intensity_co2eq_per_kg_fpcm,
    area_intensity$intensity_per_productive_ha
  ),
  Benchmark = c(1.2, 8000) # Typical benchmark values
)

ggplot(intensity_data, aes(x = Metric)) +
  geom_col(aes(y = Value), fill = "steelblue", alpha = 0.7) +
  geom_point(aes(y = Benchmark), color = "red", size = 3) +
  geom_text(aes(y = Benchmark, label = "Benchmark"),
    color = "red", vjust = -0.5
  ) +
  labs(
    title = "Farm Intensity Metrics",
    y = "Value",
    x = ""
  ) +
  theme_minimal()
```

## Understanding the Results

### Interpreting Emission Factors

- **Enteric fermentation** typically represents 40-60% of total farm emissions
- **Purchased inputs** (especially protein feeds) can be 20-40% of emissions
- **Soil N₂O** usually contributes 5-15% of total emissions
- **Energy use** is generally the smallest component (2-8%)

### Benchmarking Performance

The calculated intensities can be compared against regional or global benchmarks:

- **Excellent performance**: < 1.0 kg CO₂eq/kg FPCM
- **Good performance**: 1.0-1.3 kg CO₂eq/kg FPCM  
- **Average performance**: 1.3-2.0 kg CO₂eq/kg FPCM
- **Poor performance**: > 2.0 kg CO₂eq/kg FPCM


### Common Issues

1. **Missing data**: The package provides reasonable defaults, but farm-specific data improves accuracy
2. **Unit consistency**: Ensure all inputs use the correct units (kg, litres, hectares)
3. **System boundaries**: Be consistent about what's included/excluded
4. **Temporal boundaries**: Use annual data for meaningful comparisons

## Next Steps

This vignette introduced the basic concepts of dairy life cycle assessment and
demonstrated a complete single-farm workflow using **cowfootR**.

To continue exploring the package, users may refer to the following vignettes
and functions:

- **Single Farm Analysis**  
  A detailed walkthrough of individual emission calculation functions
  (`calc_emissions_*()`), including assumptions and optional arguments.

- **Batch Processing Workflow**  
  How to process multiple farms simultaneously using structured input data and
  Excel templates.

- **Understanding IPCC Methodology Tiers**  
  Guidance on choosing between Tier 1 and Tier 2 approaches and understanding
  their implications for data requirements and accuracy.

- **Complete Parameter Reference Guide**  
  A comprehensive overview of all available functions, arguments, and default
  values used throughout the package.
## Key Takeaways

1. **cowfootR** follows internationally recognized LCA standards (IDF 2022, IPCC 2019)
2. The modular approach allows flexible assessment of different emission sources
3. Results should be interpreted in context of farm system and regional benchmarks
4. Data quality significantly affects accuracy - collect farm-specific data when possible
5. The package provides both absolute emissions and intensity metrics for comprehensive analysis

---

*For questions, bug reports, or contributions, visit the cowfootR GitHub repository or contact the development team.*
