Prepare Italy’s 2022 supply-use data for use in a CVXLab model. Download the official ISTAT workbooks, attach greenhouse-gas emissions, employment and energy accounts, translate the labels into English, aggregate and inspect the database, then export the matrices and sets to CVXLab.
This example uses the published national classifications. Electricity, gas, steam and air conditioning remain one activity; no electricity-technology disaggregation or power-sector scenarios are introduced.
Problem statement#
Prepare a national supply-use database with domestic uses, separate product imports and compatible greenhouse-gas emissions, employment and energy accounts for a CVXLab model.
Start from 63 ISTAT activities and products and obtain 15 of each, retaining 7 final-demand categories, 8 income/accounting rows and 3 satellite accounts. Inspect the database and export its baseline matrices using the CVXLab model’s table names, coordinates and filters.
Tutorial materials#
Download this notebook, aggregation.xlsx and cvxlab_model.zip from the tutorial page. Extract the archive beside the notebook to obtain per cvxlab/. It contains the CVXLab model_settings.xlsx, classified sets and input tables. The notebook regenerates those inputs from the official source data.
Use MARIO 1.3.6 in a dedicated Python 3.12 environment. This release includes the ISTAT import and satellite options used below. Restart the notebook kernel after installation.
conda create -n mario_cvxlab_tutorial python=3.12 pip
conda activate mario_cvxlab_tutorial
python -m pip install "mariopy==1.3.6" "cvxlab==1.0.1b1" jupyterlab
python -m jupyter lab
The code uses relative paths from the working folder. The official monetary release and the selected Eurostat snapshots are cached under source_data/. The archive’s README.rst describes the data sources and model input tables. Source data is downloaded separately rather than bundled here.
Database download#
Download the official ISTAT 2020–2022 edition. The parser selects 2022 at current basic prices. The native classification contains 63 NACE Rev. 2 branches and 63 CPA 2.1 products, excluding extraterritorial organisations. Existing cached workbooks are reused.
[ ]:
import mario
mario.download_istat_io(path="source_data", edition="2020-2022")
Database parsing#
Read SUPPLY, USE and IMPORT and request the emissions, employment and energy groups. download=True reuses the monetary release and fetches missing Eurostat snapshots for Italy in the same reference year.
ISTAT is already single-region: do not call to_single_region(). IMP_a and IMP_Y retain imports by product and purchasing activity or final demand. U and Yc contain domestic uses; no origin-country detail is available.
The satellite sources are air emissions accounts, employment and PEFA net domestic energy use. The parser groups contain more indicators than this example needs. keep_extensions() therefore retains exactly three native labels: the GHG total, total employment and net domestic energy use. Hours worked and the other emission indicators are excluded; all factors
of production remain.
The following aggregation workbook contains the same three satellite rows and translates their labels into English. Activity accounts populate Ea; direct household emissions and energy use populate EY. Their units are, respectively, tonnes CO2 equivalent, persons and TJ. The GHG total is a characterised account: do not add its component gases to it.
Native NACE codes align observations before labels are translated. Missing required observations cause an error rather than being filled with zero.
The variable db is a mario.Database object containing the SUT, classifications, units, metadata and scenarios. The parsed values belong to its baseline scenario. See Objects in MARIO.
[ ]:
db = mario.parse_istat(
path="source_data",
year=2022,
table="SUT",
level="63",
price="current",
valuation="basic",
import_representation="separate",
extensions=["emissions", "employment", "energy"],
download=True,
edition="2020-2022",
)
db.keep_extensions([
"AEA | GHG",
"Employment | Total",
"Energy | Net domestic energy use",
])
db.get_index("Satellite account")
Aggregation#
aggregation.xlsx maps the original ISTAT labels directly to the English classifications used by the model. Its Activity and Commodity sheets aggregate 63 branches and products into 15 groups. Consumption category, Factor of production and Satellite account provide one-to-one English labels.
The downloadable aggregation.xlsx is already filled in for this example. To define a different mapping, generate a template from the parsed database before applying aggregation:
db.get_aggregation_excel(
path="my_aggregation.xlsx",
levels=["Activity", "Commodity", "Consumption category",
"Factor of production", "Satellite account"],
)
Fill the Aggregation column in each sheet with the destination labels, then pass io="my_aggregation.xlsx" to aggregate(). Repeated destination labels combine source items; one-to-one labels rename them. The template does not choose the groups or translate labels automatically. A different classification also needs compatible CVXLab set attributes. See the get_aggregation_excel API.
The template-generation step is optional. To reproduce the example, use the completed aggregation.xlsx from Tutorial materials.
Apply all five sheets in one call. Imports follow the commodity aggregation; final-demand categories, factors and satellite indicators remain separate. The monetary unit is renamed million EUR without numerical rescaling.
[ ]:
db.aggregate(
io="aggregation.xlsx",
levels=["Activity", "Commodity", "Consumption category",
"Factor of production", "Satellite account"],
calc_all=False,
zero_output_epsilon=None,
)
for level in ["Activity", "Commodity", "Factor of production"]:
db.units[level].loc[:, "unit"] = "million EUR"
db.meta.model_configuration["import_unit"] = "million EUR"
db.get_index("Satellite account")
Explore the database#
Use get_index() to inspect classification labels and query() to retrieve matrices as pandas objects. Start with the activities and final-demand categories.
[ ]:
db.get_index("Activity")
[ ]:
db.get_index("Consumption category")
Check matrix dimensions#
S has activities on rows and commodities on columns. U reverses those axes; Yc has commodities on rows and final-demand categories on columns. IMP_a and IMP_Y keep product imports separate. The combined Z and X views retain both productive classifications; the database remains a SUT.
[ ]:
import pandas as pd
pd.DataFrame(
[(name, *db.query(name).shape)
for name in ["Z", "X", "S", "U", "Yc", "IMP_a", "IMP_Y", "Va", "Ea", "EY"]],
columns=["Matrix", "Rows", "Columns"],
).set_index("Matrix")
Domestic inputs, imports and value added#
Compare domestic and imported intermediate purchases with the source’s eight value-added/accounting rows, in million EUR. Imports in IMP_a are separate from Va. IMP_Y contains direct final-demand imports and is not included in this activity table. Published monetary rounding differences are retained.
[ ]:
activity_inputs = pd.DataFrame({
"Domestic intermediate inputs": db.query("U").sum(axis=0),
"Imported intermediate inputs": db.query("IMP_a").sum(axis=0),
"Value added/accounting items": db.query("Va").sum(axis=0),
})
activity_inputs.index = activity_inputs.index.get_level_values("Item")
activity_inputs
Select an activity’s supply#
Retrieve the products supplied by transport activities. query() retrieves the complete matrix; pandas xs() selects the Item index level. To inspect purchases instead, select the activity column of U with db.query("U").xs("Transport activities", level="Item", axis=1).
[ ]:
db.query("S").xs("Transport activities", level="Item")
Read satellite accounts with their units#
The database retains greenhouse-gas emissions in tonnes CO2 equivalent, total employment in persons and net domestic energy use in TJ. Inspect their units before comparing values.
[ ]:
indicators = [
"Greenhouse gases (CO2 equivalent) [AEA: GHG]",
"Total employment (domestic concept)",
"Net domestic energy use",
]
db.units["Satellite account"].loc[indicators]
Rank activities by total employment in persons:
[ ]:
employment = "Total employment (domestic concept)"
db.query("Ea").loc[employment].sort_values(ascending=False).head()
EY contains direct household emissions and energy use by final-demand category. Inspect them separately from activity accounts in Ea:
[ ]:
ghg = "Greenhouse gases (CO2 equivalent) [AEA: GHG]"
energy = "Net domestic energy use"
db.query("EY").loc[[ghg, energy]]
Export to CVXLab#
per cvxlab/model_settings.xlsx defines the CVXLab sets, database tables, variables and equations. to_cvxlab() exports the matrices of the MARIO database’s baseline scenario. The mapping argument connects their axes to CVXLab sets and assigns each matrix to a CVXLab input table. The variables in those tables are defined by the model settings:
MARIO matrix |
CVXLab input variable |
CVXLab database table |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The _0 suffix identifies input variables in this model configuration. These six input tables contain the baseline values exported from MARIO. Several variables share a table: U_0 and Y_0 select intermediate and final-demand columns from use_0; the import variables use the same split in imports_0. Within extensions_0, V_a_0 selects value-added rows, while E_a_0 and E_y_0 select satellite rows for production and final demand. These selections use the category
attributes in sets.xlsx.
Activities and final demand share the accounts set; factors and satellites share extensions. This configuration has no exogenous input for VY; that final-demand accounting matrix remains in the MARIO database.
CVXLab scenario inputs#
model_settings.xlsx declares delta_use, delta_imports and delta_extensions as additional input tables. to_cvxlab() creates their templates but leaves their values blank because they have no MARIO matrix mapping. They appear in report["unmapped_tables"] and can also appear in report["missing_values"]. CVXLab supplies zeros using the configuration’s blank_fill=0 when loading them; MARIO does not calculate scenario shocks.
The supplied sets preserve four CVXLab scenario names: reference, domestic_energy, petroleum_free_transport and mixed. The six _0 tables contain the MARIO baseline values without a scenario dimension. delta_use and delta_imports have a scenario dimension; delta_extensions does not in this configuration.
Write CVXLab inputs#
to_cvxlab() writes the classified sets to sets.xlsx and the input tables to input_data/input_data.xlsx inside per cvxlab/. Load these files into CVXLab using the accompanying model configuration. Blank type attributes intentionally leave members outside the power filter. They may be flagged in report["missing_attributes"] and do not represent missing matrix values.
sync_sets=["extensions"] synchronizes the receiving set with all mapped value-added accounts and the selected satellites. Regenerating an older receiver removes obsolete indicators and their dependent input rows, retaining valid attributes and mapped value-added accounts. Inspect report["removed_set_members"] and report["removed_input_rows"] for any removals.
sets.xlsx is the classified set workbook read and updated by to_cvxlab(). Keep it beside model_settings.xlsx when rerunning the notebook. The export preserves its member order, attributes, reporting groups and four scenario names; it synchronises the extension members with the eight value-added rows and three selected satellites. The export does not calculate or populate scenario shocks.
[ ]:
report = db.to_cvxlab(
model_settings="per cvxlab/model_settings.xlsx",
path="per cvxlab",
sync_sets=["extensions"],
mapping={
"sets": {
"Commodity_from": "products", "Commodity_to": "products",
"Activity_from": "accounts", "Activity_to": "accounts",
"Consumption category_to": "accounts",
"Factor of production_from": "extensions",
"Satellite account_from": "extensions",
},
"matrices": {
"S": "make_0", "U": "use_0", "Yc": "use_0",
"IMP_a": "imports_0", "IMP_Y": "imports_0",
"Va": "extensions_0", "Ea": "extensions_0", "EY": "extensions_0",
"Xa": "total_activity_0", "Xc": "total_demand_0",
},
},
)
report["written_cells"]