I'm designing a program in Python to handle the calculation of key performance indicators (KPIs) for an industrial application. The results are calculated from raw process data, which in the program is stored in a NumPy matrix.
I wanted to keep the actual calculation procedures separate from the main program, which handles the other heavy lifting, like fetching the relevant raw data. There are multiple real-life "units" for which the KPIs can be calculated, so each of them has their own Python file containing the specific implementations of the KPIs. A for-loop in the main program module calculates all the KPIs for all the units in succession.
So what I do is as follows:
1) Import the calculation file for the unit under calculation this round:
print("Importing calculation module '{}.py'...".format(file_name))
try:
module = __import__(file_name)
except ImportError:
status = "Error: no plant file defined."
else:
print("Done.")
2) Pass the imported module to a function, which determines, which KPI function to call in the module:
def CalculateKPI(KPIToCalculate, raw_data, kpi_module):
status = ""
kpi_result = []
not_defined = "Error: Calculation method not defined for this KPI."
print("Calculating KPI values... ")
if(KPIToCalculate == "SupportFuelUsage"):
try:
kpi_result, status = kpi_module.SupportFuelUsage(raw_data)
except AttributeError:
status = not_defined
elif(KPIToCalculate == "Lambda"):
try:
kpi_result, status = kpi_module.Lambda(raw_data)
except AttributeError:
status = not_defined
elif(KPIToCalculate == "PrimaryAirRatio"):
try:
kpi_result, status = kpi_module.PrimaryAirRatio(raw_data)
except AttributeError:
status = not_defined
... As many ELIF forks as there are possible KPIs, close to 200
else:
status = "Error: Function CalculateKPI does not contain if-statement for this KPI."
return kpi_result, status
print("Done.")
return kpi_result, status
It does work. However, this seems like a very bulky and crude way of doing this, and in the long term will likely be a nightmare to manage.
So basically, what I'm asking is: is there any way of determining the function to call in the module based on the variable "KPIToCalculate" alone, and not have to list each possible function separately?