def cooccurrence(iterable, window=(-1,-1), term1=lambda x: True, term2=lambda x: True, normalize=lambda x: x, matrix=None, update=None):
    if not isinstance(matrix, dict):
        matrix = {}
    # Memory-efficient iteration:
    if isinstance(iterable, basestring):
        iterable = isplit(iterable)
    if isinstance(iterable, (list, tuple)) and all(hasattr(f, "read") for f in iterable):
        iterable = chain(*(isplit(chain(*x)) for x in iterable))
    if hasattr(iterable, "read"):
        iterable = isplit(chain(*iterable))
    # Window of terms before and after the search term.
    # Deque is more efficient than list.pop(0).
    q = deque()
    # Window size of terms alongside the search term.
    # Note that window=(0,0) will return a dictionary of search term frequency
    # (since it counts co-occurence with itself).
    n = -min(0, window[0]) + max(window[1], 0)
    m = matrix
    # Search terms may fall outside the co-occurrence window, e.g., window=(-3,-2).
    # We add sentinel markers at the start and end of the given iterable.
    for x in chain([Sentinel()] * n, iterable, [Sentinel()] * n):
        q.append(x)
        if len(q) > n:
            # Given window q size and offset,
            # find the index of the candidate term:
            if window[1] >= 0:
                i = -1 - window[1]
            if window[1] < 0:
                i = len(q) - 1
            if i < 0:
                i = len(q) + i
            x1 = q[i]
            if not isinstance(x1, Sentinel):
                x1 = normalize(x1)
                if term1(x1):
                    # Iterate the window and filter co-occurent terms.
                    for j, x2 in enumerate(list(q).__getslice__(i+window[0], i+window[1]+1)):
                        if not isinstance(x2, Sentinel):
                            x2 = normalize(x2)
                            if term2(x2):
                                if update:
                                    update(matrix, x1, x2, j); continue
                                if x1 not in m:
                                    m[x1] = {}
                                if x2 not in m[x1]:
                                    m[x1][x2] = 0
                                m[x1][x2] += 1
            # Slide window.
            q.popleft()
    return m
Estimate the tied covariance matrix.
dataset/ETHPy150Open clips/pattern/pattern/metrics.py/cooccurrence--crossover with--dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/mixture/gaussian_mixture.py/_estimate_gaussian_covariance_tied