예제 #1
0
    def reduction(P, u, O, K):
        """
        The actual reduction algorithm.
        """
        Q = []
        for i, p in enumerate(P):
            h = sdp_rem(p, P[:i] + P[i + 1:], u, O, K)
            if h != []:
                Q.append(h)

        return [sdp_monic(p, K) for p in Q]
예제 #2
0
    def representing_matrix(m):
        M = [[K.zero] * len(basis) for _ in xrange(len(basis))]

        for i, v in enumerate(basis):
            r = sdp_rem([(monomial_mul(m, v), K.one)], G, u, O, K)

            for term in r:
                j = basis.index(term[0])
                M[j][i] = term[1]

        return M
예제 #3
0
    def reduction(P, u, O, K):
        """
        The actual reduction algorithm.
        """
        Q = []
        for i, p in enumerate(P):
            h = sdp_rem(p, P[:i] + P[i + 1 :], u, O, K)
            if h != []:
                Q.append(h)

        return [sdp_monic(p, K) for p in Q]
예제 #4
0
    def representing_matrix(m):
        M = [[K.zero] * len(basis) for _ in xrange(len(basis))]

        for i, v in enumerate(basis):
            r = sdp_rem([(monomial_mul(m, v), K.one)], G, u, O, K)

            for term in r:
                j = basis.index(term[0])
                M[j][i] = term[1]

        return M
예제 #5
0
def is_groebner(G, u, O, K):
    """
    Check if G is a Groebner basis.
    """
    for i in xrange(len(G)):
        for j in xrange(i + 1, len(G)):
            s = sdp_spoly(G[i], G[j], u, O, K)
            s = sdp_rem(s, G, u, O, K)
            if s != []:
                return False

    return True
예제 #6
0
def is_groebner(G, u, O, K):
    """
    Check if G is a Groebner basis.
    """
    for i in xrange(len(G)):
        for j in xrange(i + 1, len(G)):
            s = sdp_spoly(G[i], G[j], u, O, K)
            s = sdp_rem(s, G, u, O, K)
            if s != []:
                return False

    return True
예제 #7
0
    def normal(g, J):
        h = sdp_rem(g, [f[j] for j in J], u, O, K)

        if not h:
            return None
        else:
            h = sdp_monic(h, K)
            h = tuple(h)

            if not h in I:
                I[h] = len(f)
                f.append(h)

            return sdp_LM(h, u), I[h]
예제 #8
0
    def normal(g, J):
        h = sdp_rem(g, [f[j] for j in J], u, O, K)

        if not h:
            return None
        else:
            h = sdp_monic(h, K)
            h = tuple(h)

            if not h in I:
                I[h] = len(f)
                f.append(h)

            return sdp_LM(h, u), I[h]
예제 #9
0
def test_sdp_rem():
    f = sdp_from_dict({(2,1): 4, (1,1): -2, (1,0): 4, (0,1): -2, (0,0): 8}, O_grlex)

    assert sdp_rem(f, [sdp_from_dict({(0,0): 2}, O_grlex)], 1, O_grlex, ZZ) == \
        []

    assert sdp_rem(f, [sdp_from_dict({(0,1): 2}, O_grlex)], 1, O_grlex, ZZ) == \
          sdp_from_dict({(1,0): 4, (0,0): 8}, O_grlex)

    f = sdp_from_dict({(1,0): 1, (0,0): -1}, O_grlex)
    g = sdp_from_dict({(0,1): 1, (0,0): -1}, O_grlex)

    assert sdp_rem(f, [g], 1, O_grlex, ZZ) == f

    f = sdp_from_dict({(3,): 1, (2,): -12, (0,): -42}, O_grlex)
    g = sdp_from_dict({(1,): 1, (0,): -3}, O_grlex)

    r = sdp_from_dict({(0,): -123}, O_grlex)

    assert sdp_rem(f, [g], 0, O_grlex, ZZ) == r

    f = sdp_from_dict({(1,2): 1, (0,0): 1}, O_grlex)
    G = [sdp_from_dict({(1,1): 1, (0,0): 1}, O_grlex),
         sdp_from_dict({(0,1): 1, (0,0): 1}, O_grlex)]

    r = sdp_from_dict({(0,0): 2}, O_grlex)

    assert sdp_rem(f, G, 1, O_grlex, ZZ) == r

    f = sdp_from_dict({(2,1): 1, (1,2): 1, (0,2): 1}, O_grlex)

    G = [sdp_from_dict({(1,1): 1, (0,0): -1}, O_grlex),
         sdp_from_dict({(0,2): 1, (0,0): -1}, O_grlex)]

    r = sdp_from_dict({(1,0): 1, (0,1): 1, (0,0): 1}, O_grlex)

    assert sdp_rem(f, G, 1, O_grlex, ZZ) == r

    G = [sdp_from_dict({(0,2): 1, (0,0): -1}, O_grlex),
         sdp_from_dict({(1,1): 1, (0,0): -1}, O_grlex)]

    r = sdp_from_dict({(1,0): 2, (0,0): 1}, O_grlex)

    assert sdp_rem(f, G, 1, O_grlex, ZZ) == r
