---
title: "Multi-Regional Input-Output Analysis"
date: '`r format(Sys.Date(), "%B %d, %Y")`'
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Multi-Regional Input-Output Analysis}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

<style>
p.caption {
  font-size: 0.6em;
  text-align: "center";
}
</style>

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.align = "center",
  out.width = "70%"
)

library(ggplot2)
```

# Introduction

Multi-Regional Input-Output (MRIO) analysis extends traditional input-output analysis to capture economic interdependencies between multiple regions or countries. The `miom` class in the `fio` package implements the methodology described in Miller & Blair (2009) for analyzing multi-regional economic systems.

This vignette demonstrates how to:

- Create and work with multi-regional input-output matrices
- Compute multi-regional multipliers
- Analyze inter-regional spillover effects  
- Extract country-specific input-output tables
- Measure regional interdependence

In a multi-regional system with $R$ regions and $N$ sectors per region, the total dimensions of the system are $RN \times RN$. The intermediate transactions matrix $\mathbf{Z}$ is partitioned as:

$$
\mathbf{Z} = \begin{bmatrix}
\mathbf{Z}^{11} & \mathbf{Z}^{12} & \cdots & \mathbf{Z}^{1R} \\
\mathbf{Z}^{21} & \mathbf{Z}^{22} & \cdots & \mathbf{Z}^{2R} \\
\vdots & \vdots & \ddots & \vdots \\
\mathbf{Z}^{R1} & \mathbf{Z}^{R2} & \cdots & \mathbf{Z}^{RR}
\end{bmatrix}
$$

\noindent where $\mathbf{Z}^{rs}$ represents intermediate flows from region $s$ to region $r$.

Computations of the multi-regional Leontief inverse is the same from the single-region case:

$$
\mathbf{L} = (\mathbf{I} - \mathbf{A})^{-1}
$$

\noindent where $\mathbf{A}$ is the multi-regional technical coefficients matrix. Therefore, the multi-regional input-output class `miom` is able to inherit methods from the `iom` class, implementing the additional functionality needed for multi-regional analysis.

# SHOWCASING THE `miom` CLASS: 2000 WORLD ECONOMY EXAMPLE

The `fiodata` package includes the `world_2000` dataset, which contains real multi-regional input-output data for 26 countries and 23 sectors from the year 2000. This dataset was created using element-by-element imports from Excel files with `import_element()` as demonstrated in the [World 2000 script](https://github.com/albersonmiranda/fiodata/blob/main/data-raw/world_2000.R).

Let's load and examine this real-world dataset:

```{r world_data}
# import real-world dataset
world_2000 <- fiodata::world_2000

# Examine the structure
world_2000$n_countries
world_2000$n_sectors
nrow(world_2000$intermediate_transactions)
ncol(world_2000$intermediate_transactions)

# Show the countries and sectors
world_2000$countries
world_2000$sectors
```

```{r examine_transactions}
# Show a small subset of transactions (first 6 countries x sectors)
knitr::kable(
  world_2000$intermediate_transactions[1:6, 1:6],
  digits = 0,
  caption = "Sample of Intermediate Transactions (millions of dollars)"
)

# Show total production for first few country-sectors
knitr::kable(
  t(world_2000$total_production[1, 1:6]),
  digits = 0,
  caption = "Sample of Total Production (millions of dollars)"
)
```

The intermediate transactions matrix shows the flows of goods and services between all country-sector combinations in the global economy. The values represent monetary flows in millions of dollars. Each element represents purchases of intermediate inputs from the supplying country-sector (columns) by the purchasing country-sector (rows). It captures the complete structure of intermediate transactions between 26 countries across 23 economic sectors, providing a comprehensive view of global economic interdependencies in the year 2000.

## Multi-Regional Multiplier Analysis

The `miom` class computes several types of multipliers following Miller & Blair (2009):

- **Intra-regional multipliers**: Effects within the same region
- **Spillover multipliers**: Effects on other regions
- **Total multipliers**: Sum of intra-regional and spillover effects

```{r compute_multipliers}
world_2000$compute_multiregional_multipliers()

# Show first 10 rows of multipliers for readability
knitr::kable(
  world_2000$multiregional_multipliers[1:10, 1:10],
  digits = 4,
  caption = "Multi-Regional Multipliers (first 10 country-sectors)"
)
```

## Interpreting the Multipliers

The multipliers table shows several key measures for each country-sector combination (each row is a $1 final-demand shock in `shock_country` / `shock_sector`):

- **Intra-regional multiplier**: The total effect within the same country when that sector receives a $1 shock
- **Spillover multiplier**: The total effect on all other countries from the same shock  
- **Total multiplier**: The sum of intra-regional and spillover effects
- **Multiplier to [Country]**: The specific spillover effect on each individual country

Let's find an interesting example. Take a look at Brazil Agriculture and it's effects on USA:

```{r interpret_multipliers}
# Find Brazil agriculture row
bra_agr_index <- which(grepl("BRA.*Agriculture", world_2000$multiregional_multipliers$shock_label))[1]
bra_agr <- world_2000$multiregional_multipliers[bra_agr_index, ]

