Skip to content

Commit

Permalink
First subshares samples integration
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarojhahn committed Apr 10, 2024
1 parent e66ed97 commit 9e3acde
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 19 deletions.
29 changes: 13 additions & 16 deletions pathways/lca.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,7 @@ def get_lca_matrices(
return dp

def get_subshares_matrix(
A_array: list,
indices: Dict,
year: int,
correlated_array: list,
) -> Datapackage:
"""
Add subshares samples to an LCA object.
Expand All @@ -177,21 +175,18 @@ def get_subshares_matrix(

dp_correlated = bwp.create_datapackage()

a_data, a_indices, a_sign, _ = A_array

# adjusted_data = adjust_matrix_based_on_shares(data_array, indices_array, indices, year)

a_data_samples, a_indices, a_sign = correlated_array

dp_correlated.add_persistent_array(
matrix='technosphere_matrix',
indices_array= a_indices,
data_array= a_data,
flip_array= a_sign,
indices_array=a_indices,
data_array=a_data_samples.reshape((1, -1)),
flip_array=a_sign,
)

return dp_correlated

def adjust_matrix_based_on_shares(data_array, indices_array, shares_dict, year):
def adjust_matrix_based_on_shares(A_arrays, shares_dict, use_distributions, year):
"""
Adjust the technosphere matrix based on shares.
:param data_array:
Expand All @@ -200,13 +195,14 @@ def adjust_matrix_based_on_shares(data_array, indices_array, shares_dict, year):
:param year:
:return:
"""
##### RIGHT NOW I AM ONLY MULTIPLYING BY THE SHARES IN 2020 - TO-DO: ADD THE SAMPLES
# TO-DO: RETURN THE LAST ARRAY NEEDED TO BUILD THE BW.PACKAGE

data_array, indices_array, sign_array, _ = A_arrays

index_lookup = {(row['row'], row['col']): i for i, row in enumerate(indices_array)}

modified_data = []
modified_indices = []
modified_signs = []

# Determine unique product indices from shares_dict to identify which shouldn't be automatically updated/added
unique_product_indices_from_dict = set()
Expand All @@ -225,7 +221,6 @@ def find_index(activity_idx, product_idx):
all_tech_indices = [techs[tech]['idx'] for tech in techs if techs[tech]['idx'] is not None]
all_product_indices = set()

# Optimization: Use np.isin for efficient filtering
tech_indices = np.isin(indices_array['row'], all_tech_indices)
all_product_indices.update(indices_array['col'][tech_indices])

Expand All @@ -251,15 +246,17 @@ def find_index(activity_idx, product_idx):
# Append to modified_indices regardless of whether it's a new addition or an adjustment
modified_indices.append((idx, product_idx))
modified_data.append(new_amount)
modified_signs.append(sign_array[index])
elif product_idx not in unique_product_indices_from_dict: # Exclude diagonal and undesired exchanges
modified_data.append(new_amount)
modified_indices.append((idx, product_idx))
modified_signs.append(True) # CHECK: I am assuming new exchanges are always positive

modified_data_array = np.array(modified_data, dtype=np.float64)
modified_indices_array = np.array(modified_indices, dtype=bwp.INDICES_DTYPE)
# modified_flip_array = np.array(modified_flip, dtype=flip_array.dtype)
modified_signs_array = np.array(modified_signs, dtype=bool)

return modified_data_array, modified_indices_array
return [modified_data_array, modified_indices_array, modified_signs_array]

def fill_characterization_factors_matrices(
biosphere_flows: dict, methods, biosphere_dict, debug=False
Expand Down
28 changes: 25 additions & 3 deletions pathways/pathways.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@
from .lca import (
fill_characterization_factors_matrices,
get_lca_matrices,

get_matrix_arrays,
get_indices,
# get_subshares_matrix,
adjust_matrix_based_on_shares,
get_subshares_matrix,
remove_double_counting,
)
from .lcia import get_lcia_method_names
Expand Down Expand Up @@ -136,6 +138,7 @@ def subshares_indices(regions, A_index, geo):
"""
Fetch the indices in the technosphere matrix from the activities in technologies_shares.yaml in
the given regions.
others shares are resized.
:param regions: List of regions
:param A_index: Dictionary with the indices of the activities in the technosphere matrix.
:param geo: Geomap object.
Expand Down Expand Up @@ -542,9 +545,10 @@ def _calculate_year(args):
lca.lci()
else:

subshares_indices = subshares_indices(regions, technosphere_indices, geo)
shares_indices = subshares_indices(regions, technosphere_indices, geo)
correlated_arrays = adjust_matrix_based_on_shares(A_arrays, shares_indices, use_distributions, year)

bw_correlated = get_subshares_matrix(A_arrays, subshares_indices, year)
bw_correlated = get_subshares_matrix(correlated_arrays)

lca = MonteCarloLCA(
demand={0: 1},
Expand Down Expand Up @@ -600,6 +604,24 @@ def _calculate_year(args):
return results


def correlated_uniform_montecarlo(ranges, defaults, iterations):
"""
Adjusts randomly selected shares for parameters to sum to 1 while respecting their specified ranges.
:param ranges: Dict with parameter names as keys and (min, max) tuples as values.
:param defaults: Dict with default values for each parameter.
:param iterations: Number of iterations to attempt to find a valid distribution.
:return: A dict with the adjusted shares for each parameter.
"""
for _ in range(iterations):
shares = {param: np.random.uniform(low, high) for param, (low, high) in ranges.items()}
total_share = sum(shares.values())
shares = {param: share / total_share for param, share in shares.items()}
if all(ranges[param][0] <= share <= ranges[param][1] for param, share in shares.items()):
return shares
return defaults


class Pathways:
"""The Pathways class reads in a datapackage that contains scenario data,
mapping between scenario variables and LCA datasets, and LCA matrices.
Expand Down

0 comments on commit 9e3acde

Please sign in to comment.