def error_func(x, indices, weights, target):
    """Given a range of positions x,
    calculate the weighted distances to nneighbors indicated
    by indices and compute the total squared error
    compared to the target differences.
    """
    error = 0.
    for i in range(indices.shape[1]):
        error += (weights[:, i] * (x - x[indices[:, i]] - target[:, i])**2).mean()
    return error