execute.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import re
  2. import numpy as np
  3. import pandas as pd
  4. def execute_constrains(data:pd.DataFrame,cst:str) -> np.ndarray:
  5. #######################################################################################
  6. # 以下函数用于execute_constrains中使用 #
  7. #######################################################################################
  8. def threshold_min(*data,threshold):
  9. # 原数据中,所有大于threshold的数的最小值
  10. data = np.column_stack(data)
  11. data_rm = np.where(data<=threshold,np.nan,data)
  12. data_min = np.nanmin(data_rm,axis=1)
  13. data_min = np.where(np.isnan(data_min),threshold,data_min)
  14. return data_min
  15. def max(*data):
  16. return np.max(data,axis=0)
  17. #######################################################################################
  18. #######################################################################################
  19. mod_vars = re.findall(r'{(\w+)}',cst)
  20. if len(mod_vars) > 0:
  21. for var in mod_vars:
  22. cst = cst.replace('{'+var+'}',f'data.{var}')
  23. try:
  24. cv = eval(cst)
  25. except Exception as E:
  26. print(f'执行该约束时有误:{cst},以下为输入的数据')
  27. with pd.option_context('display.max_columns', None):
  28. print(data)
  29. raise E
  30. cv = np.array(cv)
  31. else:
  32. cv = data.eval(cst).to_numpy()
  33. cv = cv.reshape(-1,1)
  34. return cv
  35. if __name__ == '__main__':
  36. res1 = execute_constrains(
  37. pd.DataFrame({'x':[1,2,3],'y':[4,5,6]}),
  38. cst='abs(x-y)'
  39. )
  40. print(res1)