def discrete_affinity(x, ref, glob_min, glob_max):
    """
    return the absolute affinity from x to ref
    as a proportion of (ref - glob_min) if x < ref
    or as a proportion of (glob_max - x) if x > ref.
    useful for mixing tagged elements in an array.
    """
    if x < glob_min or x > glob_max:
        return 0
    if (ref - x) > 0:
        return 1 - (ref - x) / (ref - glob_min)
    if (ref - x) < 0:
        return 1 - (x - ref) / (glob_max - ref)
    # ref == x
    return 1