Skip to content

Parallelised

>>> from vector import vecnpadd
>>> vecnpadd((1, 2), ((3, 4, 5),
...                   (6, 7, 8)))
array([[4, 6, 5],
       [7, 9, 8]])

Prefixed by vecnp... (vector numpy).

numpy-versions of the functions are also provided, to operate on multiple vectors at once. They behave like the ones in numpy.polynomial.polynomial, but also work on 2D-arrays (and all combinations of 1D & 2D arrays) and broadcast to multiple dimensions like the usual numpy operations (but adjust the shapes accordingly).

vecnpzero is np.array([0]) like numpy.polynomial.polynomial.polyzero, not veczero=() (empty tuple, no zero coefficient left) like in the functions and class above.

Padding is done with numpy.int64(0).

They return scalars or numpy.ndarrays.

Creation routines have a dimension argument d. If left to None, the returned values are 1D, so a single vector. If given, the routines return a 2D-array representing multiple vectors in rows.


Creation

vecnpzero(d=None)

Return d zero vectors.

\[ 0^{d\times 0} \qquad \text{or} \qquad \begin{pmatrix} 0 \end{pmatrix} \]

The returned value is a (d, 1)-array of zeros if d is not None or [0] otherwise.

Source code in vector\parallelised.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def vecnpzero(d=None):
    r"""Return `d` zero vectors.

    $$
        0^{d\times 0} \qquad \text{or} \qquad \begin{pmatrix}
            0
        \end{pmatrix} 
    $$

    The returned value is a `(d, 1)`-array of zeros if `d` is not `None`
    or `[0]` otherwise.
    """
    #same dtype as numpy.polynomial.polynomial.polyzero
    return np.zeros(1 if d is None else (d, 1), dtype=object)

vecnpbasis(i, c=1, d=None)

Return d many i-th basis vectors times c.

The returned value is a (d, i+1)-array if d is not None or (i+1,) otherwise.

Source code in vector\parallelised.py
34
35
36
37
38
39
40
41
42
43
def vecnpbasis(i, c=1, d=None):
    """Return `d` many `i`-th basis vectors times `c`.

    The returned value is a `(d, i+1)`-array if `d` is not `None`
    or `(i+1,)` otherwise.
    """
    #choose dtype acc to c
    v = np.zeros(i+1 if d is None else (d, i+1), dtype=np.dtype(type(c)))
    v[..., -1] = c #maybe scalar, maybe (d,)-array
    return v

vecnprand(n, d=None)

