Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
236 changes: 227 additions & 9 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,9 +1,227 @@
import_emission_factors/*__pycache__*
import_emission_factors/mrio_models/*
import_emission_factors/processed_mrio_resources/*
import_emission_factors/output/*
import_emission_factors/response_data/*
import_emission_factors/API/*API_key.yaml
!import_emission_factors/output/*import_factors_exiobase_2019*
!import_emission_factors/output/aggregate*
!import_emission_factors/output/import_shares_2019*
# Standard python gitignore from https://github.com/github/gitignore/

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not opposed to moving to the more standard .gitignore but I'd like to keep the existing ignores in there as well for now


# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py.cover
*.lcov
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
# Pipfile.lock

# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# uv.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
# poetry.lock
# poetry.toml

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
# pdm.lock
# pdm.toml
.pdm-python
.pdm-build/

# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
# pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi/*
!.pixi/config.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule*
celerybeat.pid

# Redis
*.rdb
*.aof
*.pid

# RabbitMQ
mnesia/
rabbitmq/
rabbitmq-data/

# ActiveMQ
activemq-data/

# SageMath parsed files
*.sage.py

# Environments
.env
.envrc
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
# .idea/

# Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/

# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# you could uncomment the following to ignore the entire vscode folder
# .vscode/
# Temporary file for partial code execution
tempCodeRunnerFile.py

# Ruff stuff:
.ruff_cache/

# PyPI configuration file
.pypirc

# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/

# Streamlit
.streamlit/secrets.toml

# Add Devcontainer
.devcontainer/
.config/
.idea/
13 changes: 12 additions & 1 deletion import_emission_factors/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,18 @@ The environmental flows fields are the same as those used for USEEIO which are f
## BEA API Access
To make calls to BEA for service imports data (by BEA service category, country, and year), users must first register at https://apps.bea.gov/api/signup/.
After doing so, users will be provided with an API key to the provided email.
Store this as 'BEA_API_key.yaml' in the API subfolder of the import_emission_factors directory.

Set the key as an environment variable before running scripts:

- `BEA_API_KEY` (preferred)
- `BEA_API_key` (backward compatible)

Optional: use a local `.env` file in the repository root with:

- `BEA_API_KEY=<your key>`
- Install `python-dotenv` to auto-load `.env` values.

Do not store API secrets in tracked files.

## Package requirements
- pandas
Expand Down
40 changes: 32 additions & 8 deletions import_emission_factors/download_imports_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import yaml
import numpy as np
import requests
import os
from pathlib import Path

apiPath = Path(__file__).parent / 'API'
Expand Down Expand Up @@ -112,15 +113,38 @@ def create_Reqs(file, d, year):
return reqs

def get_api_key(file):
# Load .env values if python-dotenv is available.
try:
with open(apiPath / f'{file}_key.yaml') as f:
api_key = yaml.safe_load(f)
return api_key
except FileNotFoundError:
raise FileNotFoundError(
f'API key required for {file}. Create the file '
f'"../import_emission_factors/API/{file}_key.yaml" and add your '
f'API key')
from dotenv import load_dotenv # type: ignore
for env_path in (
Path(__file__).parent / '.env',
Path(__file__).parents[1] / '.env',
):
if env_path.exists():
load_dotenv(dotenv_path=env_path, override=False)
except ImportError:
pass

env_var_candidates = list(dict.fromkeys([
file,
f'{file}_KEY',
f'{file}_key',
file.upper(),
f'{file.upper()}_KEY',
f'{file.upper()}_key',
file.lower(),
f'{file.lower()}_key',
]))

for env_var in env_var_candidates:
api_key = os.getenv(env_var)
if api_key and api_key.strip():
return api_key.strip()

raise EnvironmentError(
f'API key required for {file}. Set an environment variable '
f'(for example: {file}, {file}_KEY, or {file}_key).'
)


def complete_URLs(req_url, year, d):
Expand Down
8 changes: 6 additions & 2 deletions import_emission_factors/generate_import_factors.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,12 @@ def generate_import_emission_factors(years: list, schema=2012, calc_tiva=False):
## is unable to distinguish and sort out mismatches by detail/
## summary sectors.
multiplier_df = df_prepare(multiplier_df, year)
check = (multiplier_df
.query('Flow == @multiplier_df["Flow"][0]')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was this chunk causing you problems? I think it was an oversight. We should probably always use Flowable instead of Flow which should work for all instances (there's no need to have both options in here).

check_df = multiplier_df.copy()
if 'Flow' in check_df.columns:
check_df = check_df.query('Flow == @check_df["Flow"][0]')
elif 'Flowable' in check_df.columns:
check_df = check_df.query('Flowable == @check_df["Flowable"][0]')
check = (check_df
.groupby(['BEA Summary']).agg({'cntry_cntrb_to_national_summary':'sum'})
.rename(columns={'cntry_cntrb_to_national_summary': 'contrib'})
.query('contrib > 0 and contrib <= 0.9999')
Expand Down
32 changes: 32 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[project]
name = "useeio"
version = "0.1.0"
description = "United States Environmentally-Extended Input-Output (USEEIO) Modeling Framework."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"bibtexparser",
"currencyconverter",
"esupy",
"fedelemflowlist",
"numpy",
"openpyxl",
"pandas",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"pandas",
"pandas[excel]",

I get an ImportError as pandas requires openpyxl >= 3.1.5. I think setting this optional install should resolve it.

"pymrio",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"pymrio",
"pymrio",
"python-dotenv",

Let's go ahead and add python-dotenv as well.

"pyyaml",
"requests",
"tqdm",
]


[dependency-groups]
dev = [
"pytest>=8",
]

[tool.uv]
exclude-newer = "1 week"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't believe this is a valid entry


[tool.uv.sources]
fedelemflowlist = { git = "https://github.com/FLCAC-admin/fedelemflowlist", rev = "v1.3.1" }
esupy = { git = "https://github.com/USEPA/esupy.git" }
Loading