2021-10-03 13:36:35 +00:00
|
|
|
from ..API.expression import Expression
|
2021-10-06 14:17:50 +00:00
|
|
|
from .core.random_tree import RandomTree
|
2021-10-03 13:36:35 +00:00
|
|
|
|
2021-10-06 14:17:50 +00:00
|
|
|
DEFAUTL_CONFIG = {
|
2021-10-09 04:30:38 +00:00
|
|
|
"rejected": [0, 1],
|
|
|
|
"min_max": (-10, 10),
|
|
|
|
}
|
2021-10-03 13:36:35 +00:00
|
|
|
|
2021-10-09 04:30:38 +00:00
|
|
|
|
|
|
|
def expression_generator(
|
|
|
|
template: str,
|
|
|
|
conditions: list[str] = [],
|
|
|
|
global_config: dict = {},
|
|
|
|
configs: dict = {},
|
|
|
|
):
|
|
|
|
"""Generate a random expression
|
2021-10-03 13:36:35 +00:00
|
|
|
|
|
|
|
:param template: the template of the expression
|
|
|
|
:param conditions: conditions on randomly generate variable
|
2021-10-06 14:17:50 +00:00
|
|
|
:param global_config: configuration for all variables
|
|
|
|
:param configs: configuration for each variables
|
|
|
|
:return: Expression or Token generated
|
2021-10-03 13:36:35 +00:00
|
|
|
|
|
|
|
:example:
|
2021-10-06 14:17:50 +00:00
|
|
|
>>> e = expression_generator("{a}/{a*k}")
|
2021-10-03 13:36:35 +00:00
|
|
|
>>> e # doctest: +SKIP
|
|
|
|
<Exp: -3 / -15>
|
2021-10-06 14:17:50 +00:00
|
|
|
>>> e = expression_generator("{a}/{a*k} - 3*{b}", configs={'a':{'min_max':(10, 30)}})
|
2021-10-03 13:36:35 +00:00
|
|
|
>>> e # doctest: +SKIP
|
|
|
|
<Exp: 18 / 108 - 3 * 9>
|
2021-10-06 14:17:50 +00:00
|
|
|
>>> e = expression_generator("{a}*x + {b}*x + 3", conditions=["a>b"], global_config={"rejected":[0, 1]})
|
2021-10-03 13:36:35 +00:00
|
|
|
>>> print(e) # doctest: +SKIP
|
|
|
|
10x - 6x + 3
|
2021-10-06 14:17:50 +00:00
|
|
|
>>> ee = e.simplify()
|
2021-10-03 13:36:35 +00:00
|
|
|
>>> print(ee) # doctest: +SKIP
|
|
|
|
4x + 3
|
|
|
|
|
|
|
|
"""
|
2021-10-06 14:17:50 +00:00
|
|
|
rd_tree = RandomTree.from_str(template)
|
2021-10-09 04:30:38 +00:00
|
|
|
generated_tree = rd_tree.generate(
|
|
|
|
conditions, dict(DEFAUTL_CONFIG, **global_config), configs
|
|
|
|
)
|
2021-10-06 14:17:50 +00:00
|
|
|
return Expression._post_processing(generated_tree)
|