import math


def adj_mg(tm, mg_conc, seq):
    """Adjust melting temperature a duplexx based on sodium concentration.
    Based on Owczarzy et al, Biochemistry(47), 2008

    Args:
      tm (float): melting temperature at [Mg] = 0 M.
      mg_conc (float): divalent species concentration in M.
      seq (str): input sequence.

    Returns:
      float: adjusted melting temperature.
    """

    # Default
    Tm3 = tm

    # Parameters from paper
    mg_a = 3.92e-5
    mg_b = -9.11e-6
    mg_c = 6.26e-5
    mg_d = 1.42e-5
    mg_e = -4.82e-4
    mg_f = 5.25e-4
    mg_g = 8.31e-5

    # Adjust
    fgc = (seq.count("G") + seq.count("C")) / float(len(seq))
    if 0 < mg_conc:
        mg_conc_log = math.log(mg_conc)
        Tm3r = 1.0 / tm + mg_a + mg_b * mg_conc_log + fgc * (mg_c + mg_d * mg_conc_log)
        Tm3r_factor = mg_e + mg_f * mg_conc_log + mg_g * (mg_conc_log) ** 2
        Tm3r_factor *= 1.0 / (2 * (len(seq) - 1))
        Tm3r += Tm3r_factor
        Tm3 = 1.0 / Tm3r

    return Tm3