Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 3 commits into from
Jul 24, 2024

Conversation

TimoDiepers
Copy link
Member

@TimoDiepers TimoDiepers commented Jul 23, 2024

What

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

Why

Fixes an error described by @transfluxus in #100 (comment) where having a single {key: value} pair in the demands array results in wrong scores.

Copy link

codecov bot commented Jul 23, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

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

Additional details and impacted files
@@            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     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@TimoDiepers TimoDiepers changed the title add reshape to make single-row-arrays work Explicitly set array-size in MultiLCA's lci_calculation() Jul 23, 2024
@TimoDiepers
Copy link
Member Author

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
Copy link
Member

cmutel commented Jul 23, 2024

@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?

solutions = spsolve(
self.technosphere_matrix, np.vstack([arr for arr in self.demand_arrays.values()]).T
)
demand_matrix = np.vstack([arr for arr in self.demand_arrays.values()]).T
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure we need this to be a separate variable?

Copy link
Member Author

@TimoDiepers TimoDiepers Jul 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Separating this is certainly not necessary, I just thought it'd be more readable. In fact, the original commit 801f621 in this PR didn't have this. I can roll this back if you prefer not separating it.

@TimoDiepers
Copy link
Member Author

@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.

  1. 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
Copy link
Member

cmutel commented Jul 24, 2024

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
Copy link
Member Author

@cmutel did that already, see e6a83c0

@cmutel cmutel merged commit 834f3da into brightway-lca:main Jul 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants