import torch


def _rescale(dat, mn_out=0, mx_out=511):
    """ Rescales image intensities between mn_out and mx_out.

    """
    dtype = dat.dtype
    device = dat.device
    dat[(dat == dat.min()) | ~torch.isfinite(dat) | (dat == dat.max())] = 0
    # Make scaling to set image intensities between mn_out and mx_out
    mn = torch.tensor([dat.min(), 1], dtype=dtype, device=device)[None, ...]
    mx = torch.tensor([dat.max(), 1], dtype=dtype, device=device)[None, ...]
    sf = torch.cat((mn, mx), dim=0)
    sf = torch.tensor([mn_out, mx_out], dtype=dtype, device=device)[..., None].solve(sf)[0].squeeze()
    # Rescale
    dat = dat*sf[0] + sf[1]
    # Clamp
    dat = dat.clamp_min(mn_out).clamp_max(mx_out)

    return dat