예제 #10
0
def test_sdp_rem():
    f = sdp_from_dict(
        {(2, 1): 4, (1, 1): -2, (1, 0): 4, (0, 1): -2, (0, 0): 8}, grlex)

    assert sdp_rem(f, [sdp_from_dict({(0, 0): 2}, grlex)], 1, grlex, ZZ) == []
    assert sdp_rem(f, [sdp_from_dict({(0, 1): 2}, grlex)], 1, grlex, ZZ) == \
        sdp_from_dict({(1, 0): 4, (0, 0): 8}, grlex)

    f = sdp_from_dict({(1, 0): 1, (0, 0): -1}, grlex)
    g = sdp_from_dict({(0, 1): 1, (0, 0): -1}, grlex)

    assert sdp_rem(f, [g], 1, grlex, ZZ) == f

    f = sdp_from_dict({(3,): 1, (2,): -12, (0,): -42}, grlex)
    g = sdp_from_dict({(1,): 1, (0,): -3}, grlex)

    r = sdp_from_dict({(0,): -123}, grlex)

    assert sdp_rem(f, [g], 0, grlex, ZZ) == r

    f = sdp_from_dict({(1, 2): 1, (0, 0): 1}, grlex)
    G = [sdp_from_dict({(1, 1): 1, (0, 0): 1}, grlex),
         sdp_from_dict({(0, 1): 1, (0, 0): 1}, grlex)]

    r = sdp_from_dict({(0, 0): 2}, grlex)

    assert sdp_rem(f, G, 1, grlex, ZZ) == r

    f = sdp_from_dict({(2, 1): 1, (1, 2): 1, (0, 2): 1}, grlex)

    G = [sdp_from_dict({(1, 1): 1, (0, 0): -1}, grlex),
         sdp_from_dict({(0, 2): 1, (0, 0): -1}, grlex)]

    r = sdp_from_dict({(1, 0): 1, (0, 1): 1, (0, 0): 1}, grlex)

    assert sdp_rem(f, G, 1, grlex, ZZ) == r

    G = [sdp_from_dict({(0, 2): 1, (0, 0): -1}, grlex),
         sdp_from_dict({(1, 1): 1, (0, 0): -1}, grlex)]

    r = sdp_from_dict({(1, 0): 2, (0, 0): 1}, grlex)

    assert sdp_rem(f, G, 1, grlex, ZZ) == r
