Helper function for :py:func:`.make_r_gaussmix` and
    :py:func:`.make_r_tmix`. Group the ``data`` according to the R value
    and split each group into ``K_g`` patches. Return the patch means
    and covariances. For details see the docstrings of the above mentioned
    functions.

def _make_r_patches(data, K_g, critical_r, indices, approx):
    '''Helper function for :py:func:`.make_r_gaussmix` and
    :py:func:`.make_r_tmix`. Group the ``data`` according to the R value
    and split each group into ``K_g`` patches. Return the patch means
    and covariances. For details see the docstrings of the above mentioned
    functions.

    '''
    def append_components(means, covs, data, partition):
        subdata_start = 0
        subdata_stop  = partition[0]
        for len_subdata in partition:
            subdata = data[subdata_start:subdata_stop]
            means.append( _np.mean(subdata,   axis=0) )
            covs.append ( _np.cov (subdata, rowvar=0) )
            subdata_start += len_subdata
            subdata_stop  += len_subdata

    n = len(data[0])
    for item in data:
        assert len(item) == n, 'Every chain must bring the same number of points.'

    data = [_np.asarray(d) for d in data]

    if indices is None:
        # choose all parameters
        indices = _np.arange(data[0].shape[1])

    assert len(indices) > 0, 'Invalid specification of parameter indices. Need a non-empty iterable, got ' + str(indices)

    # select columns of parameters through indices
    chain_groups = r_group([_np.mean(chain_values.T[indices], axis=1) for chain_values in data],
                           [_np.var (chain_values.T[indices], axis=1, ddof=1) for chain_values in data],
                           n, critical_r, approx)

    long_patches_means = []
    long_patches_covs = []
    for group in chain_groups:
        # we want K_g components from k_g = len(group) chains
        k_g = len(group)
        if K_g >= k_g:
            # find minimal lexicographic integer partition
            n = _part(K_g, k_g)
            for i, chain_index in enumerate(group):
                # need to partition in n[i] parts
                data_full_chain = data[chain_index]
                # find minimal lexicographic integer partition of chain_length into n[i]
                this_patch_lengths = _part(len(data_full_chain), n[i])
                append_components(long_patches_means, long_patches_covs, data_full_chain, this_patch_lengths)
        else:
            # form one long chain and set k_g = 1
            k_g = 1
            # make one large chain
            data_full_chain = _np.vstack([data[i] for i in group])
            # need to partition into K_g parts -- > minimal lexicographic integer partition
            this_patch_lengths = _part(len(data_full_chain), K_g)
            append_components(long_patches_means, long_patches_covs, data_full_chain, this_patch_lengths)

    return long_patches_means, long_patches_covs