You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Brightway2调用lca.top_emissions()报错,如何获取特定排放分数?

问题:Brightway2调用lca.top_emissions()报错,无法获取排放/生物圈流分数

从ecoinvent Excel表格导入数据后,我想获取功能单元的排放结果。目前能通过ca.annotated_top_processes(lca)或lca.top_activities()获取活动/过程影响,但除了ca.hinton_matrix(lca, rows=10, cols=10)外,无法拿到排放/生物圈流的特定分数。执行以下代码时触发错误:

import brightway2 as bw
from stats_arrays import *
import bw2analyzer as bwa
projects.set_current("excel_import_verif1")
bw.databases
db = bw.Database('IoTBOLLCA') #Excel spreadsheet
CC = [method for method in bw.methods if "('ReCiPe Midpoint (H) V1.13', 'climate change', 'GWP100')" in str(method)][0]
FU = [i for i in db if 'FU' in i['name']][0]
lca = bw.LCA({FU:1},CC)
lca.lci()
lca.lcia()
lca.score
ca = bwa.ContributionAnalysis()
lca.top_emissions()

报错信息

TypeError                                 Traceback (most recent call last)
File ~\Anaconda3\envs\bw2\lib\site-packages\scipy\sparse\_sputils.py:208, in isintlike(x)
    207 try:
---> 208     operator.index(x)
    209 except (TypeError, ValueError):

TypeError: 'numpy.float64' object cannot be interpreted as an integer

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
Input In [28], in <cell line: 1>()
----> 1 lca.top_emissions()

File ~\Anaconda3\envs\bw2\lib\site-packages\bw2calc\lca.py:575, in LCA.top_emissions(self, **kwargs)
    573 except ImportError:
    574     raise ImportError("`bw2analyzer` is not installed")
---> 575 return ContributionAnalysis().annotated_top_emissions(self, **kwargs)

File ~\Anaconda3\envs\bw2\lib\site-packages\bw2analyzer\contribution.py:152, in ContributionAnalysis.annotated_top_emissions(self, lca, names, **kwargs)
    146 """Get list of most damaging biosphere flows in an LCA, sorted by ``abs(direct impact)``.
    147 
    148 Returns a list of tuples: ``(lca score, inventory amount, activity)``. If ``names`` is False, they returns the process key as the last element.
    149 
    150 """
    151 ra, rp, rb = lca.reverse_dict()
---> 152 results = [
    153     (score, lca.inventory[index, :].sum(), rb[index])
    154     for score, index in self.top_emissions(
    155         lca.characterized_inventory, **kwargs
    156     )
    157 ]
    158 if names:
    159     results = [(x[0], x[1], get_activity(x[2])) for x in results]

File ~\Anaconda3\envs\bw2\lib\site-packages\bw2analyzer\contribution.py:153, in <listcomp>(.0)
    146 """Get list of most damaging biosphere flows in an LCA, sorted by ``abs(direct impact)``.
    147 
    148 Returns a list of tuples: ``(lca score, inventory amount, activity)``. If ``names`` is False, they returns the process key as the last element.
    149 
    150 """
    151 ra, rp, rb = lca.reverse_dict()
    152 results = [
---> 153     (score, lca.inventory[index, :].sum(), rb[index])
    154     for score, index in self.top_emissions(
    155         lca.characterized_inventory, **kwargs
    156     )
    157 ]
    158 if names:
    159     results = [(x[0], x[1], get_activity(x[2])) for x in results]

File ~\Anaconda3\envs\bw2\lib\site-packages\scipy\sparse\_index.py:47, in IndexMixin.__getitem__(self, key)
     46 def __getitem__(self, key):
---> 47     row, col = self._validate_indices(key)
     49     # Dispatch to specialized methods.
     50     if isinstance(row, INT_TYPES):

File ~\Anaconda3\envs\bw2\lib\site-packages\scipy\sparse\_index.py:152, in IndexMixin._validate_indices(self, key)
    149 M, N = self.shape
    150 row, col = _unpack_index(key)
---> 152 if isintlike(row):
    153     row = int(row)
    154     if row < -M or row >= M:

File ~\Anaconda3\envs\bw2\lib\site-packages\scipy\sparse\_sputils.py:216, in isintlike(x)
    214     if loose_int:
    215         msg = "Inexact indices into sparse matrices are not allowed"
---> 216         raise ValueError(msg)
    217     return loose_int
    218 return True

ValueError: Inexact indices into sparse matrices are not allowed

解决方法

错误根源是bw2analyzer返回的索引为numpy float类型,但稀疏矩阵要求整数索引,以下是三种可行解决方案:

方法一:手动转换索引为整数

直接调用ContributionAnalysis的核心方法,手动处理索引类型:

import brightway2 as bw
import bw2analyzer as bwa

# 初始化LCA对象
projects.set_current("excel_import_verif1")
db = bw.Database('IoTBOLLCA')
CC = [method for method in bw.methods if "('ReCiPe Midpoint (H) V1.13', 'climate change', 'GWP100')" in str(method)][0]
FU = [i for i in db if 'FU' in i['name']][0]
lca = bw.LCA({FU:1}, CC)
lca.lci()
lca.lcia()

ca = bwa.ContributionAnalysis()
ra, rp, rb = lca.reverse_dict()

# 手动获取并处理排放贡献
top_emissions = ca.top_emissions(lca.characterized_inventory)
results = []
for score, idx in top_emissions:
    int_idx = int(idx)  # 转换为整数索引
    inventory_sum = lca.inventory[int_idx, :].sum()
    flow_key = rb[int_idx]
    flow_activity = bw.get_activity(flow_key)
    results.append((score, inventory_sum, flow_activity['name'], flow_key))

# 打印结果
for res in results:
    print(f"影响分数: {res[0]:.4f}, 排放总量: {res[1]:.4f}, 流名称: {res[2]}")

方法二:更新依赖版本

该错误可能是bw2analyzer与scipy版本不兼容导致,尝试更新到兼容版本:

pip install --upgrade bw2analyzer scipy

推荐使用bw2analyzer>=0.10.0和scipy>=1.10.0的组合。

方法三:直接处理特征化矩阵

绕过top_emissions方法,直接从characterized_inventory提取数据:

# 提取特征化后的排放矩阵
ci = lca.characterized_inventory.tocsr()
# 获取非零元素的索引与对应值
indices = ci.indices
values = ci.data
# 按影响绝对值降序排序
sorted_pairs = sorted(zip(values, indices), key=lambda x: abs(x[0]), reverse=True)

# 转换索引并获取流信息
ra, rp, rb = lca.reverse_dict()
results = []
# 取前10个影响最大的排放流
for val, idx in sorted_pairs[:10]:
    int_idx = int(idx)
    flow_key = rb[int_idx]
    flow = bw.get_activity(flow_key)
    results.append((val, lca.inventory[int_idx, :].sum(), flow['name']))

# 输出结果
for item in results:
    print(f"影响值: {item[0]:.6f}, 排放量: {item[1]:.6f}, 流名称: {item[2]}")

内容的提问来源于stack exchange,提问作者Mathias Tcs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 15:50:49