# Show key multiplier components
multiplier_cols <- c("shock_label", "intra_regional_multiplier", "spillover_multiplier", "total_multiplier", "multiplier_to_USA")
available_cols <- intersect(multiplier_cols, names(bra_agr))
knitr::kable(bra_agr[, available_cols],
  digits = 4,
  caption = "Example: Brazil Agriculture Multipliers"
)
```

The multipliers reveal important insights about global economic linkages. The intra-regional multiplier shows the domestic effect within a country when one of its sectors receives a demand shock, while the spillover multiplier captures the total impact on all other countries.

## Spillover Matrix

The spillover matrix provides a comprehensive view of how shocks in each country-sector affect all other country-sectors in the system:

```{r spillover_matrix}
spillover_matrix <- world_2000$get_spillover_matrix()
```

This $598 \times 598$ matrix contains the complete set of multiplier effects. For example, we can examine how a shock to the **US electrical sector** affects **manufacturing** in other countries:

```{r us_effects}
# Effects of a shock to US Electrical sector
electrical_effects <- spillover_matrix[grepl("Manufacturing", rownames(spillover_matrix)), "USA_Electrical and optical equipment"]
knitr::kable(
  electrical_effects,
  digits = 10,
  caption = "Effects of a unit shock to US Electrical sector"
)
```

These values show the output response in each foreign country-sector to a unit shock in USA Electrical and optical equipment.

## Net Spillover Effects

Net spillover effects reveal asymmetric cross-regional multiplier linkages. For countries $r$ and $s$, $net[r, s] = spillover_{s→r} - spillover_{r→s}$ (block sums from the spillover matrix).

```{r net_spillover}
net_spillover <- world_2000$get_net_spillover_matrix()
knitr::kable(net_spillover, digits = 4, caption = "Net Spillover Effects Matrix")
```

The interpretation is:

- **Positive** `net[r, s]`: country `r` receives more cross-regional output response from shocks in `s` than `s` receives from shocks in `r` (row country is a net *recipient* relative to the column country).
- **Negative** `net[r, s]`: the column country receives more than the row country.
- Values close to zero: roughly symmetric spillover relationship.

For example, `net["USA", "CHN"] > 0` means a unit final-demand shock in China induces more output response in the USA than a comparable shock in the USA induces in China.

## Key Sectors Analysis

Key sectors analysis identifies sectors with strong backward and forward linkages in the multi-regional system:

```{r key_sectors}
world_2000$compute_key_sectors()

key_sectors_table <- world_2000$key_sectors[, c(
  "country", "sector_name",
  "power_dispersion", "sensitivity_dispersion", "key_sectors"
)]
knitr::kable(head(key_sectors_table), digits = 4, caption = "Key Sectors Analysis")
```

Key sectors are defined as those with above-average values in both power dispersion (backward linkages) and sensitivity dispersion (forward linkages). If both values exceed 1, the sector is classified as a key sector.

```{r identify_key_sectors}
knitr::kable(
  subset(key_sectors_table, key_sectors == "Key Sector"),
  digits = 4,
  caption = "World Key Sectors"
)
```

## Regional Interdependence Analysis

When a region increases its final demand, it doesn't just buy from local suppliers. It imports intermediate inputs from other regions, which in turn require inputs from their suppliers, creating a chain reaction.

Regional interdependence measures help understand cross-country multiplier linkages. The `get_regional_interdependence()` method computes several key indicators (Miller & Blair, 2009, section 6.3.2):

- **Self-reliance**: Average intra-regional column multiplier by country (sector-level mean)
- **Total spillover out**: Block sum of foreign output induced by all unit shocks in the country
- **Total spillover in**: Block sum of domestic output induced by all unit shocks abroad
- **Spillover balance**: `total_spillover_out - total_spillover_in` (negative means net recipient of cross-region spillovers)
- **Spillover export share**: `total_spillover_out / (total_spillover_out + total_spillover_in)`

```{r interdependence}
#| tbl-cap: "A glimpse on interdependence indexes table"

