def nPVI(streamForAnalysis):
    """
    Algorithm to give the normalized pairwise variability index
    (Low, Grabe, & Nolan, 2000) of the rhythm of a stream.


    Used by Aniruddh D. Patel to argue for national differences between musical
    themes.  First encountered it in a presentation by Patel, Chew, Francois,
    and Child at MIT.


    n.b. -- takes the distance between each element, including clefs, keys, etc.
    use .notesAndRests etc. to filter out elements that are not useful (though this will skip
    zero length objects)


    n.b. # 2 -- duration is used rather than actual distance -- for gapless
    streams (the norm) these two measures will be identical.

    >>> s2 = converter.parse('tinynotation: 4/4 C4 D E F G').flat.notesAndRests.stream()
    >>> analysis.patel.nPVI(s2)
    0.0

    >>> s3 = converter.parse('tinynotation: 4/4 C4 D8 C4 D8 C4').flat.notesAndRests.stream()
    >>> analysis.patel.nPVI(s3)
    66.6666...

    >>> s4 = corpus.parse('bwv66.6').parts[0].flat.notesAndRests.stream()
    >>> analysis.patel.nPVI(s4)
    12.96296...
    """
    s = streamForAnalysis
    totalElements = len(s)
    summation = 0
    prevQL = s[0].quarterLength
    for i in range(1, totalElements):
        thisQL = s[i].quarterLength
        if thisQL > 0 and prevQL > 0:
            summation += abs(thisQL - prevQL) / ((thisQL + prevQL) / 2.0)
        else:
            pass
        prevQL = thisQL
    final = summation * 100 / (totalElements - 1)
    return final
