Chromium Code Reviews| Index: appengine/findit/libs/math/vectors.py |
| diff --git a/appengine/findit/libs/math/vectors.py b/appengine/findit/libs/math/vectors.py |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..62dfe92034b5a47a956eb9200bf51d748464a3b2 |
| --- /dev/null |
| +++ b/appengine/findit/libs/math/vectors.py |
| @@ -0,0 +1,41 @@ |
| +# Copyright 2016 The Chromium Authors. All rights reserved. |
| +# Use of this source code is governed by a BSD-style license that can be |
| +# found in the LICENSE file. |
| + |
| +import math |
| +import numpy as np |
| + |
| +def vsum(xs, shape=None): |
| + """Accurate summation of a list of vectors. |
| + |
| + This function is like ``math.fsum`` except operating over collections |
| + of vectors rather than collections of scalars. |
| + |
| + Args: |
| + xs (list of np.ndarray of float): The vectors to add up. |
| + shape (tuple of int): the shape of the vectors. Optional. |
| + |
| + Returns: |
| + Returns an ``np.ndarray`` if all is well, otherwise returns |
| + ``None``. The situations where all is not well (and so we return |
| + ``None``) are: (1) ``xs`` is empty and ``shape`` is not provided; |
| + (2) a ``shape`` is provided but does not match the actual shape of |
| + the vectors; (3) not all the vectors in the list have the same shape. |
| + """ |
| + if shape is None: |
| + if not xs: |
| + return None |
| + |
| + shape = xs[0].shape |
| + |
| + # TODO(wrengr): reimplement this in C, inling CPython's implementation |
|
Martin Barbella
2016/12/02 19:52:37
FWIW, I don't think that this is a worthwhile goal
Sharu Jiang
2016/12/02 22:17:51
+1
|
| + # of Shewchuk's algorithm, so that we can compute the final vector in |
| + # in a single pass over the list of vectors, rather than doing this hack. |
| + # <http://svn.python.org/view/python/trunk/Modules/mathmodule.c?view=markup> |
| + total = np.zeros(shape) |
| + it = np.nditer(total, flags=['multi_index'], op_flags=['writeonly']) |
| + while not it.finished: |
| + it[0] = math.fsum(x[it.multi_index] for x in xs) |
| + it.iternext() |
| + |
| + return total |