  Interaction with divalent cations is of paramount importance for RNA
structural stability and function. We here report a detailed molecular dynamics
study of all the possible binding sites for Mg$^{2+}$ on a RNA duplex,
including both direct (inner sphere) and indirect (outer sphere) binding. In
order to tackle sampling issues, we develop a modified version of bias-exchange
metadynamics which allows us to simultaneously compute affinities with
previously unreported statistical accuracy. Results correctly reproduce trends
observed in crystallographic databases. Based on this, we simulate a carefully
chosen set of models that allows us to quantify the effects of competition with
monovalent cations, RNA flexibility, and RNA hybridization. Our simulations
reproduce the decrease and increase of Mg$^{2+}$ affinity due to ion
competition and hybridization respectively, and predict that RNA flexibility
has a site dependent effect. This suggests a non trivial interplay between RNA
conformational entropy and divalent cation binding.