interdependence <- world_2000$get_regional_interdependence()
knitr::kable(interdependence, digits = 4) |> head()
```

Now let's plot the results and make sense of it. China has the greater self-reliance index, meaning that, on average, shocks in that economy causes higher domestic impact.

```{r}
ggplot(interdependence, aes(x = reorder(country, self_reliance), y = self_reliance)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  labs(
    title = "Self-reliance index by country",
    x = "Country",
    y = "Average intra-regional multiplier"
  ) +
  theme_minimal()
```

Concerning spillover to other countries, Hong Kong has the greatest value, meaning demand increases in that country triggers demand abroad. It is expected that a small city-state isn't able to fulfill demand industry-wide, thus stimulating suppliers abroad.

```{r}
ggplot(interdependence, aes(x = reorder(country, total_spillover_out), y = total_spillover_out)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  labs(
    title = "Total spillover to other countries by country",
    x = "Country",
    y = "Sum of induced multipliers abroad"
  ) +
  theme_minimal()
```

On the other hand, USA absorbs the most spillover-in effects. It means that USA benefits the most from demand shocks in other countries.

```{r}
interdependence |>
  subset(!country %in% "ROW") |>
  ggplot(aes(x = reorder(country, total_spillover_in), y = total_spillover_in)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  labs(
    title = "Total spillover absorbed by country",
    x = "Country",
    y = "Sum of induced multipliers at home"
  ) +
  theme_minimal()
```

The Spillover Balance measures whether a specific region or sector is a net "giver" or a net "receiver" of economic stimulus across boundaries. It is calculated as the difference between the economic activity a region exports via spillovers and what it pulls in from others.

If balance is positive, the region is a net contributor. This means when your region spends money, it leaks a massive amount of demand out to other regions, but when they spend money, your industries don't catch much of it.

A negative balance indicates the country is a net beneficiary, meaning your economy is highly capable of capturing the spillover effects of external spending. When other regions increase production, your local industries see a massive surge in demand for your intermediate inputs.

Results demonstrates that highly industrialized countries has negative balance, meaning they are able to absorb more spillover effects than leak it.

```{r}
interdependence |>
  subset(!country %in% "ROW") |>
  ggplot(aes(x = reorder(country, spillover_balance), y = spillover_balance)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  labs(
    title = "Spillover balance by country",
    x = "Country",
    y = "Spillover out - Spillover in"
  ) +
  theme_minimal()
```

The Spillover Export Share measures the degree of external leakages relative to the total economic impact. It evaluates how much of the total economic multiplier generated by a region's initial spending escapes to benefit foreign economies rather than staying local.

A higher share (e.g., 60%) indicates that a massive portion of the economic stimulus leaves the region. This typically happens in highly specialized, smaller, or open economies that rely heavily on importing specialized components, parts, or raw materials to complete production.

A lower share (e.g., 10%) means that the vast majority of the multiplier effect stays locked inside the domestic economy. This is characteristic of large, highly diversified economies with mature internal supply chains that can supply almost all of their own intermediate needs.

```{r}
ggplot(interdependence, aes(x = reorder(country, spillover_export_share), y = spillover_export_share)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  labs(
    title = "Spillover export share by country",
    x = "Country",
    y = "total_spillover_out / (out + in)"
  ) +
  theme_minimal()
```

## Bilateral Trade Analysis

The `miom` class allows extraction of bilateral trade flows between any two countries using the `get_bilateral_trade()` method:

```{r bilateral_trade}
# Get bilateral trade flows
trade_flow1 <- world_2000$get_bilateral_trade("BRA", "USA")
knitr::kable(trade_flow1[1:10, 1:5],
  digits = 2,
  caption = paste("Trade flows from", "BRA", "to", "USA", "(first 10 buying sectors, first 5 supplying sectors)")
)

trade_flow2 <- world_2000$get_bilateral_trade("USA", "BRA")
knitr::kable(trade_flow2[1:10, 1:5],
  digits = 2,
  caption = paste("Trade flows from", "USA", "to", "BRA", "(first 10 buying sectors, first 5 supplying sectors)")
)
```

These matrices show the intermediate goods flows from the origin country (columns) to the destination country (rows) by sector. The values represent the monetary flows of intermediate inputs used in production.

## Extracting Country-Specific Input-Output Tables

Lastly, one can obtain single-region `iom` objects from the multi-regional system. The `extract_country()` method allows you to extract domestic input-output tables for individual countries from the multi-regional system:

```{r extract_country}
# Extract domestic economy for deutschland in the dataset
deutsch_iom <- world_2000$extract_country("DEU")
```

The extracted `iom` object contains only the domestic transactions for the specified country:

```{r country_tables}
# Show a subset of the domestic intermediate transactions
knitr::kable(deutsch_iom$intermediate_transactions[1:8, 1:8],
  digits = 0,
  caption = paste("Deutschland Domestic Intermediate Transactions (first 8x8 sectors, millions USD)")
)

# Show total production
knitr::kable(t(deutsch_iom$total_production[1, 1:12]),
  digits = 0,
  caption = paste("Deutschland Total Production (first 12 sectors, millions USD)")
)
```

You can then perform standard input-output analysis on the domestic economy:

```{r country_analysis}
deutsch_iom$compute_tech_coeff()$compute_leontief_inverse()$compute_multiplier_output()

knitr::kable(head(deutsch_iom$multiplier_output, 12),
  digits = 4,
  caption = paste("Deutschland Domestic Output Multipliers (first 12 sectors)")
)
```

# REFERENCES

Miller, Ronald E., and Peter D. Blair. Input-Output Analysis: Foundations and Extensions. 2nd ed. Cambridge University Press, 2009. https://doi.org/10.1017/CBO9780511626982.
