Brightway2中IOTableBackend.write方法参数格式及示例问询
解决Brightway2中IOTableBackend.write的参数格式问题
一、参数格式明确
1. products参数
products是字典结构,键必须为字符串类型的活动代码(无需包含数据库元组),值是包含活动核心属性的子字典,必填属性至少包含name和unit,可按需添加categories、location等可选属性。
2. exchanges参数
你对该参数的理解正确,但需保证其中的input code和output code与products中的活动代码完全匹配,交换类型字符串需严格符合Brightway规范(如"production"、"technosphere")。
二、可运行示例代码
import bw2data as bd # 清理已存在的同名数据库,避免冲突 if 'bedb' in bd.databases: del bd.databases['bedb'] # 正确的products格式:键为活动代码字符串 products = { 'act1': {'name': 'Activity 1', 'unit': 'unit A'}, 'act2': {'name': 'Activity 2', 'unit': 'unit B'} } # exchanges格式保持,确保code与products的键一致 exchanges = [ ('act1', 'act1', 'production', 1), ('act1', 'act2', 'technosphere', 0.567), ('act2', 'act2', 'production', 1), ('act2', 'act1', 'technosphere', 0.601) ] # 初始化后端并写入数据 bedb = bd.backends.iotable.IOTableBackend('bedb') bedb.write(products, exchanges) # 验证写入结果 print("数据库写入成功,已创建活动:", list(bedb))
三、错误点说明
你之前的代码错误在于products的键使用了('bedb', 'act1')这种数据库元组格式,而IOTableBackend.write要求键直接为活动代码字符串——因为当前后端已绑定bedb数据库,内部会自动处理数据库关联逻辑。
若需扩展活动属性,直接在子字典中添加即可,例如:
'act1': {'name': 'Activity 1', 'unit': 'unit A', 'categories': ['Manufacturing'], 'location': 'GLO'}
内容的提问来源于stack exchange,提问作者MaPi
相关产品推荐
相关产品推荐

