Optimal transport and phase transition in dichotomic ratchets