예제 #11
0
def f5b(F, u, O, K, gens="", verbose=False):
    """
    Computes a reduced Groebner basis for the ideal generated by F.

    f5b is an implementation of the F5B algorithm by Yao Sun and
    Dingkang Wang. Similarly to Buchberger's algorithm, the algorithm
    proceeds by computing critical pairs, computing the S-polynomial,
    reducing it and adjoining the reduced S-polynomial if it is not 0.

    Unlike Buchberger's algorithm, each polynomial contains additional
    information, namely a signature and a number. The signature
    specifies the path of computation (i.e. from which polynomial in
    the original basis was it derived and how), the number says when
    the polynomial was added to the basis.  With this information it
    is (often) possible to decide if an S-polynomial will reduce to
    0 and can be discarded.

    Optimizations include: Reducing the generators before computing
    a Groebner basis, removing redundant critical pairs when a new
    polynomial enters the basis and sorting the critical pairs and
    the current basis.

    Once a Groebner basis has been found, it gets reduced.

    ** References **
    Yao Sun, Dingkang Wang: "A New Proof for the Correctness of F5
    (F5-Like) Algorithm", http://arxiv.org/abs/1004.0084 (specifically
    v4)

    Thomas Becker, Volker Weispfenning, Groebner bases: A computational
    approach to commutative algebra, 1993, p. 203, 216
    """
    if not K.has_Field:
        raise DomainError("can't compute a Groebner basis over %s" % K)

    # reduce polynomials (like in Mario Pernici's implementation) (Becker, Weispfenning, p. 203)
    B = F
    while True:
        F = B
        B = []

        for i in xrange(len(F)):
            p = F[i]
            r = sdp_rem(p, F[:i], u, O, K)

            if r != []:
                B.append(r)

        if F == B:
            break

    # basis
    B = [lbp(sig((0,) * (u + 1), i + 1), F[i], i + 1) for i in xrange(len(F))]
    B.sort(key=lambda f: O(sdp_LM(Polyn(f), u)), reverse=True)

    # critical pairs
    CP = [critical_pair(B[i], B[j], u, O, K) for i in xrange(len(B)) for j in xrange(i + 1, len(B))]
    CP.sort(key=lambda cp: cp_key(cp, O), reverse=True)

    k = len(B)

    reductions_to_zero = 0

    while len(CP):
        cp = CP.pop()

        # discard redundant critical pairs:
        if is_rewritable_or_comparable(cp[0], Num(cp[2]), B, u, K):
            continue
        if is_rewritable_or_comparable(cp[3], Num(cp[5]), B, u, K):
            continue

        s = s_poly(cp, u, O, K)

        p = f5_reduce(s, B, u, O, K)

        p = lbp(Sign(p), sdp_monic(Polyn(p), K), k + 1)

        if Polyn(p) != []:
            # remove old critical pairs, that become redundant when adding p:
            indices = []
            for i, cp in enumerate(CP):
                if is_rewritable_or_comparable(cp[0], Num(cp[2]), [p], u, K):
                    indices.append(i)
                elif is_rewritable_or_comparable(cp[3], Num(cp[5]), [p], u, K):
                    indices.append(i)

            for i in reversed(indices):
                del CP[i]

            # only add new critical pairs that are not made redundant by p:
            for g in B:
                if Polyn(g) != []:
                    cp = critical_pair(p, g, u, O, K)
                    if is_rewritable_or_comparable(cp[0], Num(cp[2]), [p], u, K):
                        continue
                    elif is_rewritable_or_comparable(cp[3], Num(cp[5]), [p], u, K):
                        continue

                    CP.append(cp)

            # sort (other sorting methods/selection strategies were not as successful)
            CP.sort(key=lambda cp: cp_key(cp, O), reverse=True)

            # insert p into B:
            m = sdp_LM(Polyn(p), u)
            if O(m) <= O(sdp_LM(Polyn(B[-1]), u)):
                B.append(p)
            else:
                for i, q in enumerate(B):
                    if O(m) > O(sdp_LM(Polyn(q), u)):
                        B.insert(i, p)
                        break

            k += 1

            # print(len(B), len(CP), "%d critical pairs removed" % len(indices))
        else:
            reductions_to_zero += 1

    if verbose:
        print ("%d reductions to zero" % reductions_to_zero)

    # reduce Groebner basis:
    H = [sdp_monic(Polyn(g), K) for g in B]
    H = red_groebner(H, u, O, K)

    return sorted(H, key=lambda f: O(sdp_LM(f, u)), reverse=True)
