Inventory Prediction Manager

If you read the error message, it is giving you the clues you need to start debugging. What I read is on line 148 in the function linreg(), you have a divide by zero error. I see several places this could be an issue, but there is clearly nothing checking for having a 0 in the denominator of several lines of code. I also cannot pin point the issue as we don't have line numbers, so you should be able to go right to it. So the focus should be on debugging those, or adding code to handle these situations. Look at the "###### Check this line" in the code below.

You can see a situation where det=0 or meanerror=0 or N=2 that would all throw this error.

def linreg(X, Y):
    if len(X) != len(Y):  raise ValueError, 'unequal length'
    N = len(X)
    Sx = Sy = Sxx = Syy = Sxy = 0.0
    for x, y in map(None, X, Y):
        Sx = Sx + x
        Sy = Sy + y
        Sxx = Sxx + x*x
        Syy = Syy + y*y
        Sxy = Sxy + x*y
    det = Sxx * N - Sx * Sx
    a, b = (Sxy * N - Sy * Sx)/det, (Sxx * Sy - Sx * Sxy)/det   ###### Check this line
    meanerror = residual = float(0.0)
    for x, y in map(None, X, Y):
        meanerror = meanerror + (y - Sy/N)**2
        residual = residual + (y - a * x - b)**2
    RR = 1 - residual/meanerror   ###### Check this line
    ss = residual / (N-2)  ###### Check this line
    Var_a, Var_b = ss * N / det, ss * Sxx / det      ###### Check this line
    return a, b, RR	#y intercept, slope, risk ratio
    

While you are at it, I also see a possible error coming if you run this at a certain time (midnight) as well that needs handled appriopriately.

def randomInventoryDecrementation(tagPath):#for simulation
	#called from Simulator Trigger tag in UDT
	value = system.tag.readBlocking([tagPath])[0].value
	hour = system.date.getHour24(system.date.now())
	if hour<12:#prevent "running out" every morning
		hour = 24-hour
	randomNum = 0.500/float(hour)   ###### Check this line

	newValue = value-randomNum

	if newValue<0:
		newValue = 100.000
	
	res = system.tag.writeBlocking([tagPath],[newValue])
	return

Keep in mind, reusing of code is fine, but the original developer made some assumptions about it's use (when it would be run, like not at midnight, or that certain values would always be present) that you are running into at this point. This would be a good improvement on the code if the original poster could update, but this is what we as developers get to deal with. You can try to detect the 0 before you do the division, or use a try/except here to handle it.

2 Likes