from sympy import *
class Example:
def __init__(self):
self.data = {
'sensor1': 0,
'sensor2': 0,
'sensor3': 0
}
self.registry = {
'678985': {"data": [{"MID": "sensor1", "D": 50}]},
'123454': {"data": [{"MID": "sensor2", "D": 5}]},
'345609': {"data": [{"MID": "sensor3", "D": 500}]}
}
self.symbols = {sensor_id: symbols(sensor_id) for sensor_id in self.data.keys()}
def evaluate_expression(self, expression):
try:
for sensor_id, sensor_info in self.registry.items():
for modality in sensor_info["data"]:
m_id = modality["MID"]
data = modality["D"]
if m_id in self.data:
self.data[m_id] = data
expression = expression.replace('&&', 'and').replace('||', 'or').replace('!', 'not')
sympy_expr = sympify(expression, locals=self.symbols) #parsing
substitutions = {self.symbols[key]: value for key, value in self.data.items()}
substituted_expr = sympy_expr.subs(substitutions) #substituting the value from the registry
result = substituted_expr.simplify()
# result = bool(substituted_expr)
return result
except Exception as e:
raise ValueError(f"Failed to evaluate expression:{expression} as: {e}")
a = Example()
e = "sensor1 > 10 && sensor1 <= 100 && sensor2 == 2 || sensor3 < 1000 && sensor3 > 400"
a.evaluate_expression(e)
我发送了要通过此检查的表达式
sensor1> 10 && sensor1 <=100 && sensoe2 ==2 || sensor3 < 1000 && sensor3 > 400
我更改了符号并将其与
and, not, or
相关联,但它说无法确定关系的真值
您正在尝试解析此字符串:
s = 'sensor1 > 10 and sensor1 <= 100 and sensor2 == 2 or sensor3 < 1000 and sensor3 > 400'
使用
and
和 or
会强制进行布尔计算,这对于符号表达式来说会失败。使用 &
和 |
代替,也使用 Eq
而不是 ==
:
In [30]: s = '(sensor1 > 10) & (sensor1 <= 100) & Eq(sensor2, 2) | (sensor3 < 1000) & (sensor3 > 400)'
In [31]: parse_expr(s)
Out[31]: (sensor₃ > 400 ∧ sensor₃ < 1000) ∨ (sensor₂ = 2 ∧ sensor₁ ≤ 100 ∧ sensor₁ > 10)