def bilinear_interp(x1, x2, y1, y2, x, y, q11, q12, q21, q22):
    """
    Perform a bilinear interpolation at the point x,y from the rectangular grid 
    defined by x1,y1 and x2,y2 with values at the four corners equal to Q11, Q12, 
    Q21 and Q22.
    """

    assert x1 <= x <= x2
    assert y1 <= y <= y2
    assert x2 > x1
    assert y2 > y1
    assert q11 is not None and q12 is not None and q21 is not None and q22 is not None

    val = q11 * (x2 - x) * (y2 - y)
    val += q21 * (x - x1) * (y2 - y)
    val += q12 * (x2 - x) * (y - y1)
    val += q22 * (x - x1) * (y - y1)
    val /= (x2 - x1) * (y2 - y1)

    assert val <= 0.0001 + max([q11, q12, q21, q22]), \
        str(val) + ' ' + str(q11) + ' ' + str(q12) + ' ' + str(q21) + ' ' + str(q22)
    assert val >= -0.0001 + min([q11, q12, q21, q22]), \
        str(val) + ' ' + str(q11) + ' ' + str(q12) + ' ' + str(q21) + ' ' + str(q22)
    return val