brightway-lca / brightway2-calc

The calculation engine for the Brightway2 life cycle assessment framework.
BSD 3-Clause "New" or "Revised" License
14 stars 16 forks source link

Explicitly set array-size in MultiLCA's lci_calculation() #104

Closed TimoDiepers closed 4 months ago

TimoDiepers commented 4 months ago

What

Explicitly set array-size in MultiLCA's lci_calculation().

Why

Fixes an error described by @transfluxus in https://github.com/brightway-lca/brightway2-calc/issues/100#issuecomment-2244745800 where having a single {key: value} pair in the demands array results in wrong scores.

codecov[bot] commented 4 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 83.43%. Comparing base (2417a1b) to head (098e742). Report is 1 commits behind head on main.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #104 +/- ## ========================================== - Coverage 83.65% 83.43% -0.23% ========================================== Files 14 14 Lines 832 833 +1 ========================================== - Hits 696 695 -1 - Misses 136 138 +2 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

TimoDiepers commented 4 months ago

Also, here's a minimal example. Not working:

demands = {
    "something": {123: 1}, 
}
demand_arrays = {
    "something": np.array([1, 0, 0]), 
}
demand_matrix = np.vstack([arr for arr in demand_arrays.values()]).T
technosphere = np.array([[1, 0, 0], [-2, 1, 0], [0, -5, 1]])
technosphere_sparse = scipy.sparse.csr_matrix(technosphere)
solutions = scipy.sparse.linalg.spsolve(technosphere_sparse, demand_matrix)
supply_arrays = {name: arr for name, arr in zip(demands, solutions.T)}

print(supply_arrays)

# > {'something': 1.0}

Working:

demands = {
    "something": {123: 1}, 
    "something else": {456: 1},
}
demand_arrays = {
    "something": np.array([1, 0, 0]), 
    "something else": np.array([0, 1, 0])
}
demand_matrix = np.vstack([arr for arr in demand_arrays.values()]).T
technosphere = np.array([[1, 0, 0], [-2, 1, 0], [0, -5, 1]])
technosphere_sparse = scipy.sparse.csr_matrix(technosphere)
solutions = scipy.sparse.linalg.spsolve(technosphere_sparse, demand_matrix)
supply_arrays = {name: arr for name, arr in zip(demands, solutions.T)}

print(supply_arrays)

# > {'something': array([ 1.,  2., 10.]), 'something else': array([0., 1., 5.])}

Sidenote: I've also noticed that it somewhat depends on the solver:

demands = {
    "something": {123: 1}, 
    # "something else": {456: 1},
}
demand_arrays = {
    "something": np.array([1, 0, 0]), 
    # "something else": np.array([0, 1, 0])
}
demand_matrix = np.vstack([arr for arr in demand_arrays.values()]).T
technosphere = np.array([[1, 0, 0], [-2, 1, 0], [0, -5, 1]])
solutions = scipy.linalg.solve(technosphere, demand_matrix)
supply_arrays = {name: arr for name, arr in zip(demands, solutions.T)}

technosphere_sparse = scipy.sparse.csr_matrix(technosphere)
solutions_sparse = scipy.sparse.linalg.spsolve(technosphere_sparse, demand_matrix)
supply_arrays_sparse = {name: arr for name, arr in zip(demands, solutions_sparse.T)}

print(supply_arrays)
print(supply_arrays_sparse)

# > {'something': array([ 1.,  2., 10.])}
# > {'something': 1.0}
cmutel commented 4 months ago

@TimoDiepers I am not sure I understand what is happening here, but I guess it is related to the supply arrays having incorrect dimensions if only one functional unit dict (or only one functional unit dict with only one element?) is present. Your solution is to call .reshape to force the supply arrays to have the right number of dimensions. Is that right? Can we turn your code into a test?

TimoDiepers commented 4 months ago

@cmutel Sorry, let me clarify. In the end, there are two things going on:

  1. If there is only one element in the demand_arrays, the thing I called demand_matrix is essentially a column vector. Solving the inventory with scipy.sparse.linalg.spsolve returns a 1d-array, somewhat disregarding the original dimensionality:

    solutions => array([ 1.,  2., 10.])

    If there are multiple elements in demand_arrays, the demand_matrix has as many columns as elements. Solving then retains the dimensions, returning:

    solutions => array([[ 1.,  0.], [ 2.,  1.], [10.,  5.]])

    So, while in the first case it's just a 1d-array, in the second case, the values for the first demand are stored in the first column of the solutions matrix.

  2. The actual problem then occurs when building the supply arrays:

    supply_arrays = {name: arr for name, arr in zip(demands, solutions.T)}

    Transposing the 1d-array here does nothing and just returns the original array again. If we then zip the demands and solutions arrays, essentially, the first (and only) element of the demands dict gets mapped to the first element of the solutions array (because it's just 1d), instead of the whole array, returning

    {'something': 1.0}

    instead of

    {'something': array([ 1.,  2., 10.])}

Now about the proposed solution: explicitly reshaping the solutions array "forces" even a 1d-array-output back into the column vector shape, in this case shape (3, 1). In zip, this array then gets transposed "correctly" into a row vector with the shape (1, 3) instead of being turned into shape (3,). Zipping then maps the whole row (because it's still treated as a matrix) instead of just the first element (as it happens with a 1d-array). I hope this makes it clearer.

And about adding a test: of course, I'm on it.

cmutel commented 4 months ago

Ok, that's what I thought.

For a test, you should be able to just simplify one of the existing MultiLCA tests to one functional unit.

TimoDiepers commented 4 months ago

@cmutel did that already, see e6a83c0