changeset 186:c2f545f32025

move conformity ensurance to separate function
author Jeff Hammel <k0scist@gmail.com>
date Fri, 21 Jul 2017 12:46:55 -0700
parents 411db53cb9fb
children 8aec5ebb2d19
files numerics/__init__.py numerics/conformity.py numerics/filters.py tests/test_conformity.py
diffstat 4 files changed, 64 insertions(+), 5 deletions(-) [+]
line wrap: on
line diff
--- a/numerics/__init__.py	Fri Jul 21 09:37:28 2017 -0700
+++ b/numerics/__init__.py	Fri Jul 21 12:46:55 2017 -0700
@@ -1,4 +1,4 @@
 """
-personal experiments in plotting
+personal experiments in plotting and numerics
 """
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/numerics/conformity.py	Fri Jul 21 12:46:55 2017 -0700
@@ -0,0 +1,19 @@
+"""
+ensures data is what we assert it to be
+"""
+
+
+class NonConformantRowLengths(Exception):
+    """nested arrays have different lengths"""
+
+
+def ensure_row_length(data):
+    """
+    ensures that all rows of array `data` are the same
+    If so, return that length.
+    If not, raise NonConformantArrayLengths
+    """
+    lengths = [len(i) for i in data]
+    if len(set(lengths)) != 1:
+        raise NonConformantRowLengths("Different lengths to array_mean: {}".format(' '.join(lengths)))
+    return lengths.pop()
--- a/numerics/filters.py	Fri Jul 21 09:37:28 2017 -0700
+++ b/numerics/filters.py	Fri Jul 21 12:46:55 2017 -0700
@@ -1,20 +1,24 @@
 """
-filter functions for stats
+filter functions for statistics
 """
 
+from .conformity import ensure_row_lengths
+
 __all__ = ['mean', 'array_mean', 'median']
 
 def mean(data):
+    """return arithemetic mean of a vector"""
+
     return sum(data)/float(len(data))
 
+
 def array_mean(data):
     if not data:
         return []
-    lengths = [len(i) for i in data]
-    if len(set(lengths)) != 1:
-        raise AssertionError("Different lengths to array_mean: {}".format(' '.join(lengths)))
+    ensure_row_lengths(data)
     return [mean(i) for i in zip(*data)]
 
+
 def median(data):
     length = len(data)
     index = length/2
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/test_conformity.py	Fri Jul 21 12:46:55 2017 -0700
@@ -0,0 +1,36 @@
+#!/usr/bin/env python
+
+"""
+test conformity
+"""
+
+import unittest
+from numerics import conformity
+
+class TestConformity(unittest.TestCase):
+    """tests for ensuring data conformity"""
+
+    def test_equal_lengths(self):
+
+        data = [[1,2,3],
+                [4,5,6]
+                [7,8,9]]
+
+        assert conformity.ensure_row_length(data) == 3
+
+    def test_nonequal_lengths(self):
+        data = [[1,2,3],
+                [4,5,6]
+                [7,8,9, 10]  # oops!
+                ]
+
+        e = None
+        try:
+            conformity.ensure_row_length(data)
+        except conformity.NonformantRowLengths as e:
+            pass
+        assert e is not None
+        assert isinstance(e, NonConformantRowLengths)
+
+if __name__ == '__main__':
+    unittest.main()