{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "91429c2a",
   "metadata": {},
   "source": [
    "# Update trade mixes\n",
    "\n",
    "This workflow shows how to overwrite the **regional sourcing** of traded items\n",
    "with `Database.update_trade_mix`, and how to prepare a SUT for agile trade\n",
    "updates with `Database.pool_trade`.\n",
    "\n",
    "The trade mix is the dual of the supply mix: instead of redistributing several\n",
    "labels *within one region*, it redistributes **one item across its origin\n",
    "regions** inside the columns of each destination market, preserving every\n",
    "selected column total. Each buyer therefore keeps its total input of the item;\n",
    "only the sourcing split changes.\n",
    "\n",
    "Origins that are not listed keep their current share: the provided shares\n",
    "(summing to one) are rescaled onto the combined share currently held by the\n",
    "listed origins. Partial updates — e.g. rebalancing only the intra-EU sourcing\n",
    "while the Chinese share stays put — are therefore well defined.\n",
    "\n",
    "## Where the trade lives\n",
    "\n",
    "The rewritten blocks depend on the table layout:\n",
    "\n",
    "| Layout | Bundle rows | Rewritten columns |\n",
    "|---|---|---|\n",
    "| **IOT (Isard)** | `(origin, Sector, item)` | destination's `z` and `Y` columns |\n",
    "| **SUT, Commodity level (Isard, e.g. raw EXIOBASE)** | `(origin, Commodity, item)` | destination's `u` and `Yc` columns |\n",
    "| **SUT, Activity level (pooled / Chenery-Moses)** | `(origin, Activity, item)` | destination market columns of `s` selected by `commodities=...` |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1e4bafe",
   "metadata": {},
   "source": [
    "## Isard tables\n",
    "\n",
    "On an Isard table the bilateral sourcing lives in the use side rows. Rewrite\n",
    "the sourcing of one commodity into one destination market with a\n",
    "`destination -> {origin: share}` mapping:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b924aaf1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import mario\n",
    "\n",
    "db = mario.parse_exiobase(\n",
    "    table=\"SUT\",\n",
    "    unit=\"Monetary\",\n",
    "    path=\"/path/to/MRSUT_2022.zip\",\n",
    "    name=\"EXIOBASE 3 SUT\",\n",
    "    year=2022,\n",
    ")\n",
    "\n",
    "# Italy sources its Motor vehicles 60% domestically and 40% from Germany;\n",
    "# origins that are not listed (e.g. FR) keep their current share.\n",
    "db.update_trade_mix(\n",
    "    {\"IT\": {\"IT\": 0.6, \"DE\": 0.4}},\n",
    "    items=\"Motor vehicles, trailers and semi-trailers (34)\",\n",
    "    scenario=\"baseline\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "068a6e84",
   "metadata": {},
   "source": [
    "> **Chenery-Moses uniformity — read before using on Isard tables.**\n",
    "> In an Isard table every buyer of one destination region can have its own\n",
    "> sourcing profile. Applying one destination-level mix rewrites **all** the\n",
    "> destination's buyer columns with the *same* origin shares: it imposes the\n",
    "> Chenery-Moses hypothesis of uniform sourcing on those columns. This matches\n",
    "> how per-destination statistics (Comtrade, ENTSO-E) are published, and it is\n",
    "> physically sound for grid-like commodities; for differentiated goods be\n",
    "> aware that buyer-level sourcing heterogeneity is averaged away. Use\n",
    "> `column_sectors=...` to leave selected buyers on their original sourcing."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ffaf617",
   "metadata": {},
   "source": [
    "## Pooled tables (`pool_trade`)\n",
    "\n",
    "`pool_trade` prepares one SUT so that trade updates become market-share\n",
    "rewrites, decoupled from the technology mixes. For each pooled commodity `c`\n",
    "it adds, per region, one `\"{c} - supply\"` pass-through activity and one\n",
    "`\"{c} - need\"` market commodity:\n",
    "\n",
    "1. the pass-through activity consumes the whole domestic output of `c`;\n",
    "2. every buyer (intermediate use and final demand) moves onto the domestic\n",
    "   need commodity, keeping its total input;\n",
    "3. the supply block routes each destination market to the origin pass-through\n",
    "   activities with the **bilateral trade flows observed on the Isard use\n",
    "   side** — so the pooled table is economically equivalent to the original at\n",
    "   the destination level, and the initial market shares in `s` equal the\n",
    "   observed origin shares.\n",
    "\n",
    "The technology mix of `c` (on the domestic commodity column) and its trade\n",
    "mix (on the need column) then live in two separate market-share columns of\n",
    "`s` and can be updated independently. The pooled pairs are recorded on\n",
    "`meta.pooled_trade_map`.\n",
    "\n",
    "> **Notes.** The pooling is structural: it rebuilds the baseline and drops\n",
    "> other scenarios with one warning. What is averaged away is the\n",
    "> buyer-specific sourcing heterogeneity inside each destination (the\n",
    "> Chenery-Moses hypothesis, applied only to the selected commodities). For\n",
    "> commodities distributed through one shared network — electricity being the\n",
    "> canonical case — this is typically *more* realistic than the Isard\n",
    "> buyer-specific sourcing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a4612b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "db.pool_trade(\"Electricity\")\n",
    "\n",
    "# trade mix on the pooled market: shares by origin per destination...\n",
    "db.update_trade_mix(\n",
    "    {\"IT\": {\"IT\": 0.85, \"FR\": 0.10, \"CH\": 0.05}},\n",
    "    items=\"Electricity - supply\",\n",
    "    commodities=\"Electricity - need\",\n",
    "    scenario=\"baseline\",\n",
    ")\n",
    "\n",
    "# ...and technology mix on the domestic market, fully decoupled.\n",
    "db.update_supply_mix(\n",
    "    {\"IT\": {\"Production of electricity by solar photovoltaic\": 0.6,\n",
    "            \"Production of electricity by wind\": 0.4}},\n",
    "    level=\"Activity\",\n",
    "    commodities=\"Electricity\",\n",
    "    scenario=\"baseline\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adb5f220",
   "metadata": {},
   "source": [
    "## Excel route\n",
    "\n",
    "The shock workbook accepts the `Trade mix N` type (with `N` from 1 to 10,\n",
    "available in the template picklists). All rows sharing the same\n",
    "`(item, Region_to, 'Trade mix N')` triple describe one destination mix:\n",
    "`Region_from` carries the origins and `Value` their shares, while `Region_to`\n",
    "names the destination market — one explicit region, `all` is rejected.\n",
    "\n",
    "On IOT workbooks author the mix on the `z` (or `Y`) sheet; on SUT workbooks\n",
    "use the `u`/`Yc` sheets for Isard commodity sourcing and the `s` sheet for\n",
    "pooled market shares (there `Commodity_to` must name the market commodity,\n",
    "e.g. `Electricity - need`). For example, on the `s` sheet of one pooled SUT:\n",
    "\n",
    "| Region_from | Activity_from | Region_to | Commodity_to | type | value |\n",
    "|---|---|---|---|---|---|\n",
    "| IT | Electricity - supply | IT | Electricity - need | Trade mix 1 | 0.85 |\n",
    "| FR | Electricity - supply | IT | Electricity - need | Trade mix 1 | 0.10 |\n",
    "| CH | Electricity - supply | IT | Electricity - need | Trade mix 1 | 0.05 |\n",
    "\n",
    "See [Shock analyses](apply_shocks.ipynb) for the general shock workflow."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
