### Build HTML Documentation
Source: https://github.com/indecol/pymrio/blob/master/CLAUDE.md
Generate the HTML documentation for the project. Requires Sphinx to be installed and configured.
```bash
make -C ./doc html
```
--------------------------------
### Sync Project Dependencies with uv
Source: https://github.com/indecol/pymrio/blob/master/CONTRIBUTING.rst
Installs project dependencies, including those for testing and linting, using the 'uv' package manager. Ensure 'uv' is installed before running.
```bash
uv sync --all-extras
```
--------------------------------
### Install pymrio from master branch
Source: https://github.com/indecol/pymrio/blob/master/README.rst
Install pymrio directly from the master branch on GitHub.
```bash
pip install git+https://github.com/IndEcol/pymrio@master
```
--------------------------------
### Install pymrio using pip
Source: https://github.com/indecol/pymrio/blob/master/README.rst
Install or upgrade pymrio to the latest version using pip.
```bash
pip install pymrio --upgrade
```
--------------------------------
### MRIO match method example
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/explore.ipynb
Shows the 'match' method, which looks for a match at the beginning of the string in index columns.
```python
mrio.match("ad")
```
--------------------------------
### MRIO fullmatch method example
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/explore.ipynb
Demonstrates the 'fullmatch' method, which requires the entire string to match the search term in index columns.
```python
mrio.fullmatch("trad")
```
--------------------------------
### Install pymrio using conda
Source: https://github.com/indecol/pymrio/blob/master/README.rst
Install pymrio from the conda-forge channel.
```bash
conda install -c conda-forge pymrio
```
--------------------------------
### Load and Calculate Test MRIO
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/aggregation_examples.ipynb
Loads the test MRIO system included with PyMRIO and performs initial calculations. This is a prerequisite for most aggregation examples.
```python
import numpy as np
import pymrio
```
```python
io = pymrio.load_test()
io.calc_all()
```
--------------------------------
### pymrio.load_test()
Source: https://github.com/indecol/pymrio/blob/master/doc/source/api_doc/pymrio.load_test.md
Returns a small test MRIO system. This system is useful for development and as an example of how to parse an IOSystem. It contains six regions, seven sectors, seven final demand categories, and two extensions (emissions and factor_inputs). It primarily includes Z, Y, and F, F_Y matrices, with other components calculable via calc_all().
```APIDOC
## pymrio.load_test()
### Description
Return a small test MRIO.
The test system contains:
> - six regions,
> - seven sectors,
> - seven final demand categories
> - two extensions (emissions and factor_inputs)
The test system only contains Z, Y, F, F_Y. The rest can be calculated with
calc_all()
### Notes
For development: This function can be used as an example of
how to parse an IOSystem
* **Return type:**
IOSystem
```
--------------------------------
### Load Test MRIO System
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/adjusting.ipynb
Loads the small test MRIO system included in the pymrio package. This is used for all examples in this tutorial.
```python
import pymrio
```
```python
mrio = pymrio.load_test()
```
--------------------------------
### Setup Land Use Data for Regions
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/convert.ipynb
Define a pandas DataFrame to hold land use results for different regions. This data serves as the input for characterization.
```python
import pandas as pd
land_use_data = pd.DataFrame(
columns=["Region1", "Region2", "Region3"],
index=[
"Wheat",
"Maize",
"Rice",
"Pasture",
"Forest extensive",
"Forest intensive",
],
data=[
[3, 10, 1],
[5, 20, 3],
[0, 12, 34],
[12, 34, 9],
[32, 27, 11],
[43, 17, 24],
],
)
land_use_data.index.names = ["stressor"]
land_use_data.columns.names = ["region"]
land_use_data
```
--------------------------------
### WIOD Metadata Output
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/working_with_wiod.ipynb
Example output of the WIOD metadata, detailing the dataset's origin, system, version, file location, and a history of its parsing and modifications.
```text
Output:
Description: WIOD metadata file for pymrio
MRIO Name: WIOD
System: industry-by-industry
Version: data13
File: /tmp/mrios/WIOD2013/metadata.json
History:
20210224 11:49:16 - FILEIO - Extension wat parsed from /tmp/mrios/WIOD2013
20210224 11:49:15 - FILEIO - Extension mat parsed from /tmp/mrios/WIOD2013
20210224 11:49:14 - FILEIO - Extension lan parsed from /tmp/mrios/WIOD2013
20210224 11:49:13 - FILEIO - Extension EU parsed from /tmp/mrios/WIOD2013
20210224 11:49:11 - FILEIO - Extension EM parsed from /tmp/mrios/WIOD2013
20210224 11:49:09 - FILEIO - Extension CO2 parsed from /tmp/mrios/WIOD2013
20210224 11:49:08 - FILEIO - Extension AIR parsed from /tmp/mrios/WIOD2013
20210224 11:49:06 - FILEIO - SEA file extension parsed from /tmp/mrios/WIOD2013
20210224 11:48:52 - METADATA_CHANGE - Changed parameter "system" from "IxI" to "industry-by-industry"
20210224 11:48:52 - FILEIO - WIOD data parsed from /tmp/mrios/WIOD2013/wiot07_row_apr12.xlsx
... (more lines in history)
```
--------------------------------
### Run CI Equivalent Build
Source: https://github.com/indecol/pymrio/blob/master/AGENTS.md
Executes a full build process that includes formatting, comprehensive testing, and documentation generation, mimicking the CI environment.
```bash
poe build
```
--------------------------------
### Get Satellite Account Name
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/explore.ipynb
Retrieve the name of a satellite account, for example, 'emissions'.
```python
mrio.emissions.name
```
--------------------------------
### Build Documentation
Source: https://github.com/indecol/pymrio/blob/master/AGENTS.md
Builds the project's Sphinx HTML documentation.
```bash
poe doc
```
--------------------------------
### Download Specific OECD ICIO Version
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/autodownload.ipynb
Downloads a specific release of the OECD - ICIO tables by specifying the version. For example, to get the 2018 release, use version='v2018'.
```python
log_2018 = pymrio.download_oecd(storage_folder=oecd_folder_v2018, version="v2016")
```
--------------------------------
### Run Pytest with Auto Parallelization
Source: https://github.com/indecol/pymrio/blob/master/CLAUDE.md
Execute the Pytest test suite using automatic parallelization for faster testing. No specific setup required beyond having pytest installed.
```bash
pytest -n auto
```
--------------------------------
### Open Notebooks
Source: https://github.com/indecol/pymrio/blob/master/AGENTS.md
Launches Jupyter Lab to access and run project notebooks.
```bash
poe jl
```
--------------------------------
### Define Data Storage Folders
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/GLAM_EXIO_link.ipynb
Sets up and creates directories for storing EXIOBASE and GLAM data. Ensure DATA_ROOT points to your desired data directory.
```python
DATA_ROOT = Path("/tmp/glam_exio_tutorial") # set this to your data directory
EXIOBASE_STORAGE_FOLDER = DATA_ROOT / "exiobase"
GLAM_STORAGE_FOLDER = DATA_ROOT / "glam"
EXIOBASE_STORAGE_FOLDER.mkdir(parents=True, exist_ok=True)
GLAM_STORAGE_FOLDER.mkdir(parents=True, exist_ok=True)
```
--------------------------------
### IOSystem.extension_match
Source: https://github.com/indecol/pymrio/blob/master/doc/source/api_doc/pymrio.IOSystem.extension_match.md
Get a dict of extension index dicts which match a search pattern. This calls the extension.match for all extensions. Similar to pandas str.match, thus the start of the index string must match.
```APIDOC
## IOSystem.extension_match(find_all=None, extensions=None, **kwargs)
### Description
Get a dict of extension index dicts which match a search pattern. This calls the extension.match for all extensions. Similar to pandas str.match, thus the start of the index string must match.
Arguments are set to case=True, flags=0, na=False, regex=True. For case insensitive matching, use (?i) at the beginning of the pattern. See the pandas/python.re documentation for more details.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Arguments
* **find_all** (None or str) - If str (regex pattern) search in all index levels. All matching rows are returned. The remaining kwargs are ignored.
* **extensions** (str, list of str, list of extensions, None) - Which extensions to consider, default (None): all extensions
* **kwargs** (dict) - The regex which should be contained. The keys are the index names, the values are the regex. If the entry is not in index name, it is ignored silently.
### Returns
* **dict** - A dict with the extension names as keys and an Index/MultiIndex of the matched rows as values
```
--------------------------------
### Initialize an empty IOSystem object
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/pymrio_directly_assign_attributes.ipynb
Create an instance of the IOSystem class to hold the IO data.
```python
io = pymrio.IOSystem()
```
--------------------------------
### Get Available Satellite Account Extensions
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/adjusting.ipynb
Obtains a generator for all available satellite account extensions. To get just the names, convert the generator to a list.
```python
mrio.get_extensions()
```
```python
list(mrio.get_extensions())
```
--------------------------------
### Manual Calculation of IO Matrices
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/full_tutorial.ipynb
Demonstrates how to manually calculate key input-output matrices (A, L, M) using functions from the `pymrio.tools.iomath` module. This is useful for verification or custom calculations.
```python
from pymrio.tools import iomath
# Calculate specific matrices manually
A_manual = iomath.calc_A(test_mrio.Z, test_mrio.x)
print("Manual A matrix calculation matches:", np.allclose(A_manual, test_mrio.A))
# Calculate Leontief matrix
L_manual = iomath.calc_L(test_mrio.A)
print("Manual L matrix calculation matches:", np.allclose(L_manual, test_mrio.L))
# Calculate multipliers
S = test_mrio.emissions.S
M_manual = iomath.calc_M(S, test_mrio.L)
print(
"Manual multiplier calculation matches:",
np.allclose(M_manual, test_mrio.emissions.M),
)
```
--------------------------------
### Get MRIO Classification Data
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/adjusting.ipynb
Retrieve classification synonyms for an MRIO to understand available renaming options. Pass None to get a list of available classifications.
```python
mrio_class = pymrio.get_classification(mrio_name="test")
```
--------------------------------
### Set Up New Final Demand
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/pymrio_directly_assign_attributes.ipynb
Prepare a new final demand vector by copying the original and updating specific entries. This is the first step in simulating changes to final demand.
```python
Ynew = Y.copy()
Ynew[("reg1", "final demand")] = np.array([[600], [1500]])
```
--------------------------------
### Get Eora26 regions
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/working_with_eora26.ipynb
Retrieve a list of all regions included in the Eora26 dataset.
```python
eora.get_regions()
```
--------------------------------
### Import necessary libraries
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/pymrio_directly_assign_attributes.ipynb
Import numpy, pandas, and pymrio for data manipulation and IO system creation.
```python
import numpy as np
import pandas as pd
import pymrio
```
--------------------------------
### Get Satellite Account Regions
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/explore.ipynb
List the regions associated with a satellite account.
```python
mrio.emissions.get_regions()
```
--------------------------------
### Load and Inspect Test MRIO System
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/full_tutorial.ipynb
Imports pymrio and loads the test MRIO system. Displays basic information such as type, available extensions, regions, sectors, final demand categories, and details from the emissions extension.
```python
import pymrio
# Load the test MRIO system
test_mrio = pymrio.load_test()
# Display basic information about the system
print(test_mrio)
print("Type of object:", type(test_mrio))
print("Available extensions:", test_mrio.extensions)
# Get regions and sectors
print("Regions:", test_mrio.regions)
print("Sectors:", test_mrio.sectors)
print("Final demand categories:", test_mrio.Y_categories)
print("Extensions:", test_mrio.extensions)
print("Rows in emissions extension:", test_mrio.emissions.rows)
```
--------------------------------
### Get MRIO Name
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/explore.ipynb
Retrieve the name identifier of the loaded MRIO dataset.
```python
mrio.name
```
--------------------------------
### Pre- vs. Post-Aggregation Calculation
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/aggregation_examples.ipynb
Demonstrates how to perform both pre-aggregation and post-aggregation calculations using PyMRIO. Pre-aggregation aggregates the system before calculation, while post-aggregation calculates first and then aggregates the results. This is useful for comparing the two methods.
```python
io_pre = (
pymrio.load_test()
.aggregate(region_agg=reg_agg_matrix, sector_agg=sec_agg_matrix)
.calc_all()
)
io_post = (
pymrio.load_test()
.calc_all()
.aggregate(region_agg=reg_agg_matrix, sector_agg=sec_agg_matrix)
)
```
--------------------------------
### Get Satellite Account Rows
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/explore.ipynb
Retrieve the index (rows) of a satellite account, useful for understanding its structure.
```python
mrio.emissions.get_rows()
```
--------------------------------
### Access PyMRIO DataFrame
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/explore.ipynb
Access the 'Y' DataFrame from the PyMRIO module. This is often the starting point for data analysis.
```python
df = mrio.Y
```
--------------------------------
### Run Validation and Get Report
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/stressor_characterization.ipynb
Execute the characterization and validation process. This generates a report detailing data inconsistencies.
```python
report = io.emissions.characterize(charact_table_reg, only_validation=True).validation
```
--------------------------------
### IOSystem.save_all
Source: https://github.com/indecol/pymrio/blob/master/doc/source/api_doc/pymrio.IOSystem.save_all.md
Saves the IO system and all its extensions to disk. Extensions are saved in separate folders named after the extension. Parameters are passed to the .save methods of the IOSystem and Extensions.
```APIDOC
## IOSystem.save_all
### Description
Save the system and all extensions. Extensions are saved in separate folders (names based on extension). Parameters are passed to the .save methods of the IOSystem and Extensions. See parameters description there.
### Method Signature
`save_all(path, table_format='txt', sep='\t', float_format='%.12g')`
### Parameters
- **path** (string) - The directory path where the system and extensions will be saved.
- **table_format** (string, optional) - The format for saving tables. Defaults to 'txt'.
- **sep** (string, optional) - The separator to use for text-based table formats. Defaults to '\t' (tab).
- **float_format** (string, optional) - The format string for floating-point numbers. Defaults to '%.12g'.
```
--------------------------------
### Import Pymrio Library
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/extract_data.ipynb
Import the pymrio library to begin working with Pymrio objects.
```python
import pymrio
```
--------------------------------
### Download WIOD with Specific Parameters
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/autodownload.ipynb
Download the WIOD database, specifying a storage folder, desired years, and a filtered list of satellite account URLs.
```python
wiod_meta_res = pymrio.download_wiod2013(
storage_folder="/tmp/foo_folder/WIOD2013_res",
years=res_years,
satellite_urls=res_satellite,
)
```
--------------------------------
### Get GLORIA Regions
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/working_with_gloria.ipynb
Retrieve a list of all available regions within the parsed GLORIA database using the 'get_regions()' method.
```python
gloria.get_regions()
```
--------------------------------
### Get GLORIA Sectors
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/working_with_gloria.ipynb
Retrieve a list of all available sectors within the parsed GLORIA database using the 'get_sectors()' method.
```python
gloria.get_sectors()
```
--------------------------------
### Import WIOD Configuration
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/autodownload.ipynb
Import the WIOD_CONFIG dictionary, which contains configuration details and URLs for satellite accounts.
```python
from pymrio.tools.iodownloader import WIOD_CONFIG
```
--------------------------------
### Download EXIOBASE 3 Data (Latest Version)
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/autodownload.ipynb
Initiates the download of the latest EXIOBASE 3 tables. You can specify the storage folder, system classification (e.g., 'pxp'), and desired years. If omitted, all available files are downloaded.
```python
exio_downloadlog = pymrio.download_exiobase3(
storage_folder=exio3_folder, system="pxp", years=[2011, 2012]
)
```
--------------------------------
### MRIO extension_contains method example
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/explore.ipynb
Demonstrates searching across all extensions using 'extension_contains' for 'emission' in 'stressor' and 'air' in 'compartment'.
```python
mrio.extension_contains(stressor="emission", compartment="air")
```
--------------------------------
### Define Storage Folder for WIOD
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/autodownload.ipynb
Specify the directory where the downloaded WIOD data will be stored. This is analogous to setting up storage for EXIOBASE 3.
```python
wiod_folder = "/tmp/mrios/autodownload/WIOD2013"
```
--------------------------------
### Get MRIO System Y Categories
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/adjusting.ipynb
Retrieves a list of available Y categories (final demand categories) in the MRIO system. These can be renamed to be more descriptive.
```python
mrio.get_Y_categories()
```
--------------------------------
### MRIO match method for partial string
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/explore.ipynb
Illustrates the 'match' method finding a partial string at the beginning of index entries.
```python
mrio.match("trad")
```
--------------------------------
### Get MRIO System Regions
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/adjusting.ipynb
Retrieves a list of available regions in the MRIO system. This is useful for identifying region names that can be renamed.
```python
mrio.get_regions()
```
--------------------------------
### Get Classification Data
Source: https://github.com/indecol/pymrio/blob/master/doc/source/api_doc/pymrio.get_classification.md
Retrieves predefined classifications included in pymrio. If no MRIO name is provided, it returns a list of available classifications.
```APIDOC
## pymrio.get_classification(mrio_name: str | None = None)
### Description
Get predefined classifications included in pymrio.
### Parameters
#### Path Parameters
- **mrio_name** (str) - Optional - MRIO for which to get the classification. Pass None (default) for a list of available classifications.
### Return type
[pymrio.ClassificationData](pymrio.ClassificationData.md#pymrio.ClassificationData)
```
--------------------------------
### Download GLORIA Database (Latest Release)
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/autodownload.ipynb
Initiate the download of the latest GLORIA database release to the specified storage folder. This process may take a few minutes.
```python
gloria_log_2014 = pymrio.download_gloria(storage_folder=gloria_folder)
```
--------------------------------
### Recalculating Accounts After Post-Aggregation
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/aggregation_examples.ipynb
Demonstrates how to recalculate all accounts after a post-aggregation has been performed. This ensures that the results are consistent with the aggregated system, effectively matching the pre-aggregation outcome.
```python
io_post.reset_all_full().calc_all().emissions.D_cba
```
--------------------------------
### MRIO contains method examples
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/explore.ipynb
Demonstrates the 'contains' method for searching substrings within index columns. 'find_all' is the default argument.
```python
mrio.contains(find_all="ad")
mrio.contains("ad") # find_all is the default argument
```
--------------------------------
### Loading MRIO System from File
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/metadata.ipynb
Loads an MRIO system from a previously saved directory. The metadata, including the history of operations and file I/O records, is loaded along with the system data.
```python
io_new = pymrio.load_all("/tmp/foo")
```
--------------------------------
### Load and Prepare EXIOBASE Data
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/GLAM_EXIO_link.ipynb
This snippet loads the EXIOBASE data, which includes resources and emissions, and prepares it for further processing. It assumes the data is in a format that can be read by pandas.
```python
import pandas as pd
# Load the EXIOBASE data
# Assuming the data is in a CSV file named 'exiobase_data.csv'
# Replace with your actual file path and loading method
filepath = "/path/to/your/exiobase_data.csv"
df = pd.read_csv(filepath)
# Display the first few rows to understand the structure
print(df.head())
# Further data preparation steps would follow here, such as
# filtering, cleaning, and transforming the data as needed.
```
--------------------------------
### Clean Documentation Build
Source: https://github.com/indecol/pymrio/blob/master/CLAUDE.md
Remove previously built documentation files. Use this command before rebuilding to ensure a clean state.
```bash
make -C ./doc clean
```
--------------------------------
### Get EXIOBASE Regions
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/working_with_exiobase.ipynb
Retrieves a list of all available regions in the EXIOBASE database. This is useful for filtering or selecting specific geographical areas for analysis.
```python
exio2.get_regions()
```
--------------------------------
### pymrio.download_exiobase3
Source: https://github.com/indecol/pymrio/blob/master/doc/source/api_doc/pymrio.download_exiobase3.md
Downloads EXIOBASE 3 files from Zenodo. By default, it downloads the latest version. Users can specify years, system classifications, whether to overwrite existing files, and a specific DOI for older versions.
```APIDOC
## pymrio.download_exiobase3(storage_folder, years=None, system=None, overwrite_existing=False, doi='10.5281/zenodo.3583070')
### Description
Download EXIOBASE 3 files from Zenodo. Since version 3.7, EXIOBASE has been published on the Zenodo scientific data repository. By default, this function downloads the latest available version from Zenodo. To download a previous version, specify the corresponding DOI using the ‘doi’ parameter.
### Parameters
* **storage_folder** (*str*, *valid path*) – Location to store the download, folder will be created if not existing. If the file is already present in the folder, the download of the specific file will be skipped.
* **years** (list of int or str, optional) – If years is given only downloads the specific years (be default all years will be downloaded). Years must be given in 4 digits.
* **system** (string or list of strings, optional) – ‘pxp’: download product by product classification. ‘ixi’: download industry by industry classification. [‘ixi’, ‘pxp’] or None (default): download both classifications.
* **overwrite_existing** (boolean, optional) – If False, skip download of file already existing in the storage folder (default). Set to True to replace files.
* **doi** (string, optional) – The EXIOBASE DOI to be downloaded. By default that resolves to the DOI citing the latest available version. For the previous DOI see the block ‘Versions’ on the right hand side of https://zenodo.org/record/4277368.
### Return type
Meta data of the downloaded MRIOs
```
--------------------------------
### Get Gross Trade Data
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/full_tutorial.ipynb
Retrieves total bilateral trade flows between regions and sectors. Use this to understand the scale of trade interactions.
```python
gross_trade = test_mrio.get_gross_trade()
```
--------------------------------
### Get Custom Region Names
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/aggregation_examples.ipynb
Retrieves the names of the regions from the MRIO system after aggregation with custom names. Verifies that the custom names have been applied.
```python
io.get_regions()
```
--------------------------------
### Create and assign a Factor Input extension
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/pymrio_directly_assign_attributes.ipynb
Instantiate a pymrio.Extension object for factor inputs and assign it to the IOSystem.
```python
factor_input = pymrio.Extension(name="Factor Input", F=F)
```
```python
io.factor_input = factor_input
```
--------------------------------
### Load from Multiple Extensions
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/load_save_export.ipynb
Load data from specified subfolders and select specific matrices. Handles cases where some extensions might not exist.
```python
io_multi_ext = pymrio.load_all(save_folder_full, subfolders=["emissions", "factor_inputs"], subset=["Z", "D_cba"])
print(io_multi_ext)
```
--------------------------------
### Define Aggregation Groups
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/advanced_group_stressors.ipynb
Defines a dictionary for aggregation where keys are regular expressions and values are the desired group names. This example groups all emissions.
```python
agg_groups = {("emis.*", ".*"): "all emissions"}
```
--------------------------------
### IOSystem.copy
Source: https://github.com/indecol/pymrio/blob/master/doc/source/api_doc/pymrio.IOSystem.copy.md
Returns a deep copy of the IOSystem. You can optionally provide a new name for the copied system.
```APIDOC
## IOSystem.copy(new_name=None)
### Description
Return a deep copy of the system.
### Parameters
#### Parameters
- **new_name** (str, optional) - Set a new meta name parameter. Default: _copy
```
--------------------------------
### Get MRIO System Sectors
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/adjusting.ipynb
Retrieves a list of available sectors in the MRIO system. This helps in understanding the current sector names for potential renaming.
```python
mrio.get_sectors()
```
--------------------------------
### Compare Characterization Results
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/stressor_characterization.ipynb
Compares the 'F' matrices from both characterization methods to verify they produce identical results when the same extensions are involved.
```python
# Both approaches produce the same result when the same extensions are involved:
print("Are the characterized F matrices equal?", ex_reg_multi.F.equals(ex_reg_mrio.F))
```
--------------------------------
### Cleaning Up Temporary Files
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/full_tutorial.ipynb
Removes temporary directories and their contents using shutil.rmtree. This is a common practice after running tests or examples that create temporary files.
```python
import shutil
shutil.rmtree(temp_dir)
print("Temporary files cleaned up")
```
--------------------------------
### Load MRIO System from Archive
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/load_save_export.ipynb
Loads an MRIO system directly from a zip archive. PyMRIO can read data without needing to extract the archive first.
```python
tt = pymrio.load_all(mrio_arc)
```
--------------------------------
### Load Test MRIO Data
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/aggregation_examples.ipynb
Loads the test MRIO dataset. This is a common starting point for experimenting with PyMRIO's aggregation and renaming functionalities.
```python
mrio = pymrio.load_test()
```
--------------------------------
### Export Dataframe to Excel
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/load_save_export.ipynb
Utilizes pandas' `to_excel` method to export a specific dataframe (e.g., emissions D_cba) to an Excel file. Requires pandas to be installed.
```python
io.emissions.D_cba.to_excel("/tmp/testmrio/emission_footprints.xlsx")
```
--------------------------------
### Build Aggregation Matrix with Custom Order
Source: https://github.com/indecol/pymrio/blob/master/doc/source/api_doc/pymrio.build_agg_matrix.md
Demonstrates building an aggregation matrix where the order of the new classification is explicitly defined using a dictionary. This allows for precise control over the output matrix's row order.
```python
>>> pymrio.build_agg_matrix(np.array([1, 0, 0, 2]))
>>> pymrio.build_agg_matrix(['b', 'a', 'a', 'c'], dict(a=0,b=1,c=2))
```
--------------------------------
### Extract Data from All Extensions to DataFrames
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/extract_data.ipynb
Use `extension_extract` to get data from multiple extensions as a dictionary of pandas DataFrames. The keys of the dictionary correspond to the extension names.
```python
df_extract_all = mrio.extension_extract(to_extract, return_type="dataframe")
df_extract_all.keys()
```
```python
df_extract_all["Factor Inputs"].keys()
```
--------------------------------
### Explore Initial MRIO Structure
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/aggregation_examples.ipynb
Prints the current sectors and regions of the loaded MRIO system. Useful for understanding the dimensions before aggregation.
```python
print(f"Sectors: {io.get_sectors().tolist()},\nRegions: {io.get_regions().tolist()}")
```
--------------------------------
### Load Test MRIO System
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/load_save_export.ipynb
Loads the included test MRIO system and calculates all associated accounts. This is a common starting point for testing PyMRIO functionalities.
```python
import pymrio
import os
io = pymrio.load_test().calc_all()
```
--------------------------------
### Create Temporary Directory
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/full_tutorial.ipynb
This code snippet demonstrates how to create a temporary directory using Python's tempfile and pathlib modules. This is often useful for temporary data storage during processing or analysis.
```python
import os
import tempfile
from pathlib import Path
# Create temporary directory for demonstration
temp_dir = Path(tempfile.mkdtemp())
```
--------------------------------
### Calculate All System and Extension Results
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/working_with_gloria.ipynb
Use this command to check for and calculate missing parts in the system, such as Z, L, multipliers, and footprint accounts for parsed GLORIA data.
```python
gloria.calc_all()
```
--------------------------------
### Get EXIOBASE 2 Sectors
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/working_with_exiobase.ipynb
Retrieve a list of available sectors within the EXIOBASE 2 database. This is useful for understanding the different economic activities included in the dataset.
```python
exio2.get_sectors()
```
--------------------------------
### Get Sector Renaming Dictionary
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/aggregation_examples.ipynb
Retrieves a dictionary to rename sectors based on predefined classifications. Use this to map original sector names to new, broader categories for aggregation.
```python
class_info = pymrio.get_classification("test")
rename_dict = class_info.get_sector_dict(
orig=class_info.sectors.TestMrioName, new=class_info.sectors.Type
)
```
--------------------------------
### List EXIOBASE Extensions
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/working_with_exiobase.ipynb
Returns a list of available extensions for the EXIOBASE database. Extensions provide additional data layers such as emissions, materials, or impact factors.
```python
list(exio2.get_extensions())
```
--------------------------------
### Build Aggregation Vector with Explicit Source List
Source: https://github.com/indecol/pymrio/blob/master/doc/source/api_doc/pymrio.build_agg_vec.md
Demonstrates building an aggregation vector by providing an explicit list for the 'other' source, alongside a target aggregation 'supreg1' and using the 'test' path.
```python
>>> build_agg_vec(['supreg1', 'other'], path = 'test',
>>> other = [None, None, 'other1', 'other1', 'other2', 'other2'])
['supreg1', 'supreg1', 'other1', 'other1', 'other2', 'other2']
```
--------------------------------
### Get EXIOBASE GLAM Bridge
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/GLAM_EXIO_link.ipynb
Fetches the EXIOBASE GLAM bridge, which links EXIOBASE stressors to GLAM flow names and UUIDs. Stressors are linked using regular expressions.
```python
exio_glam_bridge = pymrio.GLAMprocessing.get_GLAM_EXIO3_bridge()
```
--------------------------------
### Perform Full Match Search
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/full_tutorial.ipynb
Use the `match` method to find all occurrences of a specific term within the MRIO system. This is useful for getting a complete overview of where a term appears.
```python
match_results = test_mrio.match("reg1")
print("Full match for 'reg1':", match_results)
```
--------------------------------
### Define Storage Folder for EXIOBASE 3
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/autodownload.ipynb
Specify the directory where the downloaded EXIOBASE 3 data will be stored. Ensure this folder exists or can be created.
```python
exio3_folder = "/tmp/mrios/autodownload/EXIO3"
```
--------------------------------
### Visualize the System Matrix (A)
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/working_with_gloria.ipynb
Displays the system matrix 'A' using matplotlib. Adjust 'vmax' for appropriate scaling. Ensure matplotlib is imported.
```python
import matplotlib.pyplot as plt
plt.figure(figsize=(15, 15))
plt.imshow(gloria.A, vmax=1e-3)
plt.xlabel("Countries - sectors")
plt.ylabel("Countries - sectors")
plt.show()
```
--------------------------------
### Extract Specific Dataframes
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/adjusting.ipynb
Extracts a subset of available dataframe accounts by specifying a list of dataframe names to the 'dataframes' parameter. This example extracts only the 'F_Y' dataframe, including empty entries.
```python
only_fys = mrio.extension_extract(
cross_accounts_index, dataframes=["F_Y"], include_empty=True
)
```
--------------------------------
### Define Input Vectors for Aggregation
Source: https://github.com/indecol/pymrio/blob/master/doc/source/api_doc/pymrio.build_agg_matrix.md
Example input vectors for the build_agg_matrix function. inp1 uses numerical indicators, while inp2 uses string identifiers, both serving equivalent purposes for aggregation.
```python
>>> inp1 = np.array([0, 1, 1, 2])
```
```python
>>> inp2 = ['a', 'b', 'b', 'c']
```
--------------------------------
### Display Loaded Matrices and Extensions
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/load_save_export.ipynb
Prints the available matrices and extensions within a partially loaded IO system. Shows which data has been loaded based on the `subset` parameter.
```python
print("Available matrices in partial load:")
print(io_partial)
print(io_partial.emissions)
```
--------------------------------
### Import pymrio and Define Eora Storage Folder
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/autodownload.ipynb
Imports the pymrio library and defines the directory for storing Eora26 data. This folder will be created if it does not exist.
```python
import pymrio
eora_folder = "/tmp/mrios/eora26"
```
--------------------------------
### Get Impact Unit and Footprint Data
Source: https://github.com/indecol/pymrio/blob/master/doc/source/notebooks/working_with_exiobase.ipynb
Access the unit of a specific impact category and retrieve its footprint data. This is useful for understanding the units of measurement and the calculated impact values for different regions.
```python
print(exio2.impact.unit.loc["global warming (GWP100)"])
```
```python
exio2.impact.D_cba_reg.loc["global warming (GWP100)"]
```