使用SingleOutputEcospold2Importer导入Ecoinvent 3.9至Brightway2失败
Ecoinvent 3.9导入Brightway2(v2.4.2)报错解决方案
问题描述
尝试用Brightway2导入Ecoinvent 3.9数据库时,执行以下代码出现两处报错:
from brightway2 import * add_ecoinvent_39_biosphere_flows() pte = r"C:\Users\Joshua Schroijen\ecoinvent\ecoinvent 3.9_cutoff_lci_ecoSpold02" importer = SingleOutputEcospold2Importer(pte, "ecoinvent39") importer.apply_strategies() db = importer.write_database()
报错1:add_ecoinvent_39_biosphere_flows()执行失败
Traceback (most recent call last): File "C:\Users\Joshua Schroijen\leaf-backend\business_logic\ecoinvent.py", line 4, in <module> add_ecoinvent_39_biosphere_flows() File "C:\Users\Joshua Schroijen\.conda\envs\bw2\lib\site-packages\bw2io\data\__init__.py", line 311, in _add_new_ecoinvent_biosphere_flows db.new_activity(**flow).save() File "C:\Users\Joshua Schroijen\.conda\envs\bw2\lib\site-packages\bw2data\project.py", line 358, in writable_project return wrapped(*args, **kwargs) File "C:\Users\Joshua Schroijen\.conda\envs\bw2\lib\site-packages\bw2data\backends\peewee\proxies.py", line 160, in save raise ValidityError("This activity can't be saved for the " bw2data.errors.ValidityError: This activity can't be saved for the following reasons * ``database`` refers to unknown database
报错2:importer.write_database()执行失败
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\Joshua Schroijen\.conda\envs\bw2\lib\site-packages\bw2io\importers\base_lci.py", line 237, in write_database raise WrongDatabase(error) bw2io.errors.WrongDatabase: Activity database must be ecoinvent39, but set() was also found
解决方案
1. 先初始化Brightway项目与基础生物圈数据库
Brightway需要先激活项目并创建默认生物圈数据库,这是add_ecoinvent_39_biosphere_flows()正常运行的前提。导入前添加以下初始化代码:
from brightway2 import * # 激活或创建目标项目 projects.set_current("Ecoinvent39_LCA") # 替换为你的项目名称 # 创建标准生物圈数据库(若不存在) if "biosphere3" not in databases: bw2setup()
bw2setup()会自动创建biosphere3数据库,而add_ecoinvent_39_biosphere_flows()的作用是给这个数据库补充Ecoinvent 3.9新增的流数据,而非独立创建新数据库。
2. 修正导入流程的顺序
必须严格遵循「初始化项目→创建生物圈→添加Ecoinvent专属流→导入数据库」的顺序,正确代码如下:
from brightway2 import * # 步骤1:初始化项目与生物圈 projects.set_current("Ecoinvent39_LCA") if "biosphere3" not in databases: bw2setup() # 步骤2:添加Ecoinvent3.9专属生物圈流 add_ecoinvent_39_biosphere_flows() # 步骤3:导入Ecoinvent数据库文件 pte = r"C:\Users\Joshua Schroijen\ecoinvent\ecoinvent 3.9_cutoff_lci_ecoSpold02" importer = SingleOutputEcospold2Importer(pte, "ecoinvent39") # 步骤4:应用导入策略并检查数据(可选但推荐) importer.apply_strategies() importer.statistics() # 查看导入的活动、交换数量,验证数据完整性 # 步骤5:写入数据库 db = importer.write_database()
3. 解决WrongDatabase报错的额外处理
如果仍出现该报错,说明导入的ecospold文件中存在数据库标识不一致的情况,需添加强制统一数据库名的策略:
在importer.apply_strategies()之后加入:
# 强制将所有交换项的数据库名统一为目标数据库 importer.apply_strategy(lambda x: [exc.update({"database": "ecoinvent39"}) for exc in x.get("exchanges", [])])
该策略会遍历所有活动的交换项,将它们的database字段统一设置为ecoinvent39,避免出现混合数据库标识的问题。
内容的提问来源于stack exchange,提问作者Joshua Schroijen
相关产品推荐
相关产品推荐

