def get_auto_correlation_time(chain, max_lag=None):
    r"""Compute the auto correlation time up to the given lag for the given chain (1d vector).

    This will halt when the maximum lag :math:`m` is reached or when the sum of two consecutive lags for any
    odd lag is lower or equal to zero.

    The auto correlation sum is estimated as:

    .. math::

        \tau = 1 + 2 * \sum_{k=1}^{m}{\rho_{k}}


    Where :math:`\rho_{k}` is estimated as:

    .. math::

        \hat{\rho}_{k} = \frac{E[(X_{t} - \mu)(X_{t + k} - \mu)]}{\sigma^{2}}

    Args:
        chain (ndarray): the vector with the samples
        max_lag (int): the maximum lag to use in the autocorrelation computation. If not given we use:
            :math:`min(n/3, 1000)`.
    """
    max_lag = max_lag or min(len(chain) // 3, 1000)

    normalized_chain = chain - np.mean(chain, dtype=np.float64)

    previous_accoeff = 0
    auto_corr_sum = 0

    for lag in range(1, max_lag):
        auto_correlation_coeff = np.mean(normalized_chain[:len(chain) - lag] * normalized_chain[lag:], dtype=np.float64)

        if lag % 2 == 0:
            if previous_accoeff + auto_correlation_coeff <= 0:
                break

        auto_corr_sum += auto_correlation_coeff
        previous_accoeff = auto_correlation_coeff

    return auto_corr_sum / np.var(chain, dtype=np.float64)