Return d random vectors of n uniform coefficients in [0, 1[.

The returned value is a (d, n)-array if d is not None or (n,) otherwise.

Source code in vector\parallelised.py
45
46
47
48
49
50
51
def vecnprand(n, d=None):
    """Return `d` random vectors of `n` uniform coefficients in `[0, 1[`.

    The returned value is a `(d, n)`-array if `d` is not `None`
    or `(n,)` otherwise.
    """
    return np.random.rand(*((n,) if d is None else (d, n)))

vecnprandn(n, normed=True, d=None)

Return d random vectors of n normal distributed coefficients.

The returned value is a (d, n)-array if d is not None or (n,) otherwise.

Source code in vector\parallelised.py
53
54
55
56
57
58
59
60
def vecnprandn(n, normed=True, d=None):
    """Return `d` random vectors of `n` normal distributed coefficients.

    The returned value is a `(d, n)`-array if `d` is not `None`
    or `(n,)` otherwise.
    """
    v = np.random.randn(*((n,) if d is None else (d, n)))
    return v/np.linalg.norm(v, axis=-1, keepdims=True) if normed else v

Utility

vecnpdim(v)

Return the number of allocated dimensions in this vector or vectors.

Source code in vector\parallelised.py
64
65
66
def vecnpdim(v):
    """Return the number of allocated dimensions in this vector or vectors."""
    return np.asarray(v).shape[-1]

vecnpeq(v, w)

Return if two vectors are equal.

Source code in vector\parallelised.py
68
69
70
71
72
73
74
def vecnpeq(v, w):
    """Return if two vectors are equal."""
    v, w = np.asarray(v), np.asarray(w)
    if v.ndim == w.ndim == 1:
        return veceq(v, w)
    return np.array([veceq(v[i] if v.ndim>1 else v, w[i] if w.ndim>1 else w) \
            for i in range(v.shape[0] if v.ndim>1 else w.shape[0])])

vecnptrim(v, tol=1e-09)

Remove all trailing near zero (abs(v_i)<=tol) coefficients.

Source code in vector\parallelised.py
76
77
78
79
80
81
82
83
84
def vecnptrim(v, tol=1e-9):
    """Remove all trailing near zero (abs(v_i)<=tol) coefficients."""
    v = np.asarray(v)
    #use np.all, because v[...,-1] maybe a scalar (not iterable)
    while v.shape[-1]>1 and np.all(np.abs(v[...,-1])<=tol):
        v = v[...,:-1]
    if v.shape[-1]==1 and np.all(np.abs(v[...,0])<=tol): #leave 'leading' zero
        v[...,0] = 0
    return v

vecnpround(v, ndigits=0)

Wrapper for numpy.round.

Source code in vector\parallelised.py
86
87
88
def vecnpround(v, ndigits=0):
    """Wrapper for `numpy.round`."""
    return np.round(np.asarray(v), ndigits)

Hilbert space

vecnpabsq(v)

Return the sum of absolute squares of the coefficients.

Source code in vector\parallelised.py
92
93
94
def vecnpabsq(v):
    """Return the sum of absolute squares of the coefficients."""
    return np.sum(np.abs(v)**2, axis=-1)

vecnpabs(v)

Return the Euclidean/L2-norm.

Source code in vector\parallelised.py
96
97
98
def vecnpabs(v):
    """Return the Euclidean/L2-norm."""
    return np.linalg.norm(v, axis=-1)

vecnpdot(v, w)

Return the inner product of two vectors without conjugation.

Source code in vector\parallelised.py
100
101
102
103
104
105
def vecnpdot(v, w):
    """Return the inner product of two vectors without conjugation."""
    v, w = np.asarray(v), np.asarray(w)
    shape = tuple(reversed(tuple(
            map(min, zip(reversed(v.shape), reversed(w.shape))))))
    return np.sum(v[...,*map(slice, shape)]*w[...,*map(slice, shape)], axis=-1)

vecnpparallel(v, w)

Return if two vectors are parallel.

Source code in vector\parallelised.py
107
108
109
110
def vecnpparallel(v, w):
    """Return if two vectors are parallel."""
    v, w = np.asarray(v), np.asarray(w)
    return vecnpabsq(v)*vecnpabsq(w) == vecnpdot(v, w)**2

Vector space

vecnppos(v)

Return the vector with the unary positive operator applied.

Source code in vector\parallelised.py
114
115
116
def vecnppos(v):
    """Return the vector with the unary positive operator applied."""
    return +np.asarray(v)

vecnpneg(v)

Return the vector with the unary negative operator applied.

Source code in vector\parallelised.py
118
119
120
def vecnpneg(v):
    """Return the vector with the unary negative operator applied."""
    return -np.asarray(v)

vecnpadd(*vs)

Return the sum of vectors.

Source code in vector\parallelised.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def vecnpadd(*vs):
    """Return the sum of vectors."""
    if not vs: #empty sum
        return vecnpzero()

    vs = tuple(map(np.asarray, vs))
    if not all(v.ndim in {1, 2} for v in vs): #all 1D or 2D
        raise ValueError

    heights = {vdi for v in vs for vdi in v.shape[:-1]}
    if len(heights) > 1: #all 2D same height
        raise ValueError

    r = np.zeros(tuple(heights)+(max(v.shape[-1] for v in vs),),
            dtype=np.result_type(*vs))
    for v in vs:
        r[...,:v.shape[-1]] += v
    return r

vecnpsub(v, w)

Return the difference of two vectors.

Source code in vector\parallelised.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def vecnpsub(v, w):
    """Return the difference of two vectors."""
    v, w = np.asarray(v), np.asarray(w)
    if v.ndim not in {1, 2} or w.ndim not in {1, 2}: #1D-1D, 1D-2D, 2D-1D, 2D-2D
        raise ValueError

    heights = set(v.shape[:-1]) | set(w.shape[:-1])
    if len(heights) > 1: #both same height if both 2D
        raise ValueError

    r = np.zeros(tuple(heights)+(max(v.shape[-1], w.shape[-1]),),
            dtype=np.result_type(v, w))
    r[...,:v.shape[-1]] += v
    r[...,:w.shape[-1]] -= w
    return r

vecnpmul(a, v)

Return the product of a scalar and a vector.

Source code in vector\parallelised.py
157
158
159
def vecnpmul(a, v):
    """Return the product of a scalar and a vector."""
    return a * np.asarray(v)

vecnptruediv(v, a)

Return the true division of a vector and a scalar.

Source code in vector\parallelised.py
161
162
163
def vecnptruediv(v, a):
    """Return the true division of a vector and a scalar."""
    return np.asarray(v) / a

vecnpfloordiv(v, a)

Return the floor division of a vector and a scalar.

Source code in vector\parallelised.py
165
166
167
def vecnpfloordiv(v, a):
    """Return the floor division of a vector and a scalar."""
    return np.asarray(v) // a

vecnpmod(v, a)

Return the elementwise mod of a vector and a scalar.

Source code in vector\parallelised.py
169
170
171
def vecnpmod(v, a):
    """Return the elementwise mod of a vector and a scalar."""
    return np.asarray(v) % a