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

BUGFIX: Pin scipy version + fix Sphinx warning #13

Merged
merged 3 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,18 @@ repos:
- id: isort

- repo: https://github.com/pycqa/docformatter
rev: v1.5.1
rev: v1.7.5
hooks:
- id: docformatter
args: [
--in-place,
--make-summary-multi-line,
--close-quotes-on-newline ,
--close-quotes-on-newline,
--pre-summary-newline,
--recursive,
--wrap-summaries=90,
--wrap-descriptions=90,
--blank
]

- repo: https://github.com/psf/black
Expand Down
6 changes: 6 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
History
=======

1.4.0 (2024-03-02)
------------------

* Pin the version of scipy to 1.8.0 to avoid inexact indices changed from a deprecation to raising an error in 1.9
* Fix sphinx warnings

1.3.0 (2024-02-20)
------------------

Expand Down
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
language = "en"

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
Expand Down Expand Up @@ -139,7 +139,7 @@
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# html_static_path = ["_static"]


# -- Options for HTMLHelp output ---------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
brightway2==2.4.1
brightway2==2.4.1 # TODO: Upgrade to 2.5
bw-migrations==0.1
bw2analyzer==0.10
bw2calc==1.8.2
Expand All @@ -16,7 +16,7 @@ PySide2==5.15.2.1
pytest
pytest-cov
pytest-flake8
scipy==1.9.0
scipy==1.8.0 # To avoid https://stackoverflow.com/questions/74219727/brightway2-lca-scores-calculations/74371350#74371350
swolfpy_inputdata==1.1.*
swolfpy_processmodels==1.1.*
xlrd==1.2.0
9 changes: 7 additions & 2 deletions swolfpy/LCA_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
class LCA_matrix(LCA):
"""
This class translate the ``row`` and ``col`` of the ``tech_param`` and ``bio_param``
to the activity `key` in the Brightway2 database. \n Both the ``tech_param`` and
to the activity `key` in the Brightway2 database. Both the ``tech_param`` and
``bio_param`` has the ``dtype=[('input', '<u4'), ('output', '<u4'), ('row', '<u4'),
('col', '<u4'), ('type', 'u1'), ('uncertainty_type', 'u1'), ('amount', '<f4'), ('loc',
'<f4'), ('scale', '<f4'), ('shape', '<f4'), ('minimum', '<f4'), ('maximum', '<f4'),
('negative', '?')])`` data type. \n.
('negative', '?')])`` data type.

``self.tech_matrix`` is a dictionary that includes all the technosphere and waste exchanges as tuple ``(product,Feed)`` key and amount as value:
``{(('LF', 'Aerobic_Residual'), ('SF1_product', 'Aerobic_Residual_MRDO')):0.828}``
Expand All @@ -21,6 +21,7 @@ class LCA_matrix(LCA):

So we can update the ``tech_params`` and ``bio_params`` by tuple keys that are consistent with the keys
in the ``ProcessModel.report()``. Check :ref:`Process models class <ProcessModel>` for more info.

"""

def __init__(self, functional_unit, method):
Expand Down Expand Up @@ -66,6 +67,7 @@ def update_techmatrix(process_name, report_dict, tech_matrix):

:param tech_matrix:
:type tech_matrix: ``LCA_matrix.tech_matrix``

"""
for material, value in report_dict["Technosphere"].items():
for key2, value2 in value.items():
Expand Down Expand Up @@ -188,6 +190,7 @@ def update_biomatrix(process_name, report_dict, bio_matrix):

:param bio_matrix:
:type bio_matrix: ``LCA_matrix.bio_matrix``

"""
for material, value in report_dict["Biosphere"].items():
for key2, value2 in value.items():
Expand Down Expand Up @@ -272,6 +275,7 @@ def get_mass_flow(LCA, process):

:return: Total mass of flows to `process`
:rtype: float

"""
mass = 0
for i in LCA.activity_dict:
Expand Down Expand Up @@ -300,6 +304,7 @@ def get_mass_flow_comp(LCA, process, index):

:return: Pandas series with mass flows as values and index as rows.
:rtype: pandas.core.series.Series

"""
mass = pd.Series(np.zeros(len(index)), index=index)
for i in LCA.activity_dict:
Expand Down
8 changes: 6 additions & 2 deletions swolfpy/Monte_Carlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
class Monte_Carlo(LCA_matrix):
"""
Setups the Monte Carlo simulation. This class is inherited from
``swolfpy.LCA_matrix``. \n The Monte Carlo simulation will be only done for the
process models, common data or parameters than the class gets by arguments.
``swolfpy.LCA_matrix``. The Monte Carlo simulation will be only done for the process
models, common data or parameters than the class gets by arguments.

:param functional_unit: ``{flow:amount}``
:type functional_unit: dict
Expand All @@ -38,6 +38,7 @@ class Monte_Carlo(LCA_matrix):

:param seed: seed for ``stats_arrays.RandomNumberGenerator``
:type seed: int, optional

"""

