def jenks(data, num_breaks):
    """
    Calculate Jenks natural breaks.

    Adapted from http://danieljlewis.org/files/2010/06/Jenks.pdf
    Credit: Daniel Lewis

    Arguments:
    data -- Array of values to classify.
    num_breaks -- Number of breaks to perform.
    """

    data = numpy.ma.compressed(data)
    if len(data) > 1000:
        data.sort()
        ls = numpy.linspace(0, len(data)-1, 1000)
        ls = [int(round(x)) for x in ls]
        data_list = data[ls]
    else:
        data_list = data

    data_list.sort()

    mat1 = []
    for i in range(0, len(data_list) + 1):
        temp = []
        for j in range(0, num_breaks + 1):
            temp.append(0)
        mat1.append(temp)

    mat2 = []
    for i in range(0, len(data_list) + 1):
        temp = []
        for j in range(0, num_breaks + 1):
            temp.append(0)
        mat2.append(temp)

    for i in range(1, num_breaks + 1):
        mat1[1][i] = 1
        mat2[1][i] = 0
        for j in range(2, len(data_list) + 1):
            mat2[j][i] = float('inf')

    v = 0.0
    for l in range(2, len(data_list) + 1):
        s1 = 0.0
        s2 = 0.0
        w = 0.0
        for m in range(1, l + 1):
            i3 = l - m + 1

            val = float(data_list[i3-1])

            s2 += val * val
            s1 += val

            w += 1
            v = s2 - (s1 * s1) / w
            i4 = i3 - 1

            if i4 != 0:
                for j in range(2, num_breaks + 1):
                    if mat2[l][j] >= (v + mat2[i4][j - 1]):
                        mat1[l][j] = i3
                        mat2[l][j] = v + mat2[i4][j - 1]

        mat1[l][1] = 1
        mat2[l][1] = v

    k = len(data_list)
    kclass = []
    for i in range(0, num_breaks + 1):
        kclass.append(0)

    kclass[num_breaks] = float(data_list[len(data_list) - 1])

    count_num = num_breaks
    while count_num >= 2:
        id = int((mat1[k][count_num]) - 2)

        kclass[count_num - 1] = data_list[id]
        k = int((mat1[k][count_num] - 1))
        count_num -= 1

    return [float(x) for x in kclass][1:]
Calculate Jenks natural breaks.

    Adapted from http://danieljlewis.org/files/2010/06/Jenks.pdf
    Credit: Daniel Lewis

    Arguments:
    data -- Array of values to classify.
    num_breaks -- Number of breaks to perform.