Skip to content

Commit

Permalink
EODC
Browse files Browse the repository at this point in the history
  • Loading branch information
romainsacchi authored and romainsacchi committed Mar 28, 2024
1 parent ab5b6b1 commit 1b1fe6a
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 59 deletions.
67 changes: 19 additions & 48 deletions pathways/lca.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,26 @@ def load_matrix_and_index(
)

data_array = array[:, 2]

# make a boolean scalar array to store the sign of the data
flip_array = array[:, -1]
flip_array = array[:, -1].astype(bool)

distributions_array = np.array(
list(
zip(
array[:, 3].astype(int), # uncertainty type
array[:, 4].astype(float), # loc
array[:, 5].astype(float), # scale
array[:, 6].astype(float), # shape
array[:, 7].astype(float), # minimum
array[:, 8].astype(float), # maximum
array[:, 9].astype(bool), # negative
)
),
dtype=bwp.UNCERTAINTY_DTYPE,
)

distributions_array = array[:, 3:-1]
print(distributions_array[:5])

return data_array, indices_array, flip_array, distributions_array

Expand Down Expand Up @@ -128,57 +144,12 @@ def get_lca_matrices(
matrix="biosphere_matrix",
indices_array=b_indices,
data_array=b_data,
flip_array=b_sign,
#flip_array=b_sign,
distributions_array= b_distributions,
)

return dp, A_inds, B_inds


def load_uncertainty_data(
file_path: Path, technosphere_array, technosphere_indices
) -> np.ndarray:
"""
Reads a CSV file and returns its contents as a CSR sparse matrix.
:param file_path: The path to the CSV file.
:type file_path: Path
:return: A CSR sparse matrix.
:rtype: csr_matrix
"""
# Load the data from the CSV file
array = np.genfromtxt(file_path, delimiter=";", skip_header=1)

print(array.shape)

# remove the two first columns
uncertainty_data = array[:, 2:]
indices = array[:, :2]

print("data shape: ", uncertainty_data.shape)
print("technosphere array shape: ", technosphere_array.shape)
data_array = np.empty((technosphere_array.shape[0], 7))
print("data array shape: ", data_array.shape)
data_array[:, 0] = 0
data_array[:, 1] = technosphere_array
data_array[:, 2:6] = np.nan
data_array[:, -1] = False

# iterate through indices, and find the position of the indices in technosphere_indices
for i, idx in enumerate(indices):
print("i: ", i)
print("idx: ", idx)
row = np.where(
(technosphere_indices[:, 0] == idx[0])
& (technosphere_indices[:, 1] == idx[1])
)[0][0]
print("row: ", row)
data_array[row, 2:6] = uncertainty_data[i]
print(data_array[row])

return array


def fill_characterization_factors_matrices(
biosphere_flows: dict, methods, biosphere_dict, debug=False
) -> csr_matrix:
Expand Down
62 changes: 51 additions & 11 deletions pathways/pathways.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from typing import Any, Dict, List, Optional, Tuple

import bw2calc as bc
from bw2calc.monte_carlo import MonteCarloLCA
import numpy as np
import pandas as pd
import pyprind
Expand Down Expand Up @@ -269,6 +270,7 @@ def process_region(data: Tuple) -> dict[str, ndarray[Any, dtype[Any]] | list[int
lca,
characterization_matrix,
debug,
use_distributions,
) = data

variables_demand = {}
Expand Down Expand Up @@ -310,8 +312,34 @@ def process_region(data: Tuple) -> dict[str, ndarray[Any, dtype[Any]] | list[int
"demand": demand.values * float(unit_vector),
}

lca.lci(demand={idx: demand.values * float(unit_vector)})
characterized_inventory = (characterization_matrix @ lca.inventory).toarray()

if use_distributions == 0:
lca.lci(demand={idx: demand.values * float(unit_vector)})
characterized_inventory = (characterization_matrix @ lca.inventory).toarray()

else:
# Use distributions for LCA calculations
# next(lca) is a generator that yields the inventory matrix

for _ in range(use_distributions):
next(lca)
lca.lci(demand={idx: demand.values * float(unit_vector)})
print(lca.inventory.shape)
print(lca.inventory.sum())


results = np.array([
(characterization_matrix @ lca.lci(demand={idx: demand.values * float(unit_vector)}).inventory).toarray() for _ in zip(range(use_distributions), lca)
])

print(results.shape)
for result in results:
print(result.sum(axis=-1))


characterized_inventory = np.empty_like(lca.inventory)


# vars_info = fetch_indices(mapping, regions, variables, A_index, Geomap(model))
# characterized_inventory = remove_double_counting(characterized_inventory=characterized_inventory,
# vars_info=vars_idx,
Expand Down Expand Up @@ -450,14 +478,24 @@ def _calculate_year(args):
"acts_location_idx_array": acts_location_idx_array,
}

lca = bc.LCA(
demand={0: 1},
data_objs=[
bw_datapackage,
],
use_distributions=use_distributions,
)
lca.lci(factorize=True)
if use_distributions == 0:
lca = bc.LCA(
demand={0: 1},
data_objs=[
bw_datapackage,
],
use_distributions=True if use_distributions > 0 else False,
)
lca.lci(factorize=True)
else:
lca = MonteCarloLCA(
demand={0: 1},
data_objs=[
bw_datapackage,
],
use_distributions=True,
)
lca.lci()

characterization_matrix = fill_characterization_factors_matrices(
biosphere_indices, methods, lca.dicts.biosphere, debug
Expand Down Expand Up @@ -495,6 +533,7 @@ def _calculate_year(args):
lca,
characterization_matrix,
debug,
use_distributions,
)
)

Expand Down Expand Up @@ -693,7 +732,7 @@ def calculate(
flows: Optional[List[str]] = None,
multiprocessing: bool = False,
demand_cutoff: float = 1e-3,
use_distributions: bool = False,
use_distributions: int = 0,
) -> None:
"""
Calculate Life Cycle Assessment (LCA) results for given methods, models, scenarios, regions, and years.
Expand Down Expand Up @@ -725,6 +764,7 @@ def calculate(
:type data_type: np.dtype, default is np.float64
:param demand_cutoff: Float. If the total demand for a given variable is less than this value, the variable is skipped.
:type demand_cutoff: float, default is 1e-3
:param use_distributions: Integer. If non zero, use distributions for LCA calculations.
"""

self.scenarios = harmonize_units(self.scenarios, variables)
Expand Down

0 comments on commit 1b1fe6a

Please sign in to comment.