def interpolateFromPdfSamples(pdfSamples, x):
xSamples = sorted([i[0] for i in pdfSamples])
if((x<= max(xSamples))and(x >= min(xSamples))):
if(x in xSamples):
## we have an exact match, so we can just return the exact p
## value that was sampled at this point
for xySample in pdfSamples:
if(xySample[0] == x):
return xySample[1]
else:
## the x value we want to sample the probability of falls in
## the range of x values that we have a p value for, so we
## linearly interpolate between the two closest pairs of
## values in x
below = [xySample for xySample in pdfSamples if (xySample[0] < x)]
above = [xySample for xySample in pdfSamples if (xySample[0] > x)]
ptBelow = [xySample for xySample in below if (xySample[0] == max([pt[0] for pt in below]))]
ptBelow =[item for sublist in ptBelow for item in sublist]
ptAbove = [xySample for xySample in above if (xySample[0] == min([pt[0] for pt in above]))]
ptAbove =[item for sublist in ptAbove for item in sublist]
m = (ptAbove[1]-ptBelow[1])/(ptAbove[0]-ptBelow[0])
## calculate slope in this interval
output = ptBelow[1] + m*(x- ptBelow[0])
return output
else:
## the x point in question is beyond the margins that we sampled
## from the pdf, so we linearly interpolate based on the last
## two endpoints
if(x > max(xSamples)):
secondBiggestX = min(heapq.nlargest(2, xSamples))
largest = [xySample for xySample in pdfSamples if (xySample[0] > secondBiggestX)]
largest = [item for sublist in largest for item in sublist]
secondLargest = [xySample for xySample in pdfSamples if (xySample[0] == secondBiggestX)]
secondLargest = [item for sublist in secondLargest for item in sublist]
m = (largest[1]-secondLargest[1])/(largest[0]-secondLargest[0])
## calculate slope in this interval
output = largest[1] + m*(x- largest[0])
elif(x < min(xSamples)):
secondSmallestX = max(heapq.nsmallest(2, xSamples))
smallest = [xySample for xySample in pdfSamples if (xySample[0] < secondSmallestX)]
smallest = [item for sublist in smallest for item in sublist]
secondSmallest = [xySample for xySample in pdfSamples if (xySample[0] == secondSmallestX)]
secondSmallest = [item for sublist in secondSmallest for item in sublist]
m = (secondSmallest[1]-smallest[1])/(secondSmallest[0]-smallest[0])
## calculate slope in this interval
output = smallest[1] + m*(x- smallest[0])
return output
评论列表
文章目录