---
title: "Global Value Chain Decomposition with icio"
author: "Sebastian Krantz"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    toc: true
    toc_depth: 2
vignette: >
  %\VignetteIndexEntry{Global Value Chain Decomposition with icio}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment  = "#>",
  fig.width = 7
)
oldopts <- options(width = 90)   # restored at the end of the vignette
```

**icio** implements four gross-export decompositions from the Global Value Chain (GVC)
literature. All decompositions operate on an inter-country input-output (ICIO) table and
answer the question: *where does the value added embodied in a country's exports
ultimately originate?*

| Function | Reference | Level | Terms |
|----------|-----------|-------|------:|
| `leontief()` | Hummels, Ishii & Yi (2001) | country-industry origin | continuous shares |
| `kww()` | Koopman, Wang & Wei (2014) | country | 9 |
| `wwz()` | Wang, Wei & Zhu (2013) | bilateral country-industry | 16 |
| `bm()` | Borin & Mancini (2019) | country / sector / bilateral | up to 13 |

`bm()` is the recommended decomposition. Its world/sink perspective also provides a
corrected version of the biased KWW decomposition.

## The leather dataset

The package ships with `leather`, a minimal 3-country × 3-industry ICIO table covering
the leather GVC for Argentina, Turkey, and Germany.

```{r data}
library(icio)
data(leather)

leather$countries
leather$industries

# Intermediate demand matrix (9 × 9)
leather$inter

# Final demand matrix (9 × 3)
leather$final

# Gross output vector (length 9)
leather$out
```

The rows and columns of `inter` and the rows of `final` are ordered by country first,
then industry — 9 country-industry combinations in total.

## Building an `icio` object

`load_icio()` parses the raw ICIO matrices and pre-computes what the decompositions
need: the input coefficients `A`, the Leontief inverse `B`, the `G` blocks `Lb` of the
domestic Leontief inverse, value-added coefficients `Vc`, final demand (`Y`, `Yd`, `Ym`)
and exports (`E`, `ESR`). Only `A` and `B` are dense `GN x GN` matrices; the masked and
block-diagonal variants the decompositions use are derived on the fly.

Inverting `(I - A)` is by far the most expensive step, so build the object once and reuse
it across decompositions.

```{r load}
x <- load_icio(leather)
class(x)
names(x)
```

An `iot`-class list like `leather` is detected automatically; equivalently you can pass the
matrices directly as `load_icio(inter, final, countries, industries)`. Tables in the CSV
format of the Stata `icio` command are read with `load_icio_csv()`.

The key scalars:

```{r dims}
x$G  # number of countries
x$N  # number of industries
```

The value-added coefficient vector `Vc = v / o` gives the direct value-added share
of each country-industry's gross output:

```{r vc}
round(x$Vc, 3)
```

Total exports by country-industry:

```{r exports}
round(x$E, 2)
```

## Leontief decomposition

`leontief()` pre-multiplies the Leontief inverse by the value-added coefficient matrix
and post-multiplies by exports. The result gives the value-added origin (rows) of each
exporting country-industry (columns).

```{r leontief}
leo <- leontief(x)
head(leo, 12)
```

Each row identifies a *source* country-industry, a *using* country-industry, and the
amount of value added from the source embodied in the using sector's exports. Setting
`long = FALSE` returns the underlying matrix directly.

## Koopman-Wang-Wei (KWW) decomposition

`kww()` aggregates to the country level and splits exports into 9 components: domestic
value added (DVA), foreign value added (FVA), and various double-counting terms.

```{r kww}
kww(x)
```

> **Note:** The KWW decomposition contains a known systematic bias — it
> underestimates foreign value added by conflating some of it with domestic
> double-counting. Use `bm(perspective = "world", approach = "sink")` for the
> Borin-Mancini correction (see below).

## Wang-Wei-Zhu (WWZ) decomposition

`wwz()` operates at the bilateral country-industry level and decomposes exports into
16 value-added and double-counting terms by importing country.

```{r wwz}
wz <- wwz(x)
dim(wz)
names(wz)
```

The result is a long-format `data.table` with one row per (exporting country-industry,
importing country) pair and one column per term, preceded by three identifier columns
(`Exporting_Country`, `Exporting_Industry`, `Importing_Country`). Columns beyond the
16 decomposition terms are accounting diagnostics (`texp`, `texpint`, `texpfd`, etc.).

```{r wwz-slice}
# DVA_FIN for all exporters into Germany
subset(wz, Importing_Country == "Germany",
       select = c(Exporting_Country, Exporting_Industry, DVA_FIN))