예제 #12
0
def buchberger(f, u, O, K, gens="", verbose=False):
    """
    Computes Groebner basis for a set of polynomials in `K[X]`.

    Given a set of multivariate polynomials `F`, finds another
    set `G`, such that Ideal `F = Ideal G` and `G` is a reduced
    Groebner basis.

    The resulting basis is unique and has monic generators if the
    ground domains is a field. Otherwise the result is non-unique
    but Groebner bases over e.g. integers can be computed (if the
    input polynomials are monic).

    Groebner bases can be used to choose specific generators for a
    polynomial ideal. Because these bases are unique you can check
    for ideal equality by comparing the Groebner bases.  To see if
    one polynomial lies in an ideal, divide by the elements in the
    base and see if the remainder vanishes.

    They can also be used to solve systems of polynomial equations
    as,  by choosing lexicographic ordering,  you can eliminate one
    variable at a time, provided that the ideal is zero-dimensional
    (finite number of solutions).

    **References**

    1. [Bose03]_
    2. [Giovini91]_
    3. [Ajwa95]_
    4. [Cox97]_

    Algorithm used: an improved version of Buchberger's algorithm
    as presented in T. Becker, V. Weispfenning, Groebner Bases: A
    Computational Approach to Commutative Algebra, Springer, 1993,
    page 232.

    Added optional ``gens`` argument to apply :func:`sdp_str` for
    the purpose of debugging the algorithm.

    """
    if not K.has_Field:
        raise DomainError("can't compute a Groebner basis over %s" % K)

    def select(P):
        # normal selection strategy
        # select the pair with minimum LCM(LM(f), LM(g))
        pr = min(P, key=lambda pair: O(monomial_lcm(sdp_LM(f[pair[0]], u), sdp_LM(f[pair[1]], u))))
        return pr

    def normal(g, J):
        h = sdp_rem(g, [f[j] for j in J], u, O, K)

        if not h:
            return None
        else:
            h = sdp_monic(h, K)
            h = tuple(h)

            if not h in I:
                I[h] = len(f)
                f.append(h)

            return sdp_LM(h, u), I[h]

    def update(G, B, ih):
        # update G using the set of critical pairs B and h
        # [BW] page 230
        h = f[ih]
        mh = sdp_LM(h, u)

        # filter new pairs (h, g), g in G
        C = G.copy()
        D = set()

        while C:
            # select a pair (h, g) by popping an element from C
            ig = C.pop()
            g = f[ig]
            mg = sdp_LM(g, u)
            LCMhg = monomial_lcm(mh, mg)

            def lcm_divides(ip):
                # LCM(LM(h), LM(p)) divides LCM(LM(h), LM(g))
                m = monomial_lcm(mh, sdp_LM(f[ip], u))
                return monomial_div(LCMhg, m)

            # HT(h) and HT(g) disjoint: mh*mg == LCMhg
            if monomial_mul(mh, mg) == LCMhg or (
                not any(lcm_divides(ipx) for ipx in C) and not any(lcm_divides(pr[1]) for pr in D)
            ):
                D.add((ih, ig))

        E = set()

        while D:
            # select h, g from D (h the same as above)
            ih, ig = D.pop()
            mg = sdp_LM(f[ig], u)
            LCMhg = monomial_lcm(mh, mg)

            if not monomial_mul(mh, mg) == LCMhg:
                E.add((ih, ig))

        # filter old pairs
        B_new = set()

        while B:
            # select g1, g2 from B (-> CP)
            ig1, ig2 = B.pop()
            mg1 = sdp_LM(f[ig1], u)
            mg2 = sdp_LM(f[ig2], u)
            LCM12 = monomial_lcm(mg1, mg2)

            # if HT(h) does not divide lcm(HT(g1), HT(g2))
            if not monomial_div(LCM12, mh) or monomial_lcm(mg1, mh) == LCM12 or monomial_lcm(mg2, mh) == LCM12:
                B_new.add((ig1, ig2))

        B_new |= E

        # filter polynomials
        G_new = set()

        while G:
            ig = G.pop()
            mg = sdp_LM(f[ig], u)

            if not monomial_div(mg, mh):
                G_new.add(ig)

        G_new.add(ih)

        return G_new, B_new

    # end of update ################################

    if not f:
        return []

    # replace f with a reduced list of initial polynomials; see [BW] page 203
    f1 = f[:]

    while True:
        f = f1[:]
        f1 = []

        for i in range(len(f)):
            p = f[i]
            r = sdp_rem(p, f[:i], u, O, K)

            if r:
                f1.append(sdp_monic(r, K))

        if f == f1:
            break

    f = [tuple(p) for p in f]
    I = {}  # ip = I[p]; p = f[ip]
    F = set()  # set of indices of polynomials
    G = set()  # set of indices of intermediate would-be Groebner basis
    CP = set()  # set of pairs of indices of critical pairs

    for i, h in enumerate(f):
        I[h] = i
        F.add(i)

    #####################################
    # algorithm GROEBNERNEWS2 in [BW] page 232
    while F:
        # select p with minimum monomial according to the monomial ordering O
        h = min([f[x] for x in F], key=lambda f: O(sdp_LM(f, u)))
        ih = I[h]
        F.remove(ih)
        G, CP = update(G, CP, ih)

    # count the number of critical pairs which reduce to zero
    reductions_to_zero = 0

    while CP:
        ig1, ig2 = select(CP)
        CP.remove((ig1, ig2))

        h = sdp_spoly(f[ig1], f[ig2], u, O, K)
        # ordering divisors is on average more efficient [Cox] page 111
        G1 = sorted(G, key=lambda g: O(sdp_LM(f[g], u)))
        ht = normal(h, G1)

        if ht:
            G, CP = update(G, CP, ht[1])
        else:
            reductions_to_zero += 1

    ######################################
    # now G is a Groebner basis; reduce it
    Gr = set()

    for ig in G:
        ht = normal(f[ig], G - set([ig]))

        if ht:
            Gr.add(ht[1])

    Gr = [list(f[ig]) for ig in Gr]

    # order according to the monomial ordering
    Gr = sorted(Gr, key=lambda f: O(sdp_LM(f, u)), reverse=True)

    if verbose:
        print "reductions_to_zero = %d" % reductions_to_zero

    return Gr
