Let’s say I am predicting a quaternion. How do I implement this piecewise constraint that is conditioned on the scalar/real “w” (for quaternion = [x,y,z,w]).
In Python:
def positive_real_quat(quat):
    """
    Flip quaternion to positive real hemisphere so there is a single quaternion describing each rotation

    :param quat: [x,y,z,w]
    :return:
    """
    x, y, z, w =quat
    if w >= 0:
        return quat
    else:
        return -quat

But I need the above code to be differentiable as the final function in my neural network. How do I do it?