import random


def makeVerificationPairsFromClsDict(data, npos, nneg):
    """Makes npos positive and nneg negative pairs from the given data.
    The data is given a dictionary of cls->data.
    Returns (pos, neg), which are both sets.
    Pairs are sorted, to test for equality.
    Note that this can get stuck in an infinite loop if too many pairs are requested."""
    ckeys = data.keys()
    pos, neg = set(), set()
    # make positive pairs by choosing a random class and 2 els within that class
    while len(pos) < npos:
        c = random.choice(ckeys)
        pair = tuple(sorted(random.sample(data[c], 2)))
        pos.add(pair)
    # make negative pairs by choosing 2 random classes and 1 el within each class
    while len(neg) < nneg:
        c1, c2 = random.sample(ckeys, 2)
        pair = tuple(sorted((random.choice(data[c1]), random.choice(data[c2]))))
        neg.add(pair)
    return pos, neg