예제 #13
0
def f5b(F, u, O, K, gens='', verbose=False):
    """
    Computes a reduced Groebner basis for the ideal generated by F.

    f5b is an implementation of the F5B algorithm by Yao Sun and
    Dingkang Wang. Similarly to Buchberger's algorithm, the algorithm
    proceeds by computing critical pairs, computing the S-polynomial,
    reducing it and adjoining the reduced S-polynomial if it is not 0.

    Unlike Buchberger's algorithm, each polynomial contains additional
    information, namely a signature and a number. The signature
    specifies the path of computation (i.e. from which polynomial in
    the original basis was it derived and how), the number says when
    the polynomial was added to the basis.  With this information it
    is (often) possible to decide if an S-polynomial will reduce to
    0 and can be discarded.

    Optimizations include: Reducing the generators before computing
    a Groebner basis, removing redundant critical pairs when a new
    polynomial enters the basis and sorting the critical pairs and
    the current basis.

    Once a Groebner basis has been found, it gets reduced.

    ** References **
    Yao Sun, Dingkang Wang: "A New Proof for the Correctness of F5
    (F5-Like) Algorithm", http://arxiv.org/abs/1004.0084 (specifically
    v4)

    Thomas Becker, Volker Weispfenning, Groebner bases: A computational
    approach to commutative algebra, 1993, p. 203, 216
    """
    if not K.has_Field:
        raise DomainError("can't compute a Groebner basis over %s" % K)

    # reduce polynomials (like in Mario Pernici's implementation) (Becker, Weispfenning, p. 203)
    B = F
    while True:
        F = B
        B = []

        for i in xrange(len(F)):
            p = F[i]
            r = sdp_rem(p, F[:i], u, O, K)

            if r != []:
                B.append(r)

        if F == B:
            break

    # basis
    B = [lbp(sig((0, ) * (u + 1), i + 1), F[i], i + 1) for i in xrange(len(F))]
    B.sort(key=lambda f: O(sdp_LM(Polyn(f), u)), reverse=True)

    # critical pairs
    CP = [
        critical_pair(B[i], B[j], u, O, K) for i in xrange(len(B))
        for j in xrange(i + 1, len(B))
    ]
    CP.sort(key=lambda cp: cp_key(cp, O), reverse=True)

    k = len(B)

    reductions_to_zero = 0

    while len(CP):
        cp = CP.pop()

        # discard redundant critical pairs:
        if is_rewritable_or_comparable(cp[0], Num(cp[2]), B, u, K):
            continue
        if is_rewritable_or_comparable(cp[3], Num(cp[5]), B, u, K):
            continue

        s = s_poly(cp, u, O, K)

        p = f5_reduce(s, B, u, O, K)

        p = lbp(Sign(p), sdp_monic(Polyn(p), K), k + 1)

        if Polyn(p) != []:
            # remove old critical pairs, that become redundant when adding p:
            indices = []
            for i, cp in enumerate(CP):
                if is_rewritable_or_comparable(cp[0], Num(cp[2]), [p], u, K):
                    indices.append(i)
                elif is_rewritable_or_comparable(cp[3], Num(cp[5]), [p], u, K):
                    indices.append(i)

            for i in reversed(indices):
                del CP[i]

            # only add new critical pairs that are not made redundant by p:
            for g in B:
                if Polyn(g) != []:
                    cp = critical_pair(p, g, u, O, K)
                    if is_rewritable_or_comparable(cp[0], Num(cp[2]), [p], u,
                                                   K):
                        continue
                    elif is_rewritable_or_comparable(cp[3], Num(cp[5]), [p], u,
                                                     K):
                        continue

                    CP.append(cp)

            # sort (other sorting methods/selection strategies were not as successful)
            CP.sort(key=lambda cp: cp_key(cp, O), reverse=True)

            # insert p into B:
            m = sdp_LM(Polyn(p), u)
            if O(m) <= O(sdp_LM(Polyn(B[-1]), u)):
                B.append(p)
            else:
                for i, q in enumerate(B):
                    if O(m) > O(sdp_LM(Polyn(q), u)):
                        B.insert(i, p)
                        break

            k += 1

            #print(len(B), len(CP), "%d critical pairs removed" % len(indices))
        else:
            reductions_to_zero += 1

    if verbose:
        print("%d reductions to zero" % reductions_to_zero)

    # reduce Groebner basis:
    H = [sdp_monic(Polyn(g), K) for g in B]
    H = red_groebner(H, u, O, K)

    return sorted(H, key=lambda f: O(sdp_LM(f, u)), reverse=True)
