bw-functional 0b79__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bw_functional-0b79/LICENSE +12 -0
- bw_functional-0b79/MANIFEST.in +0 -0
- bw_functional-0b79/PKG-INFO +216 -0
- bw_functional-0b79/README.md +173 -0
- bw_functional-0b79/bw_functional/__init__.py +65 -0
- bw_functional-0b79/bw_functional/allocation.py +142 -0
- bw_functional-0b79/bw_functional/convert.py +143 -0
- bw_functional-0b79/bw_functional/database.py +514 -0
- bw_functional-0b79/bw_functional/edge_classes.py +166 -0
- bw_functional-0b79/bw_functional/node_classes.py +591 -0
- bw_functional-0b79/bw_functional.egg-info/PKG-INFO +216 -0
- bw_functional-0b79/bw_functional.egg-info/SOURCES.txt +21 -0
- bw_functional-0b79/bw_functional.egg-info/dependency_links.txt +1 -0
- bw_functional-0b79/bw_functional.egg-info/requires.txt +22 -0
- bw_functional-0b79/bw_functional.egg-info/top_level.txt +1 -0
- bw_functional-0b79/pyproject.toml +98 -0
- bw_functional-0b79/setup.cfg +4 -0
- bw_functional-0b79/setup.py +18 -0
- bw_functional-0b79/tests/test_allocation.py +132 -0
- bw_functional-0b79/tests/test_database.py +5 -0
- bw_functional-0b79/tests/test_mf_node.py +33 -0
- bw_functional-0b79/tests/test_process_node.py +175 -0
- bw_functional-0b79/tests/test_product_node.py +250 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Copyright 2024 Chris Mutel
|
|
2
|
+
Copyright 2025 Leiden University
|
|
3
|
+
|
|
4
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
5
|
+
|
|
6
|
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
7
|
+
|
|
8
|
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
9
|
+
|
|
10
|
+
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
11
|
+
|
|
12
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
File without changes
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bw-functional
|
|
3
|
+
Version: 0b79
|
|
4
|
+
Summary: Code for handling multifunctional activities in Brightway
|
|
5
|
+
Author-email: Chris Mutel <cmutel@gmail.com>, Marin Visscher <m.r.visscher@cml.leidenuniv.nl>
|
|
6
|
+
Maintainer-email: Marin Visscher <m.r.visscher@cml.leidenuniv.nl>
|
|
7
|
+
Project-URL: source, https://github.com/brightway-lca/multifunctional
|
|
8
|
+
Project-URL: homepage, https://github.com/brightway-lca/multifunctional
|
|
9
|
+
Project-URL: tracker, https://github.com/brightway-lca/multifunctional/issues
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Programming Language :: Python
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Natural Language :: English
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: blinker
|
|
23
|
+
Requires-Dist: bw2data>=4.0.1
|
|
24
|
+
Requires-Dist: bw2io>=0.9.1
|
|
25
|
+
Requires-Dist: bw_processing>=0.9.6
|
|
26
|
+
Requires-Dist: numpy<2
|
|
27
|
+
Provides-Extra: testing
|
|
28
|
+
Requires-Dist: bw-functional; extra == "testing"
|
|
29
|
+
Requires-Dist: bw2calc>=2.0.1; extra == "testing"
|
|
30
|
+
Requires-Dist: pytest; extra == "testing"
|
|
31
|
+
Requires-Dist: pytest-cov; extra == "testing"
|
|
32
|
+
Requires-Dist: pytest-loguru; extra == "testing"
|
|
33
|
+
Requires-Dist: python-coveralls; extra == "testing"
|
|
34
|
+
Provides-Extra: dev
|
|
35
|
+
Requires-Dist: build; extra == "dev"
|
|
36
|
+
Requires-Dist: pre-commit; extra == "dev"
|
|
37
|
+
Requires-Dist: pylint; extra == "dev"
|
|
38
|
+
Requires-Dist: pytest; extra == "dev"
|
|
39
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
40
|
+
Requires-Dist: pytest-randomly; extra == "dev"
|
|
41
|
+
Requires-Dist: setuptools; extra == "dev"
|
|
42
|
+
Dynamic: license-file
|
|
43
|
+
|
|
44
|
+
# bw-functional
|
|
45
|
+
|
|
46
|
+
[][pypi status]
|
|
47
|
+
[][pypi status]
|
|
48
|
+
[][pypi status]
|
|
49
|
+
[][license]
|
|
50
|
+
|
|
51
|
+
[][read the docs]
|
|
52
|
+
[][tests]
|
|
53
|
+
[][codecov]
|
|
54
|
+
|
|
55
|
+
[][pre-commit]
|
|
56
|
+
[][black]
|
|
57
|
+
|
|
58
|
+
[pypi status]: https://pypi.org/project/multifunctional/
|
|
59
|
+
[read the docs]: https://multifunctional.readthedocs.io/
|
|
60
|
+
[tests]: https://github.com/brightway-lca/multifunctional/actions?workflow=Tests
|
|
61
|
+
[codecov]: https://app.codecov.io/gh/brightway-lca/multifunctional
|
|
62
|
+
[pre-commit]: https://github.com/pre-commit/pre-commit
|
|
63
|
+
[black]: https://github.com/psf/black
|
|
64
|
+
|
|
65
|
+
Adding functions to Brightway processes
|
|
66
|
+
|
|
67
|
+
## Installation
|
|
68
|
+
|
|
69
|
+
You can install _bw-functional_ via [pip] from [PyPI]:
|
|
70
|
+
|
|
71
|
+
```console
|
|
72
|
+
$ pip install bw-functional
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
[//]: # (It is also available on `anaconda` using `mamba` or `conda` at the `cmutel` channel:)
|
|
76
|
+
|
|
77
|
+
[//]: # ()
|
|
78
|
+
[//]: # (```console)
|
|
79
|
+
|
|
80
|
+
[//]: # (mamba install -c conda-forge -c cmutel multifunctional)
|
|
81
|
+
|
|
82
|
+
[//]: # (```)
|
|
83
|
+
|
|
84
|
+
## Usage
|
|
85
|
+
|
|
86
|
+
Multifunctional activities can lead to linear algebra problems which don't have exactly one solution. Therefore, we commonly need to apply a handling function to either partition such activities, or otherwise manipulate their data such that they allow for the creation of a square and non-singular technosphere matrix.
|
|
87
|
+
|
|
88
|
+
This library is designed around the following workflow:
|
|
89
|
+
|
|
90
|
+
Users create and register a `bw_functional.FunctionalSQLiteDatabase`. Registering this database must include the database metadata key `default_allocation`, which refers to an allocation strategy function present in `bw_functional.allocation_strategies`.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
import bw_functional
|
|
94
|
+
mf_db = bw_functional.FunctionalSQLiteDatabase("emojis FTW")
|
|
95
|
+
mf_db.register()
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Multifunctional process(es) are created and written to the `FunctionalSQLiteDatabase`. A multifunctional process is any process with multiple "functions", either outputs (products) and/or input (reducts).
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
mf_data = {
|
|
102
|
+
("emojis FTW", "😼"): {
|
|
103
|
+
"type": "product",
|
|
104
|
+
"name": "meow",
|
|
105
|
+
"unit": "kg",
|
|
106
|
+
"processor": ("emojis FTW", "1"),
|
|
107
|
+
"properties": {
|
|
108
|
+
"price": {'unit': 'EUR', 'amount': 7, 'normalize': True},
|
|
109
|
+
"mass": {'unit': 'kg', 'amount': 1, 'normalize': True},
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
("emojis FTW", "🐶"): {
|
|
113
|
+
"type": "product",
|
|
114
|
+
"name": "woof",
|
|
115
|
+
"unit": "kg",
|
|
116
|
+
"processor": ("emojis FTW", "1"),
|
|
117
|
+
"properties": {
|
|
118
|
+
"price": {'unit': 'EUR', 'amount': 12, 'normalize': True},
|
|
119
|
+
"mass": {'unit': 'kg', 'amount': 4, 'normalize': True},
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
("emojis FTW", "1"): {
|
|
123
|
+
"name": "process - 1",
|
|
124
|
+
"location": "somewhere",
|
|
125
|
+
"exchanges": [
|
|
126
|
+
{
|
|
127
|
+
"type": "production",
|
|
128
|
+
"input": ("emojis FTW", "😼"),
|
|
129
|
+
"amount": 4,
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
"type": "production",
|
|
133
|
+
"input": ("emojis FTW", "🐶"),
|
|
134
|
+
"amount": 6,
|
|
135
|
+
},
|
|
136
|
+
],
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
LCA calculations can then be done as normal. See `dev/basic_example.ipynb` for a simple example.
|
|
141
|
+
|
|
142
|
+
### Substitution
|
|
143
|
+
|
|
144
|
+
_WORK IN PROGRESS_
|
|
145
|
+
|
|
146
|
+
### Built-in allocation functions
|
|
147
|
+
|
|
148
|
+
`bw-functional` includes the following built-in allocation functions:
|
|
149
|
+
|
|
150
|
+
* `manual_allocation`: Does allocation based on the "allocation" field of the Product. Doesn't normalize by amount of production exchange.
|
|
151
|
+
* `equal`: Splits burdens equally among all functional edges.
|
|
152
|
+
|
|
153
|
+
You can also do property-based allocation by specifying the property label in the `allocation` field of the Process.
|
|
154
|
+
|
|
155
|
+
## Technical notes
|
|
156
|
+
|
|
157
|
+
### Process-specific allocation strategies
|
|
158
|
+
|
|
159
|
+
Individual processes can override the default database allocation by specifying their own `allocation`:
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
import bw2data as bd
|
|
163
|
+
node = bd.get_activity(database="emojis FTW", code="1")
|
|
164
|
+
node["allocation"] = "mass"
|
|
165
|
+
node.save()
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## How does it work?
|
|
169
|
+
|
|
170
|
+
Recent Brightway versions allow users to specify which graph nodes types should be used when building matrices, and which types can be ignored. We create a multifunctional process node with the type `multifunctional`, which will be ignored when creating processed datapackages. However, in our database class `FunctionalSQLiteDatabase` we change the function which creates these processed datapackages to load the multifunctional processes, perform whatever strategy is needed to handle multifunctionality, and then use the results of those handling strategies (e.g. monofunctional processes) in the processed datapackage.
|
|
171
|
+
|
|
172
|
+
We also tell `MultifunctionalDatabase` to load a new `ReadOnlyProcess` process class instead of the standard `Activity` class when interacting with the database. This new class is read only because the data is generated from the multifunctional process itself - if updates are needed, either that input process or the allocation function should be modified.
|
|
173
|
+
|
|
174
|
+
## Contributing
|
|
175
|
+
|
|
176
|
+
Contributions are very welcome.
|
|
177
|
+
To learn more, see the [Contributor Guide][Contributor Guide].
|
|
178
|
+
|
|
179
|
+
## License
|
|
180
|
+
|
|
181
|
+
Distributed under the terms of the [BSD 3 Clause license][License],
|
|
182
|
+
_multifunctional_ is free and open source software.
|
|
183
|
+
|
|
184
|
+
## Issues
|
|
185
|
+
|
|
186
|
+
If you encounter any problems,
|
|
187
|
+
please [file an issue][Issue Tracker] along with a detailed description.
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
<!-- github-only -->
|
|
191
|
+
|
|
192
|
+
[command-line reference]: https://multifunctional.readthedocs.io/en/latest/usage.html
|
|
193
|
+
[License]: https://github.com/brightway-lca/multifunctional/blob/main/LICENSE
|
|
194
|
+
[Contributor Guide]: https://github.com/brightway-lca/multifunctional/blob/main/CONTRIBUTING.md
|
|
195
|
+
[Issue Tracker]: https://github.com/brightway-lca/multifunctional/issues
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
## Building the Documentation
|
|
199
|
+
|
|
200
|
+
You can build the documentation locally by installing the documentation Conda environment:
|
|
201
|
+
|
|
202
|
+
```bash
|
|
203
|
+
conda env create -f docs/environment.yml
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
activating the environment
|
|
207
|
+
|
|
208
|
+
```bash
|
|
209
|
+
conda activate sphinx_multifunctional
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
and [running the build command](https://www.sphinx-doc.org/en/master/man/sphinx-build.html#sphinx-build):
|
|
213
|
+
|
|
214
|
+
```bash
|
|
215
|
+
sphinx-build docs _build/html --builder=html --jobs=auto --write-all; open _build/html/index.html
|
|
216
|
+
```
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# bw-functional
|
|
2
|
+
|
|
3
|
+
[][pypi status]
|
|
4
|
+
[][pypi status]
|
|
5
|
+
[][pypi status]
|
|
6
|
+
[][license]
|
|
7
|
+
|
|
8
|
+
[][read the docs]
|
|
9
|
+
[][tests]
|
|
10
|
+
[][codecov]
|
|
11
|
+
|
|
12
|
+
[][pre-commit]
|
|
13
|
+
[][black]
|
|
14
|
+
|
|
15
|
+
[pypi status]: https://pypi.org/project/multifunctional/
|
|
16
|
+
[read the docs]: https://multifunctional.readthedocs.io/
|
|
17
|
+
[tests]: https://github.com/brightway-lca/multifunctional/actions?workflow=Tests
|
|
18
|
+
[codecov]: https://app.codecov.io/gh/brightway-lca/multifunctional
|
|
19
|
+
[pre-commit]: https://github.com/pre-commit/pre-commit
|
|
20
|
+
[black]: https://github.com/psf/black
|
|
21
|
+
|
|
22
|
+
Adding functions to Brightway processes
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
You can install _bw-functional_ via [pip] from [PyPI]:
|
|
27
|
+
|
|
28
|
+
```console
|
|
29
|
+
$ pip install bw-functional
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
[//]: # (It is also available on `anaconda` using `mamba` or `conda` at the `cmutel` channel:)
|
|
33
|
+
|
|
34
|
+
[//]: # ()
|
|
35
|
+
[//]: # (```console)
|
|
36
|
+
|
|
37
|
+
[//]: # (mamba install -c conda-forge -c cmutel multifunctional)
|
|
38
|
+
|
|
39
|
+
[//]: # (```)
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
Multifunctional activities can lead to linear algebra problems which don't have exactly one solution. Therefore, we commonly need to apply a handling function to either partition such activities, or otherwise manipulate their data such that they allow for the creation of a square and non-singular technosphere matrix.
|
|
44
|
+
|
|
45
|
+
This library is designed around the following workflow:
|
|
46
|
+
|
|
47
|
+
Users create and register a `bw_functional.FunctionalSQLiteDatabase`. Registering this database must include the database metadata key `default_allocation`, which refers to an allocation strategy function present in `bw_functional.allocation_strategies`.
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
import bw_functional
|
|
51
|
+
mf_db = bw_functional.FunctionalSQLiteDatabase("emojis FTW")
|
|
52
|
+
mf_db.register()
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Multifunctional process(es) are created and written to the `FunctionalSQLiteDatabase`. A multifunctional process is any process with multiple "functions", either outputs (products) and/or input (reducts).
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
mf_data = {
|
|
59
|
+
("emojis FTW", "😼"): {
|
|
60
|
+
"type": "product",
|
|
61
|
+
"name": "meow",
|
|
62
|
+
"unit": "kg",
|
|
63
|
+
"processor": ("emojis FTW", "1"),
|
|
64
|
+
"properties": {
|
|
65
|
+
"price": {'unit': 'EUR', 'amount': 7, 'normalize': True},
|
|
66
|
+
"mass": {'unit': 'kg', 'amount': 1, 'normalize': True},
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
("emojis FTW", "🐶"): {
|
|
70
|
+
"type": "product",
|
|
71
|
+
"name": "woof",
|
|
72
|
+
"unit": "kg",
|
|
73
|
+
"processor": ("emojis FTW", "1"),
|
|
74
|
+
"properties": {
|
|
75
|
+
"price": {'unit': 'EUR', 'amount': 12, 'normalize': True},
|
|
76
|
+
"mass": {'unit': 'kg', 'amount': 4, 'normalize': True},
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
("emojis FTW", "1"): {
|
|
80
|
+
"name": "process - 1",
|
|
81
|
+
"location": "somewhere",
|
|
82
|
+
"exchanges": [
|
|
83
|
+
{
|
|
84
|
+
"type": "production",
|
|
85
|
+
"input": ("emojis FTW", "😼"),
|
|
86
|
+
"amount": 4,
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
"type": "production",
|
|
90
|
+
"input": ("emojis FTW", "🐶"),
|
|
91
|
+
"amount": 6,
|
|
92
|
+
},
|
|
93
|
+
],
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
LCA calculations can then be done as normal. See `dev/basic_example.ipynb` for a simple example.
|
|
98
|
+
|
|
99
|
+
### Substitution
|
|
100
|
+
|
|
101
|
+
_WORK IN PROGRESS_
|
|
102
|
+
|
|
103
|
+
### Built-in allocation functions
|
|
104
|
+
|
|
105
|
+
`bw-functional` includes the following built-in allocation functions:
|
|
106
|
+
|
|
107
|
+
* `manual_allocation`: Does allocation based on the "allocation" field of the Product. Doesn't normalize by amount of production exchange.
|
|
108
|
+
* `equal`: Splits burdens equally among all functional edges.
|
|
109
|
+
|
|
110
|
+
You can also do property-based allocation by specifying the property label in the `allocation` field of the Process.
|
|
111
|
+
|
|
112
|
+
## Technical notes
|
|
113
|
+
|
|
114
|
+
### Process-specific allocation strategies
|
|
115
|
+
|
|
116
|
+
Individual processes can override the default database allocation by specifying their own `allocation`:
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
import bw2data as bd
|
|
120
|
+
node = bd.get_activity(database="emojis FTW", code="1")
|
|
121
|
+
node["allocation"] = "mass"
|
|
122
|
+
node.save()
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## How does it work?
|
|
126
|
+
|
|
127
|
+
Recent Brightway versions allow users to specify which graph nodes types should be used when building matrices, and which types can be ignored. We create a multifunctional process node with the type `multifunctional`, which will be ignored when creating processed datapackages. However, in our database class `FunctionalSQLiteDatabase` we change the function which creates these processed datapackages to load the multifunctional processes, perform whatever strategy is needed to handle multifunctionality, and then use the results of those handling strategies (e.g. monofunctional processes) in the processed datapackage.
|
|
128
|
+
|
|
129
|
+
We also tell `MultifunctionalDatabase` to load a new `ReadOnlyProcess` process class instead of the standard `Activity` class when interacting with the database. This new class is read only because the data is generated from the multifunctional process itself - if updates are needed, either that input process or the allocation function should be modified.
|
|
130
|
+
|
|
131
|
+
## Contributing
|
|
132
|
+
|
|
133
|
+
Contributions are very welcome.
|
|
134
|
+
To learn more, see the [Contributor Guide][Contributor Guide].
|
|
135
|
+
|
|
136
|
+
## License
|
|
137
|
+
|
|
138
|
+
Distributed under the terms of the [BSD 3 Clause license][License],
|
|
139
|
+
_multifunctional_ is free and open source software.
|
|
140
|
+
|
|
141
|
+
## Issues
|
|
142
|
+
|
|
143
|
+
If you encounter any problems,
|
|
144
|
+
please [file an issue][Issue Tracker] along with a detailed description.
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
<!-- github-only -->
|
|
148
|
+
|
|
149
|
+
[command-line reference]: https://multifunctional.readthedocs.io/en/latest/usage.html
|
|
150
|
+
[License]: https://github.com/brightway-lca/multifunctional/blob/main/LICENSE
|
|
151
|
+
[Contributor Guide]: https://github.com/brightway-lca/multifunctional/blob/main/CONTRIBUTING.md
|
|
152
|
+
[Issue Tracker]: https://github.com/brightway-lca/multifunctional/issues
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
## Building the Documentation
|
|
156
|
+
|
|
157
|
+
You can build the documentation locally by installing the documentation Conda environment:
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
conda env create -f docs/environment.yml
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
activating the environment
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
conda activate sphinx_multifunctional
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
and [running the build command](https://www.sphinx-doc.org/en/master/man/sphinx-build.html#sphinx-build):
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
sphinx-build docs _build/html --builder=html --jobs=auto --write-all; open _build/html/index.html
|
|
173
|
+
```
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
__all__ = (
|
|
2
|
+
"__version__",
|
|
3
|
+
"allocation_strategies",
|
|
4
|
+
"generic_allocation",
|
|
5
|
+
"Process",
|
|
6
|
+
"Product",
|
|
7
|
+
"MFExchange",
|
|
8
|
+
"MFExchanges",
|
|
9
|
+
"FunctionalSQLiteDatabase",
|
|
10
|
+
"property_allocation",
|
|
11
|
+
)
|
|
12
|
+
# import os
|
|
13
|
+
__version__ = "0.0.2"
|
|
14
|
+
|
|
15
|
+
from logging import getLogger
|
|
16
|
+
|
|
17
|
+
from bw2data import labels
|
|
18
|
+
from bw2data.subclass_mapping import DATABASE_BACKEND_MAPPING, NODE_PROCESS_CLASS_MAPPING
|
|
19
|
+
|
|
20
|
+
from .allocation import allocation_strategies, generic_allocation, property_allocation
|
|
21
|
+
from .database import FunctionalSQLiteDatabase
|
|
22
|
+
from .node_classes import Process, Product
|
|
23
|
+
from .edge_classes import MFExchange, MFExchanges
|
|
24
|
+
|
|
25
|
+
log = getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
DATABASE_BACKEND_MAPPING["functional_sqlite"] = FunctionalSQLiteDatabase
|
|
28
|
+
NODE_PROCESS_CLASS_MAPPING["functional_sqlite"] = FunctionalSQLiteDatabase.node_class
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
if "waste" not in labels.node_types:
|
|
32
|
+
labels.lci_node_types.append("waste")
|
|
33
|
+
if "nonfunctional" not in labels.node_types:
|
|
34
|
+
labels.other_node_types.append("nonfunctional")
|
|
35
|
+
|
|
36
|
+
# make sure allocation happens on parameter changes
|
|
37
|
+
def _init_signals():
|
|
38
|
+
from bw2data.signals import on_activity_parameter_recalculate
|
|
39
|
+
|
|
40
|
+
on_activity_parameter_recalculate.connect(_check_parameterized_exchange_for_allocation)
|
|
41
|
+
|
|
42
|
+
def _check_parameterized_exchange_for_allocation(_, name):
|
|
43
|
+
import bw2data as bd
|
|
44
|
+
from bw2data.parameters import ParameterizedExchange
|
|
45
|
+
from bw2data.backends import ExchangeDataset
|
|
46
|
+
|
|
47
|
+
databases = [k for k, v in bd.databases.items() if v["backend"] == "functional_sqlite"]
|
|
48
|
+
|
|
49
|
+
p_exchanges = ParameterizedExchange.select().where(ParameterizedExchange.group==name)
|
|
50
|
+
exc_ids = [p_exc.exchange for p_exc in p_exchanges]
|
|
51
|
+
exchanges = ExchangeDataset.select(ExchangeDataset.output_database, ExchangeDataset.output_code).where(
|
|
52
|
+
(ExchangeDataset.id.in_(exc_ids)) &
|
|
53
|
+
(ExchangeDataset.type == "production") &
|
|
54
|
+
(ExchangeDataset.output_database.in_(databases))
|
|
55
|
+
)
|
|
56
|
+
process_keys = set(exchanges.tuples())
|
|
57
|
+
|
|
58
|
+
for key in process_keys:
|
|
59
|
+
process = bd.get_activity(key)
|
|
60
|
+
if not isinstance(process, Process):
|
|
61
|
+
log.warning(f"Process {key} is not an instance of Process, skipping allocation check.")
|
|
62
|
+
continue
|
|
63
|
+
process.allocate()
|
|
64
|
+
|
|
65
|
+
_init_signals()
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
from functools import partial
|
|
2
|
+
from typing import Callable, List
|
|
3
|
+
from logging import getLogger
|
|
4
|
+
|
|
5
|
+
from .node_classes import Process, Product
|
|
6
|
+
|
|
7
|
+
log = getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def generic_allocation(
|
|
11
|
+
process: Process,
|
|
12
|
+
getter: lambda function: float(),
|
|
13
|
+
) -> None:
|
|
14
|
+
"""
|
|
15
|
+
Perform allocation for a multifunctional process using a specified getter function.
|
|
16
|
+
|
|
17
|
+
This function calculates allocation factors for each product in a multifunctional process
|
|
18
|
+
based on the values returned by the `getter` function. The allocation factor for each product
|
|
19
|
+
is determined by dividing the value returned by the `getter` function for that function by the
|
|
20
|
+
sum of all values returned by the `getter` function for all product in the process.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
process (Process): The process object to allocate. Must be an instance of the `Process` class.
|
|
24
|
+
getter (Callable): A function that takes a `Product` object and returns a float value
|
|
25
|
+
used for allocation calculations.
|
|
26
|
+
|
|
27
|
+
Raises:
|
|
28
|
+
ValueError: If the `process` is not an instance of the `Process` class.
|
|
29
|
+
ZeroDivisionError: If the sum of allocation factors is zero.
|
|
30
|
+
|
|
31
|
+
Notes:
|
|
32
|
+
- Products with a positive `substitution_factor` and a non-zero `allocation_factor` will
|
|
33
|
+
have their `allocation_factor` reset to 0.0 and will not be included in the allocation.
|
|
34
|
+
- Products with a non-positive `substitution_factor` are included in the allocation.
|
|
35
|
+
"""
|
|
36
|
+
# Ensure the process is a valid Process instance
|
|
37
|
+
if not isinstance(process, Process):
|
|
38
|
+
raise ValueError("Activity must be a Process instance")
|
|
39
|
+
|
|
40
|
+
# Return none if the process is not multifunctional
|
|
41
|
+
if not process.multifunctional:
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
# Collect products eligible for allocation (functions that are not subsituted)
|
|
45
|
+
products = []
|
|
46
|
+
for product in process.products():
|
|
47
|
+
if product.get("substitution_factor", 0) > 0 and product["allocation_factor"] > 0:
|
|
48
|
+
# Reset allocation factor for products with positive substitution factor
|
|
49
|
+
product["allocation_factor"] = 0.0
|
|
50
|
+
product.save()
|
|
51
|
+
elif product.get("substitution_factor", 0) <= 0:
|
|
52
|
+
# Include functions with non-positive substitution factor
|
|
53
|
+
products.append(product)
|
|
54
|
+
|
|
55
|
+
# Calculate the total value for allocation
|
|
56
|
+
total = sum([getter(product) for product in products])
|
|
57
|
+
|
|
58
|
+
# Raise an error if the total is zero to avoid division by zero
|
|
59
|
+
if not total:
|
|
60
|
+
raise ZeroDivisionError("Sum of allocation factors is zero")
|
|
61
|
+
|
|
62
|
+
# Calculate and assign allocation factors for each product
|
|
63
|
+
for i, product in enumerate(products):
|
|
64
|
+
factor = getter(product) / total
|
|
65
|
+
product["allocation_factor"] = factor
|
|
66
|
+
product.save()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def get_property_value(
|
|
70
|
+
product: Product,
|
|
71
|
+
property_label: str,
|
|
72
|
+
) -> float:
|
|
73
|
+
"""
|
|
74
|
+
Retrieve the value of a specified property from a given function.
|
|
75
|
+
|
|
76
|
+
This function extracts the value of a property identified by `property_label` from the
|
|
77
|
+
`properties` dictionary of the provided `Product` object. If the property is marked
|
|
78
|
+
as normalized, the value is calculated by multiplying the `amount` in the processing
|
|
79
|
+
edge with the `amount` of the property.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
product (Product): The product object from which the property value is retrieved.
|
|
83
|
+
Must be an instance of the `Product` class.
|
|
84
|
+
property_label (str): The label of the property to retrieve.
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
float: The value of the specified property.
|
|
88
|
+
|
|
89
|
+
Raises:
|
|
90
|
+
ValueError: If the provided `product` is not an instance of the `Product` class.
|
|
91
|
+
KeyError: If the `properties` dictionary is missing or the specified property
|
|
92
|
+
is not found in the `properties` dictionary.
|
|
93
|
+
|
|
94
|
+
Notes:
|
|
95
|
+
- If the property is stored as a float (legacy format), a warning is logged.
|
|
96
|
+
- If the property is normalized, the value is calculated as:
|
|
97
|
+
`product.processing_edge["amount"] * prop["amount"]`.
|
|
98
|
+
"""
|
|
99
|
+
if not isinstance(product, Product):
|
|
100
|
+
raise ValueError("Passed non-function for allocation")
|
|
101
|
+
|
|
102
|
+
props = product.get("properties")
|
|
103
|
+
|
|
104
|
+
if not props:
|
|
105
|
+
raise KeyError(f"Product {product} from process {product.processor} doesn't have properties")
|
|
106
|
+
|
|
107
|
+
prop = props.get(property_label)
|
|
108
|
+
|
|
109
|
+
if not prop:
|
|
110
|
+
raise KeyError(f"Product {product} from {product.processor} missing property {property_label}")
|
|
111
|
+
|
|
112
|
+
if isinstance(prop, float):
|
|
113
|
+
log.warning("Property using legacy float format")
|
|
114
|
+
return prop
|
|
115
|
+
|
|
116
|
+
if prop.get("normalize", False):
|
|
117
|
+
return abs(product.processing_edge["amount"]) * prop["amount"]
|
|
118
|
+
else:
|
|
119
|
+
return prop["amount"]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def property_allocation(property_label: str) -> Callable:
|
|
123
|
+
"""
|
|
124
|
+
Create a partial function for allocating a process based on a specific property.
|
|
125
|
+
|
|
126
|
+
This function generates a callable that performs allocation for a multifunctional process
|
|
127
|
+
using a getter function that retrieves the value of the specified property.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
property_label (str): The label of the property to be used for allocation.
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
Callable: A partial function that performs allocation using the specified property.
|
|
134
|
+
"""
|
|
135
|
+
getter = partial(get_property_value, property_label=property_label)
|
|
136
|
+
return partial(generic_allocation, getter=getter)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
allocation_strategies = {
|
|
140
|
+
"equal": partial(generic_allocation, getter=lambda x: 1.0),
|
|
141
|
+
"manual": partial(generic_allocation, getter=lambda x: x.get("allocation_factor", 1)),
|
|
142
|
+
}
|