def _mini_batch_convergence(model, iteration_idx, n_iter, tol, n_samples,
    centers_squared_diff, batch_inertia, context, verbose=0):
    """Helper function to encapsulate the early stopping logic"""
    batch_inertia /= model.batch_size
    centers_squared_diff /= model.batch_size
    ewa_diff = context.get('ewa_diff')
    ewa_inertia = context.get('ewa_inertia')
    if ewa_diff is None:
        ewa_diff = centers_squared_diff
        ewa_inertia = batch_inertia
    else:
        alpha = float(model.batch_size) * 2.0 / (n_samples + 1)
        alpha = 1.0 if alpha > 1.0 else alpha
        ewa_diff = ewa_diff * (1 - alpha) + centers_squared_diff * alpha
        ewa_inertia = ewa_inertia * (1 - alpha) + batch_inertia * alpha
    if verbose:
        progress_msg = (
            'Minibatch iteration %d/%d: mean batch inertia: %f, ewa inertia: %f '
             % (iteration_idx + 1, n_iter, batch_inertia, ewa_inertia))
        print(progress_msg)
    if tol > 0.0 and ewa_diff <= tol:
        if verbose:
            print('Converged (small centers change) at iteration %d/%d' % (
                iteration_idx + 1, n_iter))
        return True
    ewa_inertia_min = context.get('ewa_inertia_min')
    no_improvement = context.get('no_improvement', 0)
    if ewa_inertia_min is None or ewa_inertia < ewa_inertia_min:
        no_improvement = 0
        ewa_inertia_min = ewa_inertia
    else:
        no_improvement += 1
    if (model.max_no_improvement is not None and no_improvement >= model.
        max_no_improvement):
        if verbose:
            print(
                'Converged (lack of improvement in inertia) at iteration %d/%d'
                 % (iteration_idx + 1, n_iter))
        return True
    context['ewa_diff'] = ewa_diff
    context['ewa_inertia'] = ewa_inertia
    context['ewa_inertia_min'] = ewa_inertia_min
    context['no_improvement'] = no_improvement
    return False
