File: arraybuilder.pyx

package info (click to toggle)
scikit-learn 0.11.0-2%2Bdeb7u1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 13,900 kB
  • sloc: python: 34,740; ansic: 8,860; cpp: 8,849; pascal: 230; makefile: 211; sh: 14
file content (47 lines) | stat: -rw-r--r-- 1,209 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Author: Lars Buitinck <L.J.Buitinck@uva.nl>
# License: BSD-style

cimport cython
cimport numpy as np
import numpy as np


cdef class ArrayBuilder(object):
    """Helper class to incrementally build a 1-d numpy.ndarray"""
    # Or: let's reinvent the wheel!

    GROWTH_FACTOR = 1.5

    cdef Py_ssize_t _nelems
    cdef object _arr    # object because we don't know the dtype statically

    def __init__(self, dtype, initial_capacity=256):
        assert self.GROWTH_FACTOR > 1
        assert initial_capacity >= 2
        self._arr = np.empty(initial_capacity, dtype=dtype)
        self._nelems = 0

    def __len__(self):
        return self._nelems

    @cython.boundscheck(False)
    def append(self, x):
        """Append a single value.

        Complexity: amortized O(1).
        """
        if self._nelems == self._arr.size:
            self._grow()
        self._arr[self._nelems] = x
        self._nelems += 1

    def get(self):
        """Return the constructed array.

        Don't use an ArrayBuilder after calling this method.
        """
        self._arr.resize(self._nelems)
        return self._arr

    cdef _grow(self):
        self._arr.resize(self._arr.size * self.GROWTH_FACTOR)