def __init__(
Expand Down Expand Up @@ -72,6 +73,7 @@ def run(self, nproc, n):
:type nproc: int
:param n: Number of iterations in MC
:type n: int

"""

def pool_adapter(x):
Expand Down Expand Up @@ -169,6 +171,7 @@ def parallel_mc(
and ``bio_matrix``.

Creates new ``bio_param`` and ``tech_param`` and then recalculate the LCA.

"""
uncertain_inputs = []
if process_models:
Expand Down Expand Up @@ -223,6 +226,7 @@ def result_to_DF(self):

:return: Monte Carlo results
:rtype: ``pandas.DataFrame``

"""
output = pd.DataFrame()
# Reporting the LCIA results; Create a column for each method
Expand Down
22 changes: 14 additions & 8 deletions swolfpy/Optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def _objective_function(self, x):
### Mass to process
def get_mass_flow_from_supply_array(self, key, KeyType, x):
"""
calculate the mass to the process from the `supply_array` matrix.
Calculate the mass to the process from the `supply_array` matrix.
"""
self._objective_function(x)

Expand All @@ -186,7 +186,7 @@ def get_mass_flow_from_supply_array(self, key, KeyType, x):
### Emission flow in LCI
def get_emission_amount(self, emission, x):
"""
calculate the mass of the `emission` to biosphere from the `inventory`.
Calculate the mass of the `emission` to biosphere from the `inventory`.
"""
self._objective_function(x)
inventory = self.biosphere_matrix * self.supply_array
Expand Down Expand Up @@ -337,9 +337,13 @@ def multi_start_optimization(
initialize_guess="random",
):
"""
Call the ``scipy.optimize.minimize()`` to minimize the LCA score. \n
``constraints`` is python dictionary. \n Constraint type can be ``'<='`` or
``'>='``. \n Three kind of constraints are defined as below: \n.
Call the ``scipy.optimize.minimize()`` to minimize the LCA score.

Notes
-----
- ``constraints`` is python dictionary.
- Constraint type can be ``'<='`` or ``'>='``.
- Three kind of constraints are defined as below:

* **Process:** Constraint on the total mass to the process. The ``'KeyType'`` should be ``'Process'``
(e.g., The capacity of the WTE). Example:
Expand All @@ -360,6 +364,7 @@ def multi_start_optimization(
>>> constraints = {}
>>> # Use database key as key in dict
>>> constraints[('biosphere3', 'eba59fd6-f37e-41dc-9ca3-c7ea22d602c7')] = {'limit':100,'KeyType':'Emission','ConstType':"<="}

"""
optObject.constraints = constraints
optObject.collection = collection
Expand Down Expand Up @@ -517,16 +522,17 @@ def set_optimized_parameters_to_project(self):

def plot_sankey(self, optimized_flow=True, show=True, fileName=None, params=None):
"""
Plots a sankey diagram for the waste mass flows. \n Calls the
``plotly.graph_objs.Sankey`` to plot sankey. \n Calculates the mass flows by
calling ``self.get_mass_flow_from_supply_array()``. \n.
Plots a sankey diagram for the waste mass flows. Calls the
``plotly.graph_objs.Sankey`` to plot sankey. Calculates the mass flows by calling
``self.get_mass_flow_from_supply_array()``.

:param optimized_flow: If ``True``, it plots the sankey based on the optimized waste fractions.
If ``False``, it plots the sankey based on the current waste fractions by calling ``self.project.parameters_list``.
:type optimized_flow: bool

:param show: If ``True``, it will show the figure
:type show: bool

"""
if optimized_flow:
params = [i["amount"] for i in self.optimized_x]
Expand Down
7 changes: 5 additions & 2 deletions swolfpy/Parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ def add_parameter(
:type process_model_to: str
:param value: Value for the parameter
:type value: float

"""
param_name = (
"frac_of_" + product + "_from_" + process_model_from + "_to_" + process_model_to
Expand Down Expand Up @@ -123,10 +124,10 @@ def add_parameter(
def SWM_network(self, view=True, show_vals=True, all_flow=True, filename="SWM_network"):
"""
To render the generated DOT source code, you also need to install `Graphviz.

<https://www.graphviz.org/download>`_.

..note:: Make sure that the directory containing the dot executable is on your systems path.

"""
# Initialize SWM network
self.network = graphviz.Digraph(
Expand Down Expand Up @@ -222,10 +223,11 @@ def check_sum(self):

def add_uncertainty(self, param_name, **kwargs):
"""
add uncertainty to parameter.
Add uncertainty to parameter.

:param param_name: Name of the parameter (wastefraction) that has uncertainty
:type param_name: str

"""
base_dict = {}
base_dict["loc"] = kwargs.get("loc", None)
Expand Down Expand Up @@ -300,6 +302,7 @@ def MC_get_param_val(self, param_name):
:type param_name: str
:return: Value of the parameter
:rtype: float

"""
for item in self.MC_param_uncertainty_dict.values():
for list_item in item:
Expand Down
30 changes: 23 additions & 7 deletions swolfpy/Project.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,14 @@ class Project:
>>> demo.write_project()
>>> demo.group_exchanges()
>>> demo.parameters.default_parameters_list()

[{'name': 'frac_of_Bottom_Ash_from_WTE_to_LF', 'amount': 1.0},
{'name': 'frac_of_Fly_Ash_from_WTE_to_LF', 'amount': 1.0},
{'name': 'frac_of_RWC_from_SF_COl_to_LF', 'amount': 0.5},
{'name': 'frac_of_RWC_from_SF_COl_to_WTE', 'amount': 0.5}]

>>> demo.update_parameters(demo.parameters.default_parameters_list())

"""

def __init__(
Expand Down Expand Up @@ -147,6 +150,7 @@ def _find_destination(self, product):

:return: A list of the discovered processes in the ``Treatment_processes`` dictionary that can treat the `product`
:rtype: list

"""
destination = []
for P in self.Treatment_processes:
Expand All @@ -156,10 +160,12 @@ def _find_destination(self, product):

def init_project(self, signal=None):
"""
Calls the Create_Technosphere_ method to initialize a project.\n This function
create an empty database for each process as a placeholder, so swolfpy can browse
these databases in the next step (writing project) and create exchanges between
them.
Calls the Create_Technosphere_ method to initialize a project.

This function create an empty database for each process as a placeholder, so
swolfpy can browse these databases in the next step (writing project) and create
exchanges between them.

"""
if signal:
self._progress += 5
Expand Down Expand Up @@ -211,11 +217,13 @@ def _import_database(self, name):
"""
.. _import_database:

Instantiate the ProcessDB_ class for the process model and gets the LCI report from it; then translates
the report for Brightway2 and populates the databases by Write_DB_ method.
Instantiate the ProcessDB_ class for the process model and gets the LCI report
from it; then translates the report for Brightway2 and populates the databases by
Write_DB_ method.

:return: Returns a tuple (parameters,act_in_group)
:rtype: tuple

"""
self.process_model[name] = ProcessDB(
name, self.waste_treatment, self.CommonData, self.processTypes, self.Distance
Expand Down Expand Up @@ -255,8 +263,10 @@ def report_parameters(self):
"""
Reports the `parameters` in dictionary format.

:return: dictionary include the processes as key and parameters in each process as values.
:return: dictionary include the processes as key and parameters in each process as
values.
:rtype: dict

"""
return self.parameters_dict

Expand All @@ -266,6 +276,7 @@ def report_parameters_list(self):

:return: List of `parameters` (waste fractions) in the project
:rtype: list

"""
return self.parameters_list

Expand All @@ -276,6 +287,7 @@ def group_exchanges(self, signal=None):

As a results, model know to update the values in those exchanges when the
`parameter` is updated

"""
for j in self.processes:
print(
Expand Down Expand Up @@ -306,6 +318,7 @@ def update_parameters(self, new_param_data, signal=None):

.. note:: `parameters` are waste fractions which show what fraction of waste from one source
go to different destinations, so sum of parameters from each source should be 1. (0<= `parameters` <=1)

"""

progress = 0
Expand Down Expand Up @@ -374,6 +387,7 @@ def setup_LCA(name, functional_units, impact_methods):

``bw2calc.multi_lca`` is a wrapper class for performing LCA calculations with many
functional units and LCIA methods.

"""
if len(functional_units) > 0 and len(impact_methods) > 0:
calculation_setups[name] = {"inv": functional_units, "ia": impact_methods}
Expand Down Expand Up @@ -402,6 +416,7 @@ def contribution_analysis(

* ``bw2analyzer.ContributionAnalysis.annotated_top_processes``
* ``bw2analyzer.ContributionAnalysis.annotated_top_emissions``

"""
lca = LCA(functional_unit, impact_method)
lca.lci()
Expand Down Expand Up @@ -488,6 +503,7 @@ def save(self, filename):

:param filename:
:type filename: str

"""
with open(filename, "wb") as f:
pickle.dump(self, f)
Loading
Loading