para-gsa 0.1.0__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.
@@ -0,0 +1,59 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ *.egg-info/
7
+ dist/
8
+ build/
9
+ *.egg
10
+
11
+ # Virtual environments
12
+ .venv/
13
+ venv/
14
+ env/
15
+
16
+ # Jupyter
17
+ .ipynb_checkpoints/
18
+
19
+ # IDE
20
+ .vscode/
21
+ .idea/
22
+ *.swp
23
+ *.swo
24
+ *~
25
+
26
+ # OS
27
+ .DS_Store
28
+ Thumbs.db
29
+ Desktop.ini
30
+
31
+ # Project-specific
32
+ *.pkl
33
+ *.log
34
+ results/*/*.xlsx
35
+ results/*/*.pkl
36
+ results/*/*.csv
37
+ !results/*/.gitkeep
38
+ !results/README.md
39
+
40
+ # User-provided data (not tracked in git)
41
+ data/
42
+
43
+ # WorkBuddy / tool configs
44
+ .workbuddy/
45
+
46
+ # Temp / debug outputs
47
+ quick_out.txt
48
+ quick_err.txt
49
+ test_output.txt
50
+ test_result.txt
51
+ test_result_err.txt
52
+ test_stderr.txt
53
+ test_stdout.txt
54
+ test_full_result.txt
55
+ test_full_result_err.txt
56
+ test_sobol_result.txt
57
+ spsolve_result.txt
58
+ sobol_debug.txt
59
+ init_db.log
para_gsa-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,429 @@
1
+ Metadata-Version: 2.5
2
+ Name: para-gsa
3
+ Version: 0.1.0
4
+ Summary: Parameter-perturbation life cycle assessment (LCA) and global sensitivity analysis (GSA) with Brightway 2.5 and SALib
5
+ Project-URL: Homepage, https://github.com/lucas-sys/para_gsa
6
+ Project-URL: Repository, https://github.com/lucas-sys/para_gsa
7
+ Project-URL: Issues, https://github.com/lucas-sys/para_gsa/issues
8
+ Project-URL: Changelog, https://github.com/lucas-sys/para_gsa/commits/main
9
+ Author: Nanlin Liao, Rebecca Belfiore, Christhel Andrade Diaz, Weier Liu
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: Brightway,FAST,LCA,Monte Carlo,SALib,Sobol,global sensitivity analysis,life cycle assessment,sensitivity analysis,uncertainty analysis
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: asteval>=0.9.6
24
+ Requires-Dist: bw2analyzer>=0.11.8
25
+ Requires-Dist: bw2calc<3,>=2.0
26
+ Requires-Dist: bw2data<5,>=4.0
27
+ Requires-Dist: numpy>=1.24
28
+ Requires-Dist: pandas>=2.0
29
+ Requires-Dist: salib<2,>=1.4
30
+ Requires-Dist: scipy>=1.10
31
+ Provides-Extra: dev
32
+ Requires-Dist: build>=1.2; extra == 'dev'
33
+ Requires-Dist: pytest>=8.0; extra == 'dev'
34
+ Requires-Dist: twine>=5.0; extra == 'dev'
35
+ Provides-Extra: io
36
+ Requires-Dist: bw2io>=0.9; extra == 'io'
37
+ Description-Content-Type: text/markdown
38
+
39
+ ## Contributors
40
+
41
+ <a href="https://github.com/lucas-sys/para_gsa/graphs/contributors">
42
+ <img src="https://img.shields.io/github/contributors/lucas-sys/para_gsa?style=for-the-badge&logo=github" alt="Contributors"/>
43
+ </a>
44
+
45
+ <a href="https://github.com/lucas-sys/para_gsa/graphs/contributors">
46
+ <img src="https://contrib.rocks/image?repo=lucas-sys/para_gsa" alt="Contributors"/>
47
+ </a>
48
+
49
+
50
+
51
+ # LCA Global Sensitivity Analysis (GSA) Toolkit
52
+
53
+ A modular Python toolkit for performing **parameter-perturbation Life Cycle Assessment (LCA)** with **Global Sensitivity Analysis (GSA)**, built on [Brightway2.5](https://brightway.dev/), [SALib](https://salib.readthedocs.io/), and Python multiprocessing.
54
+
55
+ This toolkit was developed in collaboration by Rebecca Belfiore, Christhel Andrade Diaz, Weier Liu and Nanlin Liao. Code X was used to improve the code efficiency, and WorkBuddy was used to organize all files.
56
+
57
+ ## Features
58
+
59
+ - **Deterministic LCA** -- Compute baseline environmental impact scores across multiple functional units and impact categories
60
+ - **Contribution Analysis** -- Recursive Tier-2 contribution analysis to identify key process contributions
61
+ - **Formula Validation** -- Verify stored exchange amounts against parameterized formulas
62
+ - **OAT Sensitivity** -- One-at-a-time finite-difference sensitivity analysis with elasticity coefficients
63
+ - **Analytical Variance** -- Variance decomposition from uncertainty metadata (13 distribution types)
64
+ - **Monte Carlo Simulation** -- Parallel stochastic sampling with configurable worker count
65
+ - **Sobol GSA** -- First-order (S1) and total-order (ST) Sobol indices via SALib with parallel evaluation
66
+ - **FAST / RBD-FAST GSA** -- Global sensitivity analysis via Fourier Amplitude Sensitivity Test (FAST) and its Random Balance Designs variant (RBD-FAST), with parallel evaluation
67
+ - **Background Uncertainty (BG)** -- Optionally combine foreground parameter uncertainty with background-database uncertainty (Brightway `use_distributions=True`) for Monte Carlo, Sobol, and FAST / RBD-FAST
68
+
69
+ ## Project Structure
70
+
71
+ ```
72
+ .
73
+ ├── para_gsa/ # Core LCA modules
74
+ │ ├── __init__.py # Public API re-exports
75
+ │ ├── lca_config.py # Configuration, logging, Timer, LCASetup
76
+ │ ├── lca_project_setup.py # Brightway project init, MultiLCA
77
+ │ ├── lca_parameters.py # Parameter queries, formula resolution
78
+ │ ├── lca_matrices.py # Sparse matrix update utilities
79
+ │ ├── lca_contribution.py # Contribution analysis, OAT, analytical variance
80
+ │ ├── lca_monte_carlo.py # Monte Carlo sampling & parallel evaluation
81
+ │ ├── lca_sobol.py # Sobol GSA (build, sample, evaluate, analyze)
82
+ │ ├── lca_fast.py # FAST / RBD-FAST GSA (build, sample, evaluate, analyze)
83
+ │ └── lca_gsa_helper.py # Backward-compatible re-export layer
84
+ ├── data/ # Input databases (user-provided)
85
+ │ └── ... # Place your Excel database files here
86
+ ├── results/ # Output files (organized by analysis type)
87
+ │ ├── deterministic/ # Deterministic LCA results
88
+ │ ├── contribution/ # Contribution analysis results
89
+ │ ├── sensitivity_oat/ # OAT sensitivity results
90
+ │ ├── sensitivity_analytical/ # Analytical variance results
91
+ │ ├── monte_carlo/ # Monte Carlo results
92
+ │ ├── sobol/ # Sobol GSA results
93
+ │ └── fast/ # FAST / RBD-FAST GSA results
94
+ ├── gsa_workflow.ipynb # Interactive notebook (full workflow)
95
+ ├── init_databases.py # Database initialization script
96
+ ├── test_full_workflow.py # End-to-end test
97
+ ├── test_run.py # Quick validation test
98
+ ├── test_sobol_only.py # Sobol-only test
99
+ ├── requirements.txt
100
+ ├── LICENSE
101
+ └── README.md
102
+ ```
103
+
104
+ ## Prerequisites
105
+
106
+ - Python >= 3.10
107
+ - [Brightway2.5](https://brightway.dev/) (`bw2data`, `bw2calc`, `bw2analyzer`; `bw2io` only for the database-initialization helper)
108
+ - An ecoinvent database (requires ecoinvent license)
109
+
110
+ ## Installation
111
+
112
+ ### From PyPI
113
+
114
+ ```bash
115
+ pip install para-gsa
116
+ ```
117
+
118
+ The runtime dependencies (Brightway 2.5, SALib, NumPy, SciPy, pandas, asteval) are
119
+ installed automatically. You still need your own Brightway project and, for
120
+ background data, an ecoinvent licence.
121
+
122
+ To also install the helper used to import ecoinvent / custom databases:
123
+
124
+ ```bash
125
+ pip install "para-gsa[io]"
126
+ ```
127
+
128
+ Verify the install:
129
+
130
+ ```bash
131
+ python -c "import para_gsa; print(para_gsa.__version__)"
132
+ ```
133
+
134
+ ### From source (development)
135
+
136
+ ```bash
137
+ git clone https://github.com/lucas-sys/para_gsa.git
138
+ cd para_gsa
139
+ pip install -e ".[dev]"
140
+ ```
141
+
142
+ ### Conda environment
143
+
144
+ ```bash
145
+ conda create -n bw25 python=3.10
146
+ conda activate bw25
147
+ pip install para-gsa
148
+ ```
149
+
150
+ ## Configuration
151
+
152
+ Before running any analysis, you need to configure the following parameters:
153
+
154
+ | Parameter | Description | Where to set |
155
+ | ----------------------------- | ---------------------------------------------- | -------------------------------------------- |
156
+ | `PROJECT_NAME` | Your Brightway project name | `init_databases.py`, test scripts, notebook |
157
+ | `FOREGROUND_DB` | Name of your foreground database | Test scripts, notebook |
158
+ | `GROUP_NAME` | ActivityParameter group name | Test scripts, notebook |
159
+ | `FU_CODE` | Activity code for the functional unit | Test scripts, notebook |
160
+ | `METHODS` | List of impact method tuples | Test scripts, notebook |
161
+ | `ECOINVENT_USERNAME/PASSWORD` | ecoinvent credentials | `init_databases.py` or environment variables |
162
+ | `CUSTOM_DATABASES` | List of (db_name, xlsx_path, match_dbs) tuples | `init_databases.py` |
163
+
164
+ All parameters use `your_*` placeholders in the template files. Replace them with your actual values before running.
165
+
166
+ ## Database Initialization
167
+
168
+ ```bash
169
+ # Set ecoinvent credentials (recommended: use environment variables)
170
+ export ECOINVENT_USERNAME="your_username"
171
+ export ECOINVENT_PASSWORD="your_password"
172
+
173
+ # Or edit init_databases.py directly and update the configuration section
174
+
175
+ # Run the initialization script
176
+ python init_databases.py
177
+ ```
178
+
179
+ Place your custom database Excel files in the `data/` directory and add entries to the `CUSTOM_DATABASES` list in `init_databases.py`.
180
+
181
+ ## Quick Start
182
+
183
+ ### In Python
184
+
185
+ ```python
186
+ from para_gsa import (
187
+ set_project, initialize_multilca, deterministic_lca,
188
+ oat_sensitivity, run_parallel_monte_carlo,
189
+ build_sobol_problem, generate_sobol_samples,
190
+ run_parallel_sobol_from_samples, sobol_indices_from_results,
191
+ )
192
+
193
+ import bw2data as bd
194
+
195
+ # Setup
196
+ PROJECT_NAME = 'your_project_name'
197
+ FOREGROUND_DB = 'your_foreground_db'
198
+ GROUP_NAME = 'your_parameter_group'
199
+
200
+ set_project(PROJECT_NAME)
201
+ db = bd.Database(FOREGROUND_DB)
202
+ fu = [db.get(code='your_fu_code')]
203
+
204
+ methods = [
205
+ ('your_ecoinvent_db', 'EF v3.1', 'climate change',
206
+ 'global warming potential (GWP100)'),
207
+ ]
208
+
209
+ # Deterministic LCA
210
+ df = deterministic_lca(fu, methods)
211
+
212
+ # Monte Carlo (1000 iterations, 2 workers)
213
+ mc_results = run_parallel_monte_carlo(
214
+ project_name=PROJECT_NAME,
215
+ group_name=GROUP_NAME,
216
+ functional_units=fu,
217
+ methods=methods,
218
+ n_samples=1000,
219
+ n_workers=2,
220
+ )
221
+
222
+ # Sobol GSA
223
+ problem, params = build_sobol_problem(GROUP_NAME)
224
+ samples = generate_sobol_samples(problem, N=512)
225
+ sobol_results = run_parallel_sobol_from_samples(
226
+ project_name=PROJECT_NAME,
227
+ group_name=GROUP_NAME,
228
+ functional_units=fu,
229
+ methods=methods,
230
+ sobol_problem=problem,
231
+ sobol_samples=samples,
232
+ n_workers=2,
233
+ )
234
+
235
+ # FAST / RBD-FAST GSA
236
+ from para_gsa import lca_fast
237
+
238
+ fast_problem, fast_params = lca_fast.build_fast_problem(GROUP_NAME)
239
+
240
+ # --- Classic FAST (S1 only, fewer samples) ---
241
+ fast_samples = lca_fast.generate_fast_samples(fast_problem, M=4, method='fast')
242
+ fast_results = lca_fast.run_parallel_fast_from_samples(
243
+ project_name=PROJECT_NAME,
244
+ group_name=GROUP_NAME,
245
+ functional_units=fu,
246
+ methods=methods,
247
+ fast_problem=fast_problem,
248
+ fast_samples=fast_samples,
249
+ n_workers=2,
250
+ )
251
+ Si_fast = lca_fast.fast_indices_from_results(
252
+ fast_problem=fast_problem,
253
+ fast_results_df=fast_results,
254
+ functional_unit=fu[0]['name'],
255
+ method=methods[0],
256
+ fast_samples=fast_samples,
257
+ M=4,
258
+ analysis_method='fast',
259
+ )
260
+ df_fast = lca_fast.fast_indices_to_dataframe(Si_fast, fast_problem, analysis_method='fast')
261
+
262
+ # --- RBD-FAST (S1 + ST) ---
263
+ rbd_samples = lca_fast.generate_fast_samples(fast_problem, M=4, method='rbd_fast', seed=42)
264
+ rbd_results = lca_fast.run_parallel_fast_from_samples(
265
+ project_name=PROJECT_NAME,
266
+ group_name=GROUP_NAME,
267
+ functional_units=fu,
268
+ methods=methods,
269
+ fast_problem=fast_problem,
270
+ fast_samples=rbd_samples,
271
+ n_workers=2,
272
+ )
273
+ Si_rbd = lca_fast.fast_indices_from_results(
274
+ fast_problem=fast_problem,
275
+ fast_results_df=rbd_results,
276
+ functional_unit=fu[0]['name'],
277
+ method=methods[0],
278
+ fast_samples=rbd_samples,
279
+ M=4,
280
+ analysis_method='rbd_fast',
281
+ )
282
+ df_rbd = lca_fast.fast_indices_to_dataframe(Si_rbd, fast_problem, analysis_method='rbd_fast')
283
+
284
+ # One-click workflow
285
+ result = lca_fast.run_full_fast_workflow(
286
+ project_name=PROJECT_NAME,
287
+ group_name=GROUP_NAME,
288
+ functional_units=fu,
289
+ methods=methods,
290
+ M=4,
291
+ n_workers=2,
292
+ method='rbd_fast', # or 'fast'
293
+ )
294
+ ```
295
+
296
+ ### In Jupyter Notebook
297
+
298
+ Open `gsa_workflow.ipynb` and run cells sequentially. The notebook covers the complete workflow from database setup through Sobol and FAST GSA. Before running, update the configuration cells with your project-specific values.
299
+
300
+ ## Workflow Sections
301
+
302
+ | Section | Description | Output Directory |
303
+ | ------- | ------------------------- | --------------------------------- |
304
+ | 0 | Brightway project setup | -- |
305
+ | 1 | Impact method selection | -- |
306
+ | 2 | Functional unit selection | -- |
307
+ | 3 | Deterministic LCA | `results/deterministic/` |
308
+ | 4 | Contribution analysis | `results/contribution/` |
309
+ | 5 | OAT sensitivity | `results/sensitivity_oat/` |
310
+ | 6 | Analytical variance | `results/sensitivity_analytical/` |
311
+ | 7 | Monte Carlo simulation | `results/monte_carlo/` |
312
+ | 8 | Sobol GSA | `results/sobol/` |
313
+ | 10 | FAST / RBD-FAST GSA | `results/fast/` |
314
+
315
+ ## Supported Uncertainty Distributions
316
+
317
+ | Code | Distribution | Parameters |
318
+ | ---- | ---------------- | ---------------------------------------- |
319
+ | 0, 1 | No uncertainty | -- |
320
+ | 2 | Lognormal | loc (ln_mean), scale (ln_std) |
321
+ | 3 | Normal | loc (mean), scale (std) |
322
+ | 4 | Uniform | minimum, maximum |
323
+ | 5 | Triangular | minimum, maximum, loc (mode) |
324
+ | 6 | Bernoulli | loc (probability) |
325
+ | 7 | Discrete uniform | minimum, maximum |
326
+ | 8 | Weibull | shape, loc, scale |
327
+ | 9 | Gamma | shape (alpha), loc, scale |
328
+ | 10 | Beta | shape (alpha), shape2 (beta), loc, scale |
329
+ | 11 | Gumbel (GEV) | shape (xi), loc, scale |
330
+ | 12 | Student-t | shape (df), loc, scale |
331
+
332
+ ## FAST / RBD-FAST GSA
333
+
334
+ | Variant | Function | Indices | Sample size formula | Notes |
335
+ | --------- | ------------------- | ------- | ------------------- | ---------------------------------------- |
336
+ | Classic FAST | `method='fast'` | S1 | `(4M²+1)·k` | Deterministic, first-order only, low sample cost |
337
+ | RBD-FAST | `method='rbd_fast'` | S1 + ST | `≥65·k` | Random, first + total order, Latin hypercube sampling |
338
+
339
+ where `k` = number of uncertain parameters, `M` = interference factor (recommended default: 4).
340
+
341
+ **Comparison with Sobol**
342
+
343
+ | Method | S1 | ST | Min. recommended samples | When to use |
344
+ | ------------ | --- | --- | ------------------------ | --------------------------------- |
345
+ | Sobol | ✓ | ✓ | `N·(k+2)` | Standard full GSA |
346
+ | Classic FAST | ✓ | ✗ | `(4M²+1)·k` | S1 only, tight sample budget |
347
+ | RBD-FAST | ✓ | ✓ | `65·k` | S1 + ST at lower cost than Sobol |
348
+
349
+ Key API:
350
+
351
+ | Function | Description |
352
+ | ----------------------------------------------- | -------------------------------------------------- |
353
+ | `build_fast_problem(group)` | Build SALib problem dict from ActivityParameters |
354
+ | `sanitize_fast_problem(problem)` | Validate and repair invalid parameter bounds |
355
+ | `generate_fast_samples(problem, M, method)` | Generate FAST / RBD-FAST sample matrix |
356
+ | `expected_fast_sample_rows(problem, M, method)` | Predict number of sample rows |
357
+ | `run_parallel_fast_from_samples(...)` | Evaluate sample matrix with multiple workers |
358
+ | `fast_indices_from_results(...)` | Compute FAST / RBD-FAST sensitivity indices |
359
+ | `fast_indices_to_dataframe(Si, problem)` | Convert indices to a tidy DataFrame |
360
+ | `run_full_fast_workflow(...)` | One-click workflow (build → sample → evaluate) |
361
+
362
+ ## Background Uncertainty (BG)
363
+
364
+ By default the GSA only perturbs the **foreground** ActivityParameters while the
365
+ background database (e.g. ecoinvent) stays at its deterministic values. Passing
366
+ `include_background=True` combines every parameter sample with one independent
367
+ draw of the **background** database uncertainty, so both uncertainty sources are
368
+ propagated together.
369
+
370
+ ```python
371
+ # Monte Carlo with background uncertainty
372
+ mc_bg = run_parallel_monte_carlo(
373
+ project_name=PROJECT_NAME,
374
+ group_name=GROUP_NAME,
375
+ functional_units=fu,
376
+ methods=methods,
377
+ n_samples=1000,
378
+ include_background=True,
379
+ )
380
+
381
+ # Sobol with background uncertainty
382
+ sobol_bg = run_parallel_sobol_from_samples(
383
+ project_name=PROJECT_NAME,
384
+ group_name=GROUP_NAME,
385
+ functional_units=fu,
386
+ methods=methods,
387
+ sobol_problem=problem,
388
+ sobol_samples=samples,
389
+ include_background=True,
390
+ )
391
+
392
+ # FAST / RBD-FAST with background uncertainty
393
+ fast_bg = lca_fast.run_parallel_fast_from_samples(
394
+ project_name=PROJECT_NAME,
395
+ group_name=GROUP_NAME,
396
+ functional_units=fu,
397
+ methods=methods,
398
+ fast_problem=fast_problem,
399
+ fast_samples=fast_samples,
400
+ include_background=True,
401
+ )
402
+ ```
403
+
404
+ Implementation notes:
405
+
406
+ - Each worker builds an additional `MultiLCA(..., use_distributions=True)`
407
+ instance and advances it by exactly one draw per sample.
408
+ - Parameterized foreground cells are masked out of the background draw
409
+ (`_prepare_bg_data_objs`), otherwise the foreground perturbation would be
410
+ counted twice (once by the background sampler, once by the delta overlay).
411
+ - The foreground perturbation is applied as a cell-wise **delta** on top of the
412
+ background-sampled matrices (`compute_param_delta` /
413
+ `apply_param_delta_to_matrices`), so only one LCI/LCIA round is needed per sample.
414
+ - Cost: background runs are slower and use more memory per worker, because an
415
+ extra distribution-sampling MultiLCA must be kept in memory.
416
+
417
+ ## Multiprocessing
418
+
419
+ Monte Carlo, Sobol, and FAST evaluations all use Python's `spawn` multiprocessing context to ensure Windows compatibility. Each worker process independently loads the Brightway project and databases, so memory usage scales with the number of workers. 2–4 workers are recommended.
420
+
421
+ ## License
422
+
423
+ This project is released under the MIT License. See [LICENSE](LICENSE) for details.
424
+
425
+ ## Acknowledgments
426
+
427
+ - [Brightway2.5](https://brightway.dev/) -- LCA framework
428
+ - [SALib](https://salib.readthedocs.io/) -- Sensitivity Analysis Library
429
+ - [ecoinvent](https://ecoinvent.org/) -- Life cycle inventory database