Skip to content

Commit

Permalink
Use user function in LCA computation
Browse files Browse the repository at this point in the history
  • Loading branch information
gschwind committed Jun 21, 2023
1 parent 9aa1b13 commit 35b444a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
3 changes: 2 additions & 1 deletion lca_algebraic/base_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ def _getAmountOrFormula(ex: ExchangeDataset) -> Union[Basic, float]:
""" Return either a fixed float value or an expression for the amount of this exchange"""
if 'formula' in ex:
try:
return parse_expr(ex['formula'])
local_dict = {x[0].name: x[0] for x in _user_functions.values()}
return parse_expr(ex['formula'], local_dict=local_dict)
except:
error("Error while parsing formula '%s' : backing to amount" % ex['formula'])

Expand Down
17 changes: 14 additions & 3 deletions lca_algebraic/lca.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from pandas import DataFrame
from sympy import lambdify, simplify, Function
from sympy.printing.numpy import NumPyPrinter

from .base_utils import _actName, _getDb, _method_unit
from .base_utils import _getAmountOrFormula
Expand Down Expand Up @@ -137,6 +138,15 @@ def __init__(self, exprOrDict, expanded_params=None, params=None, sobols=None):
you can provide either the list pf expanded parameters (full vars for enums) for the 'user' param names
"""

printer = NumPyPrinter({
'fully_qualified_modules': False,
'inline': True,
'allow_unknown_functions': True,
'user_functions': { }
})

modules = [{x[0].name : x[1] for x in _user_functions.values()}, 'numpy']

if isinstance(exprOrDict, dict) :
# Come from JSON serialization
obj = exprOrDict
Expand All @@ -145,8 +155,9 @@ def __init__(self, exprOrDict, expanded_params=None, params=None, sobols=None):

# Full names
self.expanded_params = _expand_param_names(self.params)
self.expr = parse_expr(obj["expr"])
self.lambd = lambdify(self.expanded_params, self.expr, 'numpy')
local_dict = {x[0].name: x[0] for x in _user_functions.values()}
self.expr = parse_expr(obj["expr"], local_dict=local_dict)
self.lambd = lambdify(self.expanded_params, self.expr, modules, printer=printer)
self.sobols = obj["sobols"]

else :
Expand All @@ -158,7 +169,7 @@ def __init__(self, exprOrDict, expanded_params=None, params=None, sobols=None):
if self.params is None :
self.params = _expanded_names_to_names(expanded_params)

self.lambd = lambdify(expanded_params, exprOrDict, 'numpy')
self.lambd = lambdify(expanded_params, self.expr, modules, printer=printer)
self.expanded_params = expanded_params
self.sobols = sobols

Expand Down

0 comments on commit 35b444a

Please sign in to comment.