Brightway数据库导入问题:.bw2package导入及xlsx内部关联丢失
Brightway数据库导入问题解决方案
1. 导入.bw2package文件的方法
Brightway的bw2io库提供了专用的导入函数来处理.bw2package文件,具体操作如下:
- 先导入对应函数:
from bw2io import import_package - 直接调用函数并传入文件路径即可完成导入:
import_package("/path/to/your/target-file.bw2package")
导入完成后,目标数据库会自动注册到当前Brightway项目中,可通过bw2data.Database("<数据库名称>")访问。
2. Excel导入后内部关联丢失及写入错误的解决
问题本质
ExcelImporter默认不会自动识别并关联库内的活动交换,而SimaPro格式本身会保留内部引用结构;写入时触发的InvalidExchange错误,是因为部分交换缺失input、amount或type这三个必填字段。
分步解决方案
步骤1:恢复库内活动关联
在匹配Ecoinvent数据库之前,先处理内部活动的关联逻辑:
- 导入Excel数据后,为当前数据库的每个活动创建唯一标识映射(用活动的名称、参考产品、地理位置等字段组合作为唯一键,避免重复):
from bw2io import ExcelImporter ei = ExcelImporter("/path/to/your/data.xlsx") # 先执行基础策略补全必要字段 ei.apply_strategy(ei.assign_only_product_as_production) ei.apply_strategy(ei.add_missing_exchanges) # 创建内部活动映射字典 internal_activity_map = {} target_db_name = "你的自定义数据库名称" for dataset in ei.data: # 用多字段组合生成唯一键,适配无地理位置的情况 unique_key = ( dataset.get('name'), dataset.get('reference product', ''), dataset.get('location', 'GLO') # 无地理位置时用默认值GLO ) internal_activity_map[unique_key] = (target_db_name, dataset['code']) - 遍历所有交换,匹配并替换内部活动的
input字段:for dataset in ei.data: for exchange in dataset.get('exchanges', []): # 生成交换对应的唯一键,匹配内部活动 exc_unique_key = ( exchange.get('name'), exchange.get('product', ''), exchange.get('location', 'GLO') ) if exc_unique_key in internal_activity_map: exchange['input'] = internal_activity_map[exc_unique_key] # 补全缺失的交换类型 if 'type' not in exchange: exchange['type'] = 'technosphere' # 根据实际交换类型调整,比如biosphere/production
步骤2:补全必填字段,解决写入错误
在写入数据库前,批量检查并补全所有交换的必填字段:
for dataset in ei.data: for exchange in dataset.get('exchanges', []): # 确保amount字段存在且为有效数值 if 'amount' not in exchange or exchange['amount'] is None: exchange['amount'] = 0.0 # 无值时设为0,或根据业务逻辑调整 # 确保type字段存在 if 'type' not in exchange: exchange['type'] = 'technosphere' # 按需调整类型 # 跳过未匹配到input的交换(或手动处理这类异常) if 'input' not in exchange: continue
完成上述处理后,再执行你原有Ecoinvent匹配流程,最后写入数据库:
# 执行跨库匹配Ecoinvent的操作 ei.match_iterable_by_fields('你的Ecoinvent数据库名', fields=['name', 'reference product', 'location']) # 写入数据库 ei.write_database()
内容的提问来源于stack exchange,提问作者Daina
相关产品推荐
相关产品推荐

