from .ops import NumpyOps, CupyOps


def get_ops(ops):
    if ops in ('numpy', 'cpu'):
        return NumpyOps()
    elif ops == ('cupy', 'gpu'):
        return CupyOps()
    else:
        return ops


def score_model(model, X, y):
    correct = 0
    total = 0
    scores = model.predict_batch(X)
    if isinstance(y, tuple) and (isinstance(y[0], tuple) or isinstance(y[0], list)):
        y = model.ops.asarray(model.ops.flatten(y), dtype='i')
    else:
        y = model.ops.asarray(y, dtype='i')
    for i, gold in enumerate(y):
        correct += scores[i].argmax() == gold
        total += 1
    return float(correct) / total


def partition(examples, split_size):
    examples = list(examples)
    numpy.random.shuffle(examples)
    n_docs = len(examples)
    split = int(n_docs * split_size)
    return examples[:split], examples[split:]


def minibatch(stream, batch_size=1000):
    batch = []
    for X in stream:
        batch.append(X)
        if len(batch) >= batch_size:
            yield batch
            batch = []
    if len(batch) != 0:
        yield batch


class Unassigned(object):
    def __init__(self, expected_type):
        self.expected_type = expected_type

    def __get__(self, obj, objtype):
        return None

    def __set__(self, obj, value):
        if not isinstance(obj, self.expected_type):
            raise TypeError("TODO Error")

@@ -1071,16 +1071,774 @@
 batch%0A%0A%0A
+def im2col(sequence, window):%0A    assert window == 2%0A    output = numpy.zeros((sequence.shape%5B0%5D, window*2+1, sequence.shape%5B1%5D))%0A    output%5B:, 2%5D = sequence%0A    output%5B2:, 0%5D = sequence%5B:-2%5D%0A    output%5B1:, 1%5D = sequence%5B:-1%5D%0A    output%5B:-1, 3%5D = sequence%5B1:%5D%0A    output%5B:-2, 4%5D = sequence%5B2:%5D%0A    # Words 0 and 1 have no LL feature%0A    assert sum(abs(output%5B0, 0%5D)) == 0%0A    if len(output) %3E= 2:%0A        assert sum(abs(output%5B1, 0%5D)) == 0%0A        # Word 0 no L feature%0A        assert sum(abs(output%5B1, 0%5D)) == 0%0A    # Words -1 and -2 have no RR feature%0A    assert sum(abs(output%5B-1, 4%5D)) == 0%0A    if len(output) %3E= 2:%0A        assert sum(abs(output%5B-2, 4%5D)) == 0%0A        # Word -1 has no R feature%0A    assert sum(abs(output%5B-1, 3%5D)) == 0%0A    return output%0A%0A%0A
 class Un

Move im2col into util