예제 #14
0
def buchberger(f, u, O, K, gens='', verbose=False):
    """
    Computes Groebner basis for a set of polynomials in `K[X]`.

    Given a set of multivariate polynomials `F`, finds another
    set `G`, such that Ideal `F = Ideal G` and `G` is a reduced
    Groebner basis.

    The resulting basis is unique and has monic generators if the
    ground domains is a field. Otherwise the result is non-unique
    but Groebner bases over e.g. integers can be computed (if the
    input polynomials are monic).

    Groebner bases can be used to choose specific generators for a
    polynomial ideal. Because these bases are unique you can check
    for ideal equality by comparing the Groebner bases.  To see if
    one polynomial lies in an ideal, divide by the elements in the
    base and see if the remainder vanishes.

    They can also be used to  solve systems of polynomial equations
    as,  by choosing lexicographic ordering,  you can eliminate one
    variable at a time, provided that the ideal is zero-dimensional
    (finite number of solutions).

    **References**

    1. [Bose03]_
    2. [Giovini91]_
    3. [Ajwa95]_
    4. [Cox97]_

    Algorithm used: an improved version of Buchberger's algorithm
    as presented in T. Becker, V. Weispfenning, Groebner Bases: A
    Computational Approach to Commutative Algebra, Springer, 1993,
    page 232.

    Added optional ``gens`` argument to apply :func:`sdp_str` for
    the purpose of debugging the algorithm.

    """
    if not K.has_Field:
        raise DomainError("can't compute a Groebner basis over %s" % K)

    def select(P):
        # normal selection strategy
        # select the pair with minimum LCM(LM(f), LM(g))
        pr = min(P,
                 key=lambda pair:
                 O(monomial_lcm(sdp_LM(f[pair[0]], u), sdp_LM(f[pair[1]], u))))
        return pr

    def normal(g, J):
        h = sdp_rem(g, [f[j] for j in J], u, O, K)

        if not h:
            return None
        else:
            h = sdp_monic(h, K)
            h = tuple(h)

            if not h in I:
                I[h] = len(f)
                f.append(h)

            return sdp_LM(h, u), I[h]

    def update(G, B, ih):
        # update G using the set of critical pairs B and h
        # [BW] page 230
        h = f[ih]
        mh = sdp_LM(h, u)

        # filter new pairs (h, g), g in G
        C = G.copy()
        D = set()

        while C:
            # select a pair (h, g) by popping an element from C
            ig = C.pop()
            g = f[ig]
            mg = sdp_LM(g, u)
            LCMhg = monomial_lcm(mh, mg)

            def lcm_divides(ip):
                # LCM(LM(h), LM(p)) divides LCM(LM(h), LM(g))
                m = monomial_lcm(mh, sdp_LM(f[ip], u))
                return monomial_div(LCMhg, m)

            # HT(h) and HT(g) disjoint: mh*mg == LCMhg
            if monomial_mul(mh, mg) == LCMhg or (not any(
                    lcm_divides(ipx)
                    for ipx in C) and not any(lcm_divides(pr[1]) for pr in D)):
                D.add((ih, ig))

        E = set()

        while D:
            # select h, g from D (h the same as above)
            ih, ig = D.pop()
            mg = sdp_LM(f[ig], u)
            LCMhg = monomial_lcm(mh, mg)

            if not monomial_mul(mh, mg) == LCMhg:
                E.add((ih, ig))

        # filter old pairs
        B_new = set()

        while B:
            # select g1, g2 from B (-> CP)
            ig1, ig2 = B.pop()
            mg1 = sdp_LM(f[ig1], u)
            mg2 = sdp_LM(f[ig2], u)
            LCM12 = monomial_lcm(mg1, mg2)

            # if HT(h) does not divide lcm(HT(g1), HT(g2))
            if not monomial_div(LCM12, mh) or \
                monomial_lcm(mg1, mh) == LCM12 or \
                monomial_lcm(mg2, mh) == LCM12:
                B_new.add((ig1, ig2))

        B_new |= E

        # filter polynomials
        G_new = set()

        while G:
            ig = G.pop()
            mg = sdp_LM(f[ig], u)

            if not monomial_div(mg, mh):
                G_new.add(ig)

        G_new.add(ih)

        return G_new, B_new

    # end of update ################################

    if not f:
        return []

    # replace f with a reduced list of initial polynomials; see [BW] page 203
    f1 = f[:]

    while True:
        f = f1[:]
        f1 = []

        for i in range(len(f)):
            p = f[i]
            r = sdp_rem(p, f[:i], u, O, K)

            if r:
                f1.append(sdp_monic(r, K))

        if f == f1:
            break

    f = [tuple(p) for p in f]
    I = {}  # ip = I[p]; p = f[ip]
    F = set()  # set of indices of polynomials
    G = set()  # set of indices of intermediate would-be Groebner basis
    CP = set()  # set of pairs of indices of critical pairs

    for i, h in enumerate(f):
        I[h] = i
        F.add(i)

    #####################################
    # algorithm GROEBNERNEWS2 in [BW] page 232
    while F:
        # select p with minimum monomial according to the monomial ordering O
        h = min([f[x] for x in F], key=lambda f: O(sdp_LM(f, u)))
        ih = I[h]
        F.remove(ih)
        G, CP = update(G, CP, ih)

    # count the number of critical pairs which reduce to zero
    reductions_to_zero = 0

    while CP:
        ig1, ig2 = select(CP)
        CP.remove((ig1, ig2))

        h = sdp_spoly(f[ig1], f[ig2], u, O, K)
        # ordering divisors is on average more efficient [Cox] page 111
        G1 = sorted(G, key=lambda g: O(sdp_LM(f[g], u)))
        ht = normal(h, G1)

        if ht:
            G, CP = update(G, CP, ht[1])
        else:
            reductions_to_zero += 1

    ######################################
    # now G is a Groebner basis; reduce it
    Gr = set()

    for ig in G:
        ht = normal(f[ig], G - set([ig]))

        if ht:
            Gr.add(ht[1])

    Gr = [list(f[ig]) for ig in Gr]

    # order according to the monomial ordering
    Gr = sorted(Gr, key=lambda f: O(sdp_LM(f, u)), reverse=True)

    if verbose:
        print 'reductions_to_zero = %d' % reductions_to_zero

    return Gr