PascalLesage / presamples

Package to write, load, manage and verify numerical arrays, called presamples.
BSD 3-Clause "New" or "Revised" License
14 stars 11 forks source link

One-off issue in MonteCarloLCA with presamples #47

Closed PascalLesage closed 6 years ago

PascalLesage commented 6 years ago

Suppose I have a simple system with the technosphere matrix defined as: image

I create a presample package like this:

>>> arr = np.array([10, 20, 30, 40, 50]).reshape(1, -1)
>>> _, fp = create_presamples_package(
...    [
...        (arr, 
...         [(('db', 'B'), ('db', 'A'), 'technosphere')], 
...         'technosphere')
...    ], seed='sequential'
... )

I use seed='sequential' because I then want to calculate the correlation between this specific technosphere exchange and results.
Because of the way MonteCarloLCA  objects are usually manipulated, I end up including the second sample (index=1) first:

>>> mc = MonteCarloLCA({a:1}, presamples=[fp])
>>> for i in range(5):
...        next(mc)
...        print(mc.technosphere_matrix[mc.product_dict[('db', 'B')], mc.activity_dict[('db', 'A')]])
-20.0
-30.0
-40.0
-50.0
-10.0

To get what I really need, I have to do this:

>>> mc = MonteCarloLCA({a:1}, presamples=[fp])
>>> mc.lci()
>>> for i in range(5):
...    if i == 0:
...        pass
...    else:
...        next(mc)
...    print(mc.technosphere_matrix[mc.product_dict[('db', 'B')], mc.activity_dict[('db', 'A')]])
-10.0
-20.0
-30.0
-40.0
-50.0

The example on the GSA example notebook shows how to build up the arrays during Monte Carlo, but if the seed is sequential, this shouldn't be necessary: one simply needs to go in an read the presample array.

One simple solution would be to change the way the Indexer is instantiated, from:

self.seed_value, self.count, self.index = seed, 0, None

to:

self.seed_value, self.count, self.index = seed, -1, None

This generates the expected results:

```python
>>> mc = MonteCarloLCA({a:1}, presamples=[fp])
>>> for i in range(5):
...        next(mc)
...        print(mc.technosphere_matrix[mc.product_dict[('db', 'B')], mc.activity_dict[('db', 'A')]])
-10.0
-20.0
-30.0
-40.0
-50.0
PascalLesage commented 6 years ago

@cmutel I checked the behavior for LCA with Indexer.__init__ starting at -1. It behaves as hoped for:


>>>_, fp = create_presamples_package(
...     [
...          (np.array([42]).reshape(1, -1), 
...          [(('db', 'B'), ('db', 'A'), 'technosphere')], 
...          'technosphere')
...     ], seed='sequential'
...    )
... lca = LCA({a:1}, presamples=[fp])
... lca.lci()
... print(lca.technosphere_matrix[lca.product_dict[('db', 'B')], lca.activity_dict[('db', 'A')]])

-42