bw2calc#
Submodules#
Classes#
Mixin that allows method, etc. to be filepaths or |
|
A static LCI or LCIA calculation. |
|
Solve overdetermined technosphere matrix with more products than activities using least-squares approximation. |
|
The class, and its subclasses, load structured arrays, manipulate them, and generate SciPy sparse matrices. |
|
Wrapper class for performing LCA calculations with many functional units and LCIA methods. |
|
Subclass of |
Functions#
Load a calculation package created by |
Package Contents#
- class bw2calc.DenseLCA[source]#
Bases:
bw2calc.lca.LCA
- solve_linear_system()[source]#
Master solution function for linear system \(Ax=B\).
To most numerical analysts, matrix inversion is a sin.
—Nicolas Higham, Accuracy and Stability of Numerical Algorithms, Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 2002, p. 260.
We use UMFpack, which is a very fast solver for sparse matrices.
If the technosphere matrix has already been factorized, then the decomposed technosphere (
self.solver) is reused. Otherwise the calculation is redone completely.
- class bw2calc.IndependentLCAMixin[source]#
Bases:
objectMixin that allows method, etc. to be filepaths or
np.ndarrayinstead of DataStore object names.Removes dependency on bw2data.
- class bw2calc.LCA(demand, method=None, weighting=None, normalization=None, database_filepath=None, log_config=None, presamples=None, seed=None, override_presamples_seed=False)[source]#
Bases:
objectA static LCI or LCIA calculation.
Following the general philosophy of Brightway2, and good software practices, there is a clear separation of concerns between retrieving and formatting data and doing an LCA. Building the necessary matrices is done with MatrixBuilder objects (matrixbuilders). The LCA class only does the LCA calculations themselves.
Create a new LCA calculation.
- Parameters:
demand (*) – The demand or functional unit. Needs to be a dictionary to indicate amounts, e.g.
{("my database", "my process"): 2.5}.method (*) – LCIA Method tuple, e.g.
("My", "great", "LCIA", "method"). Can be omitted if only interested in calculating the life cycle inventory.
- Returns:
A new LCA object
- build_demand_array(demand=None)[source]#
Turn the demand dictionary into a NumPy array of correct size.
- Parameters:
demand (*) – Demand dictionary. Optional, defaults to
self.demand.- Returns:
A 1-dimensional NumPy array
- decompose_technosphere()[source]#
Factorize the technosphere matrix into lower and upper triangular matrices, \(A=LU\). Does not solve the linear system \(Ax=B\).
Doesn’t return anything, but creates
self.solver.Warning
Incorrect results could occur if a technosphere matrix was factorized, and then a new technosphere matrix was constructed, as
self.solverwould still be the factorized older technosphere matrix. You are responsible for deletingself.solverwhen doing these types of advanced calculations.
- fix_dictionaries()[source]#
Fix technosphere and biosphere dictionaries from this:
{mapping integer id: matrix row/column index}
To this:
{(database, key): matrix row/column index}
This isn’t needed for the LCA calculation itself, but is helpful when interpreting results.
Doesn’t require any arguments or return anything, but changes
self.activity_dict,self.product_dictandself.biosphere_dict.
- lci(factorize=False, builder=TBMBuilder)[source]#
Calculate a life cycle inventory.
Load LCI data, and construct the technosphere and biosphere matrices.
Build the demand array
Solve the linear system to get the supply array and life cycle inventory.
- Parameters:
factorize (*) – Factorize the technosphere matrix. Makes additional calculations with the same technosphere matrix much faster. Default is
False; not useful is only doing one LCI calculation.builder (*) – Default is
bw2calc.matrices.TechnosphereBiosphereMatrixBuilder, which is fine for most cases. Custom matrix builders can be used to manipulate data in creative ways before building the matrices.
Warning
Custom matrix builders should inherit from
TechnosphereBiosphereMatrixBuilder, because technosphere inputs need to have their signs flipped to be negative, as we do \(A^{-1}f\) directly instead of \((I - A^{-1})f\).Doesn’t return anything, but creates
self.supply_arrayandself.inventory.
- lci_calculation()[source]#
The actual LCI calculation.
Separated from
lcito be reusable in cases where the matrices are already built, e.g.redo_lciand Monte Carlo classes.
- lcia(builder=MatrixBuilder)[source]#
Calculate the life cycle impact assessment.
Load and construct the characterization matrix
Multiply the characterization matrix by the life cycle inventory
- Parameters:
builder (*) – Default is
bw2calc.matrices.MatrixBuilder, which is fine for most cases. Custom matrix builders can be used to manipulate data in creative ways before building the characterization matrix.
Doesn’t return anything, but creates
self.characterized_inventory.
- lcia_calculation()[source]#
The actual LCIA calculation.
Separated from
lciato be reusable in cases where the matrices are already built, e.g.redo_lciaand Monte Carlo classes.
- load_lci_data(fix_dictionaries=True, builder=TBMBuilder)[source]#
Load data and create technosphere and biosphere matrices.
- load_lcia_data(builder=MatrixBuilder)[source]#
Load data and create characterization matrix.
This method will filter out regionalized characterization factors. This filtering needs access to
bw2data- therefore, regionalized methods will cause incorrect results ifbw2datais not importable.
- normalization_calculation()[source]#
The actual normalization calculation.
Creates
self.normalized_inventory.
- rebuild_biosphere_matrix(vector)[source]#
Build a new biosphere matrix using the same row and column indices, but different values. Useful for Monte Carlo iteration or sensitivity analysis.
- Parameters:
vector (*) – 1-dimensional NumPy array with length (# of biosphere parameters), in same order as
self.bio_params.
Doesn’t return anything, but overwrites
self.biosphere_matrix.
- rebuild_characterization_matrix(vector)[source]#
Build a new characterization matrix using the same row and column indices, but different values. Useful for Monte Carlo iteration or sensitivity analysis.
- Parameters:
vector (*) – 1-dimensional NumPy array with length (# of characterization parameters), in same order as
self.cf_params.
Doesn’t return anything, but overwrites
self.characterization_matrix.
- rebuild_technosphere_matrix(vector)[source]#
Build a new technosphere matrix using the same row and column indices, but different values. Useful for Monte Carlo iteration or sensitivity analysis.
- Parameters:
vector (*) – 1-dimensional NumPy array with length (# of technosphere parameters), in same order as
self.tech_params.
Doesn’t return anything, but overwrites
self.technosphere_matrix.
- redo_lci(demand=None)[source]#
Redo LCI with same databases but different demand.
- Parameters:
demand (*) – A demand dictionary.
Doesn’t return anything, but overwrites
self.demand_array,self.supply_array, andself.inventory.Warning
If you want to redo the LCIA as well, use
redo_lcia(demand)directly.
- redo_lcia(demand=None)[source]#
Redo LCIA, optionally with new demand.
- Parameters:
demand (*) – New demand dictionary. Optional, defaults to
self.demand.
Doesn’t return anything, but overwrites
self.characterized_inventory. Ifdemandis given, also overwritesself.demand_array,self.supply_array, andself.inventory.
- reverse_dict()[source]#
Construct reverse dicts from technosphere and biosphere row and col indices to activity_dict/product_dict/biosphere_dict keys.
- Returns:
(reversed
self.activity_dict,self.product_dictandself.biosphere_dict)
- solve_linear_system()[source]#
Master solution function for linear system \(Ax=B\).
To most numerical analysts, matrix inversion is a sin.
—Nicolas Higham, Accuracy and Stability of Numerical Algorithms, Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 2002, p. 260.
We use UMFpack, which is a very fast solver for sparse matrices.
If the technosphere matrix has already been factorized, then the decomposed technosphere (
self.solver) is reused. Otherwise the calculation is redone completely.
- to_dataframe(cutoff=200)[source]#
Return all nonzero elements of characterized inventory as Pandas dataframe
- weight()[source]#
Multiply characterized inventory by weighting value.
Can be done with or without normalization.
- weighting_calculation()[source]#
The actual weighting calculation.
Multiples weighting value by normalized inventory, if available, otherwise by characterized inventory.
Creates
self.weighted_inventory.
- _fixed = False#
- database_filepath#
- demand#
- logger#
- method#
- normalization#
- property score#
- The LCIA score as a ``float``.
Note that this is a property, so it is
foo.lca, notfoo.score()
- seed#
- weighting#
- class bw2calc.LeastSquaresLCA(demand, method=None, weighting=None, normalization=None, database_filepath=None, log_config=None, presamples=None, seed=None, override_presamples_seed=False)[source]#
Bases:
bw2calc.lca.LCA
Solve overdetermined technosphere matrix with more products than activities using least-squares approximation.
See also:
Create a new LCA calculation.
- Parameters:
demand (*) – The demand or functional unit. Needs to be a dictionary to indicate amounts, e.g.
{("my database", "my process"): 2.5}.method (*) – LCIA Method tuple, e.g.
("My", "great", "LCIA", "method"). Can be omitted if only interested in calculating the life cycle inventory.
- Returns:
A new LCA object
- abstract decompose_technosphere()[source]#
Factorize the technosphere matrix into lower and upper triangular matrices, \(A=LU\). Does not solve the linear system \(Ax=B\).
Doesn’t return anything, but creates
self.solver.Warning
Incorrect results could occur if a technosphere matrix was factorized, and then a new technosphere matrix was constructed, as
self.solverwould still be the factorized older technosphere matrix. You are responsible for deletingself.solverwhen doing these types of advanced calculations.
- solve_linear_system(solver=lsmr)[source]#
Master solution function for linear system \(Ax=B\).
To most numerical analysts, matrix inversion is a sin.
—Nicolas Higham, Accuracy and Stability of Numerical Algorithms, Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 2002, p. 260.
We use UMFpack, which is a very fast solver for sparse matrices.
If the technosphere matrix has already been factorized, then the decomposed technosphere (
self.solver) is reused. Otherwise the calculation is redone completely.
- class bw2calc.MatrixBuilder[source]#
Bases:
objectThe class, and its subclasses, load structured arrays, manipulate them, and generate SciPy sparse matrices.
Matrix builders use an array of row indices, an array of column indices, and an array of values to create a coordinate (coo) matrix, which is then converted to a compressed sparse row (csr) matrix.
See the following for more information on structured arrays:
These classes are not instantiated, and have only classmethods. They are not really true classes, but more organizational. In other words, you should use:
MatrixBuilder.build(args)
and not:
mb = MatrixBuilder() mb.build(args)
- classmethod build(paths, data_label, row_id_label, row_index_label, col_id_label=None, col_index_label=None, row_dict=None, col_dict=None, one_d=False, drop_missing=True)[source]#
Build a sparse matrix from NumPy structured array(s).
See more detailed documentation at building-matrices.
This method does the following:
TODO: Update
Load and concatenate the structured arrays files in filepaths
pathsusing the functionutils.load_arrays()into a parameter array.If not
row_dict, usebuild_dictionary()to buildrow_dictfrom the parameter array columnrow_id_label.Using the
row_id_labeland therow_dict, use the methodadd_matrix_indices()to add matrix indices to therow_index_labelcolumn.If not
one_d, do the same tocol_dictandcol_index_label, usingcol_id_label.If not
one_d, usebuild_matrix()to build a sparse matrix usingdata_labelfor the matrix data values, androw_index_labelandcol_index_labelfor row and column indices.Else if
one_d, usebuild_diagonal_matrix()to build a diagonal matrix usingdata_labelfor diagonal matrix data values androw_index_labelas row/column indices.Return the loaded parameter arrays from step 1, row and column dicts from steps 2 & 4, and matrix from step 5 or 6.
- Parameters:
paths (*) – List of array filepaths to load.
data_label (*) – Label of column in parameter arrays with matrix data values.
row_id_label (*) – Label of column in parameter arrays with row ID values, i.e. the integer values returned from
mapping.row_index_label (*) – Label of column in parameter arrays where matrix row indices will be stored.
col_id_label (*) – Label of column in parameter arrays with column ID values, i.e. the integer values returned from
mapping. Not needed for diagonal matrices.col_index_label (*) – Label of column in parameter arrays where matrix column indices will be stored. Not needed for diagonal matrices.
row_dict (*) – Mapping dictionary linking
row_id_labelvalues torow_index_labelvalues. Will be built if not given.col_dict (*) – Mapping dictionary linking
col_id_labelvalues tocol_index_labelvalues. Will be built if not given.one_d (*) – Build diagonal matrix.
drop_missing (*) – Remove rows from the parameter array which aren’t mapped by
row_dictorcol_dict. Default isTrue. Advanced use only.
- Returns:
A numpy parameter array, the row mapping dictionary, the column mapping dictionary, and a COO sparse matrix.
- class bw2calc.MultiLCA(cs_name, log_config=None)[source]#
Bases:
objectWrapper class for performing LCA calculations with many functional units and LCIA methods.
Needs to be passed a
calculation_setupname.This class does not subclass the LCA class, and performs all calculations upon instantiation.
Initialization creates self.results, which is a NumPy array of LCA scores, with rows of functional units and columns of LCIA methods. Ordering is the same as in the calculation_setup.
- property all#
- Get all possible databases by merging all functional units
- func_units#
- lca#
- method_matrices = []#
- methods#
- results#
- class bw2calc.TechnosphereBiosphereMatrixBuilder[source]#
Bases:
MatrixBuilder
Subclass of
MatrixBuilderthat separates technosphere and biosphere parameters- classmethod get_biosphere_inputs_mask(array)[source]#
Get boolean mask of biosphere flows from
array(i.e. the ones to include when building the biosphere matrix).
- classmethod get_technosphere_inputs_mask(array)[source]#
Get boolean mask of technosphere inputs from
array(i.e. the ones to include when building the technosphere matrix).
- bw2calc.load_calculation_package(fp)[source]#
Load a calculation package created by
save_calculation_package.NumPy arrays are saved to a temporary directory, and file paths are adjusted.
fpis the absolute file path of a calculation package file.Returns a dictionary suitable for passing to an LCA object, e.g.
LCA(**load_calculation_package(fp)).