```

`wwz2kww()` maps the 16-term result to the 9-term KWW format when both are needed:

```{r wwz2kww}
wwz2kww(wz)
```


## Borin-Mancini (BM) decomposition

`bm()` is the most flexible decomposition. It supports three aggregation levels
(`"country"`, `"sector"`, `"bilateral"`) and two accounting perspectives
(`"exporter"` with 13 terms, or `"world"` with 9 terms).

### Country level (exporter perspective, 13 terms)

```{r bm-country}
bm(x)
```

The 13 terms break gross exports (`GEXP`) into domestic content (`DC`) and foreign
content (`FC`), and further into value-added and double-counting components. GVC
participation is measured by `GVC = GEXP - DAVAX`, split into backward (`GVCB`) and
forward (`GVCF`) linkages.

### Sector level

```{r bm-sector}
bm(x, aggregation = "sector")
```

### Bilateral sector level

```{r bm-bilateral}
bm(x, aggregation = "bilateral")
```

The bilateral result contains one row per (exporting country-industry, importing
country) pair, excluding within-country flows. Country- and sector-level results are
additive aggregations of this table.

### Corrected KWW (world perspective, 9 terms)

The world/sink perspective implements the Borin-Mancini correction to the biased KWW
decomposition. It is only available at the country level.

```{r bm-worldsink}
bm(x, perspective = "world", approach = "sink")
```

Comparing to `kww()` above, `FVA` increases and `DDC` decreases accordingly.

### WWZ vs. BM (exporter/source): different perimeters

WWZ and BM (exporter/source) both decompose bilateral exports into value-added and
double-counting components, but they disagree on what "double-counted" means — and that
choice shapes which questions each method can answer.

WWZ uses a *bilateral* perimeter: an item is double-counted only if it crosses the same
s→r border more than once. Compared to BM, this is looser, so some items that BM
classifies as double-counted appear as value-added in WWZ. This makes WWZ well-suited to
questions about the GDP content of a specific trade flow — tariff incidence, bilateral
trade balances — but the tradeoff is that WWZ results do not add up: summing bilateral
terms over all importers does not recover a sensible country-level total. WWZ also
conflates source-based and sink-based approaches within the same decomposition, so its
terms are not on the same accounting footing and GVC indicators such as DAVAX cannot be
computed from the output.

BM (exporter/source) uses the *exporting country* as the perimeter: an item is
double-counted the second time it crosses country s's border, wherever it goes. One
approach throughout, so all 13 terms are comparable. Bilateral results sum to sector
totals, sector totals to country totals — and DAVAX, GVC-related trade, and
backward/forward participation shares all come out of the same calculation. For most
country- or sector-level work, BM (exporter/source) is the natural choice; reach for WWZ
when the question is specifically about what crosses a particular bilateral border.

## Convenience interface

`decomp()` is a single entry point for all methods, dispatching on `method` (default
`"bm"`) and passing `...` on to the decomposition function:

```{r decomp}
decomp(x, method = "leontief")
decomp(x, aggregation = "sector")
```

Given a list of `icio` objects — typically one ICIO table per year — it runs the
decomposition on each and stacks the results, prepending an identifier column:

```{r decomp-list}
decomp(list(`2015` = x, `2016` = x), idcol = "Year")
```

## Output format

All decompositions return a `data.table`, so column selection follows data.table rules:
`d$GEXP` and `d[["GEXP"]]` work as usual, but `d[, "GEXP"]` returns a one-column table
rather than a vector, and `d[c("GEXP", "DVA")]` is a join, not a column subset — use
`d[, .(GEXP, DVA)]` or `as.data.frame(d)` if you want base-R semantics.

## References

Borin, A., & Mancini, M. (2019). Measuring what matters in global value chains and
value-added trade. *World Bank Policy Research Working Paper 8804*.

Koopman, R., Wang, Z., & Wei, S.-J. (2014). Tracing value-added and double counting
in gross exports. *American Economic Review, 104*(2), 459–494.

Wang, Z., Wei, S.-J., & Zhu, K. (2013). *Quantifying international production sharing
at the bilateral and sector levels*. NBER Working Paper 19677.

Hummels, D., Ishii, J., & Yi, K.-M. (2001). The nature and growth of vertical
specialization in world trade. *Journal of International Economics, 54*(1), 75–96.

```{r cleanup, include=FALSE}
options(oldopts)
```
