From 31d2f3cfd75520f2bdca72909d9514a838745e49 Mon Sep 17 00:00:00 2001
From: lodenthal <lodenthal@uni-bielefeld.de>
Date: Fri, 15 Dec 2017 10:16:02 +0300
Subject: [PATCH] did things on todo list

---
 navipy/comparing/__init__.py  | 130 ++++++++++---------------
 navipy/comparing/test.py      | 107 ++++++++++++++-------
 navipy/database/__init__.py   |  53 +++++-----
 navipy/processing/__init__.py | 175 ++++++++++++++++++++++------------
 navipy/processing/test.py     | 111 ++++++++++-----------
 5 files changed, 321 insertions(+), 255 deletions(-)

diff --git a/navipy/comparing/__init__.py b/navipy/comparing/__init__.py
index b033fd1..7b25390 100644
--- a/navipy/comparing/__init__.py
+++ b/navipy/comparing/__init__.py
@@ -5,60 +5,11 @@ memorised places.
 """
 import numpy as np
 from navipy.processing.tools import is_ibpc, is_obpc
-
-
-def is_numeric_array(array):
-    """Checks if the dtype of the array is numeric.
-
-    Booleans, unsigned integer, signed integer, floats and complex are
-    considered numeric.
-
-    Parameters
-    ----------
-    array : `numpy.ndarray`-like
-        The array to check.
-
-    Returns
-    -------
-    is_numeric : `bool`
-        True if it is a recognized numerical and False if object or
-        string.
-    """
-    numerical_dtype_kinds = {'b',  # boolean
-                             'u',  # unsigned integer
-                             'i',  # signed integer
-                             'f',  # floats
-                             'c'}  # complex
-    try:
-        return array.dtype.kind in numerical_dtype_kinds
-    except AttributeError:
-        # in case it's not a numpy array it will probably have no dtype.
-        return np.asarray(array).dtype.kind in numerical_dtype_kinds
-
-
-def check_scene(scene):
-    if is_ibpc(scene):
-        #  print("normal")
-        assert is_numeric_array(scene)  # np.isscalar(scene)
-        assert ~np.any(np.isnan(scene))
-        assert len(scene.shape) == 4
-        assert (scene.shape[1] > 0)
-        assert (scene.shape[0] > 0)
-        assert (scene.shape[2] == 4)
-        assert (scene.shape[3] == 1)
-        # assert ~(np.any(np.isNone(scene)))
-
-    elif is_obpc(scene):
-        assert is_numeric_array(scene)  # np.isscalar(scene)
-        assert ~np.any(np.isnan(scene))
-        assert len(scene.shape) == 3
-        assert ~(scene.shape[1] <= 0)
-        assert ~(scene.shape[0] <= 0)
-        assert (scene.shape[2] == 1)
+from navipy.processing.__init__ import check_scene
 
 
 def simple_imagediff(current, memory):
-    """Compute the root mean square difference between
+    """Compute the difference between
 the current and memorised place code
 
     :param current: current place code
@@ -70,12 +21,13 @@ the current and memorised place code
            Current opinion in neurobiology
 
     """
-    assert isinstance(current, np.ndarray),\
-        'current place code should be a numpy array'
-    assert isinstance(memory, np.ndarray),\
-        'memory place code should be a numpy array'
-    assert np.all(current.shape == memory.shape),\
-        'memory and current place code should have the same shape'
+    if not isinstance(current, np.ndarray):
+        raise TypeError('current place code should be a numpy array')
+    if not isinstance(memory, np.ndarray):
+        raise TypeError('memory place code should be a numpy array')
+    if not np.all(current.shape == memory.shape):
+        raise Exception('memory and current place code should\
+                       have the same shape')
     check_scene(current)
     check_scene(memory)
     diff = current - memory
@@ -100,15 +52,8 @@ the current and memorised place code
            Current opinion in neurobiology
 
     """
-    assert isinstance(current, np.ndarray),\
-        'current place code should be a numpy array'
-    assert isinstance(memory, np.ndarray),\
-        'memory place code should be a numpy array'
-    assert np.all(current.shape == memory.shape),\
-        'memory and current place code should have the same shape'
-    check_scene(current)
-    check_scene(memory)
-    diff = np.power(current - memory, 2)
+    simple_diff = simple_imagediff(current, memory)
+    diff = np.power(simple_diff, 2)
     if is_ibpc(current):
         return np.sqrt(diff.mean(axis=0).mean(axis=0))  # 1
     elif is_obpc(current):
@@ -131,10 +76,12 @@ the current and memorised place code.
     ..note: assume that the image is periodic along the x axis
            (the left-right axis)
     """
-    assert is_ibpc(current),\
-        'The current and memory place code should be image based'
-    assert is_ibpc(memory),\
-        'The current and memory place code should be image based'
+    if not is_ibpc(current):
+        raise TypeError('The current and memory place code\
+                       should be image based')
+    if not is_ibpc(memory):
+        raise TypeError('The current and memory place code\
+                       should be image based')
     check_scene(current)
     check_scene(memory)
     ridf = np.zeros((current.shape[1], current.shape[2]))
@@ -145,11 +92,36 @@ the current and memorised place code.
 
 
 def diff_optic_flow(current, memory):
-    print("shape of current", current.shape)
-    assert is_ibpc(current),\
-        'The current and memory place code should be image based'
-    assert is_ibpc(memory),\
-        'The current and memory place code should be image based'
+    """Computes the direction of motion from current
+to memory by using the optic flow under the
+constrain that the brightness is constant, (small movement),
+using a taylor expansion and solving the equation:
+0=I_t+\delta I*<u,v> or I_x+I_y+I_t=0
+
+afterwards the aperture problem is solved by a
+Matrix equation Ax=b, where x=(u,v) and
+A=(I_x,I_y) and b = I_t
+
+    :param current: current place code
+    :param memory: memorised place code
+    :returns: a directional vectors
+    :rtype: (np.ndarray)
+
+    ..ref: aperture problem:
+           Shimojo, Shinsuke, Gerald H. Silverman, and Ken Nakayama:
+           "Occlusion and the solution to the aperture problem for motion."
+            Vision research 29.5 (1989): 619-626.
+           optic flow:
+           Horn, Berthold KP, and Brian G. Schunck.:
+           "Determining optical flow."
+           Artificial intelligence 17.1-3 (1981): 185-203.
+    """
+    if not is_ibpc(current):
+        raise TypeError('The current and memory place code\
+                       should be image based')
+    if not is_ibpc(memory):
+        raise TypeError('The current and memory place code\
+                       should be image based')
     check_scene(current)
     check_scene(memory)
     currroll = np.roll(current, 1, axis=1)
@@ -160,10 +132,10 @@ def diff_optic_flow(current, memory):
     dx = np.reshape(dx, (np.prod(dx.shape), 1))
     di = current-memory
     di = np.reshape(di, (np.prod(di.shape), 1))
-    A = np.column_stack([dy, dx])
-    ATA = np.dot(np.transpose(A), A)
-    b = np.dot(np.transpose(A), di)
-    res = np.linalg.solve(ATA, b)
+    a_matrix = np.column_stack([dy, dx])
+    a_matrix_sqr = np.dot(np.transpose(a_matrix), a_matrix)
+    b_vector = np.dot(np.transpose(a_matrix), di)
+    res = np.linalg.solve(a_matrix_sqr, b_vector)
     return res
 
 
diff --git a/navipy/comparing/test.py b/navipy/comparing/test.py
index 0b4cf2f..e940814 100644
--- a/navipy/comparing/test.py
+++ b/navipy/comparing/test.py
@@ -51,10 +51,13 @@ class TestCase(unittest.TestCase):
         curr3 = np.array(curr3)
         curr4 = np.zeros((3, 4, 5, 0))
 
-        for s in [curr2, curr3, curr4]:  # put useless stuff here
-            with self.assertRaises(Exception) as cm:
-                comparing.imagediff(s, mem)
-            print("wanted exception occured", cm.exception)
+        # put useless stuff here
+        with self.assertRaises(ValueError):
+            comparing.imagediff(curr2, mem)
+        with self.assertRaises(Exception):
+            comparing.imagediff(curr3, mem)
+        with self.assertRaises(Exception):
+            comparing.imagediff(curr4, mem)
 
         # should be working -> check if result is correct
         for s in [curr]:
@@ -74,10 +77,12 @@ class TestCase(unittest.TestCase):
         mem3 = np.array(mem3)
         mem4 = np.zeros((3, 4, 5, 0))
 
-        for s in [mem2, mem3, mem4]:  # put useless stuff here
-            with self.assertRaises(Exception) as cm:
-                comparing.imagediff(curr, s)
-            print("wanted exception occured", cm.exception)
+        with self.assertRaises(ValueError):
+            comparing.imagediff(curr, mem2)
+        with self.assertRaises(Exception):
+            comparing.imagediff(curr, mem3)
+        with self.assertRaises(Exception):
+            comparing.imagediff(curr, mem4)
 
         # should be working -> check if result is correct
         for s in [mem]:
@@ -97,10 +102,12 @@ class TestCase(unittest.TestCase):
         curr3 = np.array(curr3)
         curr4 = np.zeros((3, 4, 5, 0))
 
-        for s in [curr2, curr3, curr4]:  # put useless stuff here
-            with self.assertRaises(Exception) as cm:
-                comparing.rot_imagediff(s, mem)
-            print("wanted exception occured", cm.exception)
+        with self.assertRaises(ValueError):
+            comparing.rot_imagediff(curr2, mem)
+        with self.assertRaises(Exception):
+            comparing.rot_imagediff(curr3, mem)
+        with self.assertRaises(Exception):
+            comparing.rot_imagediff(curr4, mem)
 
         # should be working -> check if result is correct
         for s in [curr]:
@@ -120,10 +127,12 @@ class TestCase(unittest.TestCase):
         mem3 = np.array(mem3)
         mem4 = np.zeros((3, 4, 5, 0))
 
-        for s in [mem2, mem3, mem4]:  # put useless stuff here
-            with self.assertRaises(Exception) as cm:
-                comparing.rot_imagediff(curr, s)
-            print("wanted exception occured", cm.exception)
+        with self.assertRaises(ValueError):
+            comparing.rot_imagediff(curr, mem2)
+        with self.assertRaises(Exception):
+            comparing.rot_imagediff(curr, mem3)
+        with self.assertRaises(Exception):
+            comparing.rot_imagediff(curr, mem4)
 
         # should be working -> check if result is correct
         for s in [mem]:
@@ -143,10 +152,12 @@ class TestCase(unittest.TestCase):
         curr3 = np.array(curr3)
         curr4 = np.zeros((3, 4, 5, 0))
 
-        for s in [curr2, curr3, curr4]:  # put useless stuff here
-            with self.assertRaises(Exception) as cm:
-                comparing.simple_imagediff(s, mem)
-            print("wanted exception occured", cm.exception)
+        with self.assertRaises(ValueError):
+            comparing.simple_imagediff(curr2, mem)
+        with self.assertRaises(Exception):
+            comparing.simple_imagediff(curr3, mem)
+        with self.assertRaises(Exception):
+            comparing.simple_imagediff(curr4, mem)
 
         # should be working -> check if result is correct
         for s in [curr]:
@@ -161,17 +172,19 @@ class TestCase(unittest.TestCase):
     def test_simple_imagediff_mem(self):
         curr = processing.scene(self.mydb, rowid=1)
         mem = processing.scene(self.mydb, rowid=2)
-        curr2 = curr.copy()
-        curr2[3, 5, 2, 0] = np.nan
-        curr3 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
-        curr3 = [curr3, curr3, curr3]
-        curr3 = np.array(curr3)
-        curr4 = np.zeros((3, 4, 5, 0))
+        mem2 = curr.copy()
+        mem2[3, 5, 2, 0] = np.nan
+        mem3 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
+        mem3 = [mem3, mem3, mem3]
+        mem3 = np.array(mem3)
+        mem4 = np.zeros((3, 4, 5, 0))
 
-        for s in [curr2, curr3, curr4]:  # put useless stuff here
-            with self.assertRaises(Exception) as cm:
-                comparing.simple_imagediff(s, mem)
-            print("wanted exception occured", cm.exception)
+        with self.assertRaises(ValueError):
+            comparing.simple_imagediff(curr, mem2)
+        with self.assertRaises(Exception):
+            comparing.simple_imagediff(curr, mem3)
+        with self.assertRaises(Exception):
+            comparing.simple_imagediff(curr, mem4)
 
         # should be working -> check if result is correct
         for s in [mem]:
@@ -193,10 +206,12 @@ class TestCase(unittest.TestCase):
         mem3 = np.array(mem3)
         mem4 = np.zeros((3, 4, 5, 0))
 
-        for s in [mem2, mem3, mem4]:  # put useless stuff here
-            with self.assertRaises(Exception) as cm:
-                comparing.diff_optic_flow(curr, s)
-            print("wanted exception occured", cm.exception)
+        with self.assertRaises(ValueError):
+            comparing.diff_optic_flow(curr, mem2)
+        with self.assertRaises(Exception):
+            comparing.diff_optic_flow(curr, mem3)
+        with self.assertRaises(Exception):
+            comparing.diff_optic_flow(curr, mem4)
 
         # should be working -> check if result is correct
         for s in [mem]:
@@ -205,6 +220,30 @@ class TestCase(unittest.TestCase):
             self.assertFalse(np.any(np.isnan(vec)))
             self.assertTrue(is_numeric_array(vec))
 
+    def test_diff_optic_flow_curr(self):
+        curr = processing.scene(self.mydb, rowid=1)
+        mem = processing.scene(self.mydb, rowid=2)
+        curr2 = curr.copy()
+        curr2[3, 5, 2, 0] = np.nan
+        curr3 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
+        curr3 = [curr3, curr3, curr3]
+        curr3 = np.array(curr3)
+        curr4 = np.zeros((3, 4, 5, 0))
+
+        with self.assertRaises(ValueError):
+            comparing.diff_optic_flow(curr2, mem)
+        with self.assertRaises(Exception):
+            comparing.diff_optic_flow(curr3, mem)
+        with self.assertRaises(Exception):
+            comparing.diff_optic_flow(curr4, mem)
+
+        # should be working -> check if result is correct
+        for s in [mem]:
+            vec = comparing.diff_optic_flow(s, curr)
+            self.assertFalse(vec.shape[1] == (1, 2))
+            self.assertFalse(np.any(np.isnan(vec)))
+            self.assertTrue(is_numeric_array(vec))
+
 
 if __name__ == '__main__':
     unittest.main()
diff --git a/navipy/database/__init__.py b/navipy/database/__init__.py
index 673bc45..b69c6a6 100644
--- a/navipy/database/__init__.py
+++ b/navipy/database/__init__.py
@@ -116,8 +116,10 @@ It creates three sql table on initialisation.
 
     def __init__(self, filename, channels=['R', 'G', 'B', 'D']):
         """Initialisation of the database """
-        assert isinstance(filename, str), 'filename should be a string'
-        assert isinstance(channels, list), 'nb_channel should be an integer'
+        if not isinstance(filename, str):
+            raise TypeError('filename should be a string')
+        if not isinstance(channels, list):
+            raise TypeError('nb_channel should be a list')
         self.filename = filename
         self.channels = channels
         self.normalisation_columns = list()
@@ -146,9 +148,9 @@ It creates three sql table on initialisation.
                 filename, detect_types=sqlite3.PARSE_DECLTYPES)
             self.db_cursor = self.db.cursor()
             for tablename, _ in self.tablecolumns.items():
-                assert self.table_exist(tablename),\
-                    '{} does not contain a table named {}'.format(
-                        filename, tablename)
+                if not self.table_exist(tablename):
+                    raise Exception('{} does not contain a table named {}'.format(
+                        filename, tablename))
         elif self.create():
             # Create database
             self.db = sqlite3.connect(
@@ -173,7 +175,8 @@ It creates three sql table on initialisation.
         self.viewing_directions[..., 1] = ma
 
     def table_exist(self, tablename):
-        assert isinstance(tablename, str), 'tablename should be a string'
+        if not isinstance(tablename, str):
+            raise TypeError('tablename should be a string')
         self.db_cursor.execute(
             """
             SELECT count(*)
@@ -305,8 +308,8 @@ database
         return posorient
 
     def read_posorient(self, posorient=None, rowid=None):
-        assert (posorient is None) or (rowid is None),\
-            'posorient and rowid can not be both None'
+        if (posorient is None) and (rowid is None):
+            raise ValueError('posorient and rowid can not be both None')
         if posorient is not None:
             rowid = self.get_posid(posorient)
         # Read images
@@ -332,8 +335,8 @@ database
         :returns: an image
         :rtype: numpy.ndarray
         """
-        assert (posorient is None) or (rowid is None),\
-            'posorient and rowid can not be both None'
+        if (posorient is None) and (rowid is None):
+            raise ValueError('posorient and rowid can not be both None')
         if posorient is not None:
             rowid = self.get_posid(posorient)
         # Read images
@@ -353,19 +356,19 @@ database
                 FROM {}
                 WHERE (rowid={})
                 """.format(tablename, rowid), self.db)
-        assert cmaxminrange.shape[0] == 1,\
-            'Error while reading normalisation factors'
+        if not cmaxminrange.shape[0] == 1:
+            raise Exception('Error while reading normalisation factors')
         cmaxminrange = cmaxminrange.iloc[0, :]
         return self.denormalise_image(image, cmaxminrange)
 
     def denormalise_image(self, image, cmaxminrange):
-        assert len(image.shape) == 3,\
-            'image should be 3D array'
-        assert image.shape[2] == len(self.channels),\
-            'image does not have the required number of channels {}'.format(
-                len(self.channels))
-        assert isinstance(cmaxminrange, pd.Series),\
-            'cmaxminrange should be a pandas Series'
+        if not len(image.shape) == 3:
+            raise Exception('image should be 3D array')
+        if not image.shape[2] == len(self.channels):
+            raise Exception('image does not have the required number of channels {}'.format(
+                len(self.channels)))
+        if not isinstance(cmaxminrange, pd.Series):
+            raise TypeError('cmaxminrange should be a pandas Series')
         denormed_im = np.zeros(image.shape, dtype=np.float)
         maxval_nim = np.iinfo(image.dtype).max
         #
@@ -378,8 +381,8 @@ database
             cimage *= crange
             cimage += cmin
             denormed_im[:, :, chan_i] = cimage
-            assert np.max(cimage) == cmax,\
-                'denormalisation failed {}!={}'.format(np.max(cimage), cmax)
+            if not np.max(cimage) == cmax:
+                raise Exception('denormalisation failed {}!={}'.format(np.max(cimage), cmax))
         return denormed_im
 
 
@@ -415,10 +418,10 @@ class DataBaseSave(DataBase):
         self.insert_replace(tablename, params)
 
     def insert_replace(self, tablename, params):
-        assert isinstance(tablename, str),\
-            'table are named by string'
-        assert isinstance(params, dict),\
-            'params should be dictionary columns:val'
+        if not isinstance(tablename, str):
+            raise TypeError('table are named by string')
+        if not isinstance(params, dict):
+            raise TypeError('params should be dictionary columns:val')
         params_list = list()
         columns_str = ''
         for key, val in params.items():
diff --git a/navipy/processing/__init__.py b/navipy/processing/__init__.py
index 1d2c1b3..b552906 100644
--- a/navipy/processing/__init__.py
+++ b/navipy/processing/__init__.py
@@ -110,63 +110,96 @@ def scene(database, posorient=None, rowid=None):
     # where to check if db is okay? in database?
 
     if posorient is not None:
-        assert isinstance(posorient, pd.Series),\
-            'posorient should be a pandas Series'
-        assert ~posorient.empty, 'position must not be empty'
-        assert ('x' in posorient.index),\
-            'missing index x'
-        assert ('y' in posorient.index), 'missing index y'
-        assert 'z' in posorient.index, 'missing index z'
-        assert 'alpha_0' in posorient.index, 'missing index alpha_0'
-        assert 'alpha_1' in posorient.index, 'missing index alpha_1'
-        assert 'alpha_2' in posorient.index, 'missing index alpha_2'
-        assert ~np.any(np.isnan(posorient))
+        if not isinstance(posorient, pd.Series):
+            raise TypeError('posorient should be a pandas Series')
+        if posorient.empty:
+            raise Exception('position must not be empty')
+        if 'x' not in posorient.index:
+            raise ValueError('missing index x')
+        if 'y' not in posorient.index:
+            raise ValueError('missing index y')
+        if 'z' not in posorient.index:
+            raise ValueError('missing index z')
+        if 'alpha_0' not in posorient.index:
+            raise ValueError('missing index alpha_0')
+        if 'alpha_1' not in posorient.index:
+            raise ValueError('missing index alpha_1')
+        if 'alpha_2' not in posorient.index:
+            raise ValueError('missing index alpha_2')
+        if not ~np.any(np.isnan(posorient)):
+            raise ValueError('posorient must not contain nan')
     if rowid is not None:
-        assert rowid > 0
-        assert isinstance(rowid, int)
-        assert rowid is not None
-        assert rowid is not np.nan
+        if not isinstance(rowid, int):
+            raise TypeError('rowid must be of type integer')
+        if rowid <= 0:
+            raise ValueError('rowid must be greater zero')
+        if rowid is np.nan:
+            raise ValueError('rowid must not be nan')
         # assert rowid in database.index#??
-    assert rowid is not None or posorient is not None
-    scene = database.read_image(posorient=posorient,
-                                rowid=rowid
-                                )
-    # print(np.array(scene).shape)
-    scene = scene[..., np.newaxis]
-    # print(np.array(scene).shape)
-    return scene
+    if rowid is not None or posorient is not None:
+        scene = database.read_image(posorient=posorient,
+                                    rowid=rowid)
+        # print(np.array(scene).shape)
+        scene = scene[..., np.newaxis]
+        # print(np.array(scene).shape)
+        return scene
+    else:
+        raise ValueError('either rowid or posoriend must be given')
 
 
 def check_scene(scene):
     if is_ibpc(scene):
         #  print("normal")
-        assert is_numeric_array(scene)  # np.isscalar(scene)
-        assert ~np.any(np.isnan(scene))
-        assert len(scene.shape) == 4
-        assert (scene.shape[1] > 0)
-        assert (scene.shape[0] > 0)
-        assert (scene.shape[2] == 4)
-        assert (scene.shape[3] == 1)
+        if not is_numeric_array(scene):
+            raise TypeError('scene is of non numeric type')
+        if not ~np.any(np.isnan(scene)):
+            raise ValueError('scene contains nans')
+        if not len(scene.shape) == 4:
+            raise Exception('scene has wrong shape, must have 4 dimensions')
+        if not (scene.shape[1] > 0):
+            raise Exception('scenes first dimension is empty')
+        if not (scene.shape[0] > 0):
+            raise Exception('scenes second dimension is empty')
+        if not (scene.shape[2] == 4):
+            raise Exception('3rd dimension of scene must be four')
+        if not (scene.shape[3] == 1):
+            raise Exception('4rd dimension of scene must be one')
         # assert ~(np.any(np.isNone(scene)))
+        return True
 
     elif is_obpc(scene):
-        assert is_numeric_array(scene)  # np.isscalar(scene)
-        assert ~np.any(np.isnan(scene))
-        assert len(scene.shape) == 3
-        assert ~(scene.shape[1] <= 0)
-        assert ~(scene.shape[0] <= 0)
-        assert (scene.shape[2] == 4)
-        assert (scene.shape[3] == 1)
+        if not is_numeric_array(scene):
+            raise TypeError('scene is of non numeric type')
+        if not ~np.any(np.isnan(scene)):
+            raise ValueError('scene contains nans')
+        if not len(scene.shape) == 3:
+            raise Exception('scene has wrong shape, must have 4 dimensions')
+        if not ~(scene.shape[1] <= 0):
+            raise Exception('scenes first dimension is empty')
+        if not ~(scene.shape[0] <= 0):
+            raise Exception('scenes second dimension is empty')
+        if not (scene.shape[2] == 4):
+            raise Exception('3rd dimension of scene must be four')
+        if not (scene.shape[3] == 1):
+            raise Exception('4rd dimension of scene must be one')
         # assert ~(np.any(np.isNone(scene)))
+        return True
 
 
 def check_viewing_direction(viewing_direction):
-    assert is_numeric_array(viewing_direction)
-    assert ~np.any(np.isnan(viewing_direction))
-    assert len(viewing_direction.shape) == 3
-    assert (viewing_direction.shape[1] > 0)
-    assert (viewing_direction.shape[0] > 0)
-    assert (viewing_direction.shape[2] == 2)
+    if not is_numeric_array(viewing_direction):
+        raise TypeError('viewing direction is of non numeric type')
+    if not ~np.any(np.isnan(viewing_direction)):
+        raise ValueError('viewing direction contains nans')
+    if not len(viewing_direction.shape) == 3:
+        raise Exception('viewing direction must have 3 dimensions')
+    if not (viewing_direction.shape[1] > 0):
+        raise Exception('viewing direction has empty second dimension')
+    if not (viewing_direction.shape[0] > 0):
+        raise Exception('viewing direction has empty first dimension')
+    if not (viewing_direction.shape[2] == 2):
+        raise Exception(' 3rd dimension of viewing direction must equal 2')
+    return True
 
 
 def skyline(scene):
@@ -181,10 +214,9 @@ def skyline(scene):
     .. plot:: example/processing/skyline.py
 
     """
-    assert is_ibpc(scene),\
-        'scene should be image based to compute a skyline'
+    if not is_ibpc(scene):
+        raise TypeError('scene should be image based to compute a skyline')
     check_scene(scene)
-
     skyline = scene.mean(axis=__ibpc_indeces__['elevation'])
     return skyline[np.newaxis, :]
 
@@ -212,9 +244,13 @@ and minimum of the local image intensity
 
     """
     check_scene(scene)
-    assert is_ibpc(scene), \
-        'scene should be image based to compute the michelson constrast'
-    assert size >= 2 and size <= 5  # in range(2,6)
+    if not is_ibpc(scene):
+        raise TypeError('scene should be image based\
+                       to compute the michelson constrast')
+    if not isinstance(size, int):
+        raise TypeError('size must be integer')
+    if (size < 2 or size > 5):
+        raise ValueError('size must be between 2 and 5')
     contrast = np.zeros_like(scene)
     for channel in range(scene.shape[__ibpc_indeces__['channel']]):
         i_max = maximum_filter(scene[..., channel, 0],
@@ -240,10 +276,17 @@ and minimum of the local image intensity in the michelson-contrast.
 
     """
     check_scene(scene)
-    assert contrast_size >= 2 and contrast_size <= 5  # in range(2,6)
-    assert distance_channel in [0, 1, 2, 3]
-    assert is_ibpc(scene), \
-        'scene should be image based to compute the contrast weighted nearness'
+    if not isinstance(contrast_size, int):
+        raise TypeError('constrast size must be of type integer')
+    if not isinstance(distance_channel, int):
+        raise TypeError('distance channel must be of type integer')
+    if contrast_size not in range(2, 6):
+        raise ValueError('contrast size out of range')
+    if distance_channel not in range(4):
+        raise ValueError('distance channel out of range')
+    if not is_ibpc(scene):
+        raise TypeError('scene should be image based to\
+                       compute the contrast weighted nearness')
     contrast = michelson_contrast(scene, size=contrast_size)
     distance = scene[..., distance_channel, 0]
     distance = distance[..., np.newaxis, np.newaxis]
@@ -277,13 +320,17 @@ def pcv(place_code, viewing_directions):
 
     check_scene(place_code)
     check_viewing_direction(viewing_directions)
-    assert place_code.shape[0] == viewing_directions.shape[0]
-    assert place_code.shape[1] == viewing_directions.shape[1]
-    assert isinstance(viewing_directions, np.ndarray), \
-        'viewing_directions should be a numpy array'
-    assert place_code.shape[component_dim] == 1, \
-        'the last dimension ({}) of the place-code should be 1'.format(
-        place_code.shape[component_dim])
+    if not place_code.shape[0] == viewing_directions.shape[0]:
+        raise Exception('dimensions of place code and viewing\
+                       direction do not match')
+    if not place_code.shape[1] == viewing_directions.shape[1]:
+        raise Exception('dimensions of place code and viewing\
+                       direction do not match')
+    if not isinstance(viewing_directions, np.ndarray):
+        raise TypeError('viewing_directions should be a numpy array')
+    if not place_code.shape[component_dim] == 1:
+        raise Exception('the last dimension ({}) of the place-code\
+                       should be 1'.format(place_code.shape[component_dim]))
     elevation = viewing_directions[..., __spherical_indeces__['elevation']]
     azimuth = viewing_directions[..., __spherical_indeces__['azimuth']]
     unscaled_lv = spherical_to_cartesian(elevation, azimuth, radius=1)
@@ -313,8 +360,12 @@ def apcv(place_code, viewing_directions):
     """
     check_scene(place_code)
     check_viewing_direction(viewing_directions)
-    assert place_code.shape[0] == viewing_directions.shape[0]
-    assert place_code.shape[1] == viewing_directions.shape[1]
+    if not place_code.shape[0] == viewing_directions.shape[0]:
+        raise Exception('dimensions of place code and viewing\
+                      direction do not match')
+    if not place_code.shape[1] == viewing_directions.shape[1]:
+        raise Exception('dimensions of place code and viewing\
+                       direction do not match')
     scaled_lv = pcv(place_code, viewing_directions)
     if is_ibpc(place_code):
         return (scaled_lv.sum(axis=0).sum(axis=0))[np.newaxis, np.newaxis, ...]
diff --git a/navipy/processing/test.py b/navipy/processing/test.py
index 84b9bfb..94d2778 100644
--- a/navipy/processing/test.py
+++ b/navipy/processing/test.py
@@ -2,7 +2,7 @@ import unittest
 import sqlite3
 import numpy as np
 import pandas as pd
-from navipy.database import database
+import navipy.database as database
 import navipy.processing as processing
 import pkg_resources
 
@@ -114,10 +114,8 @@ class TestCase(unittest.TestCase):
         posorient2.alpha_0 = posorient.alpha_0
         posorient2.alpha_1 = posorient.alpha_1
         posorient2.alpha_2 = posorient.alpha_2
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(Exception):
             image = processing.scene(self.mydb, posorient=posorient2)
-        # print("missing column")
-        print(cm.exception)
 
         # incorrect case None
         posorient2 = pd.Series(index=['x', 'y', 'z',
@@ -128,9 +126,8 @@ class TestCase(unittest.TestCase):
         posorient2.alpha_0 = posorient.alpha_0
         posorient2.alpha_1 = posorient.alpha_1
         posorient2.alpha_2 = posorient.alpha_2
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(ValueError):
             image = processing.scene(self.mydb, posorient=posorient2)
-        print(cm.exception)
 
         # incorrect case nan
         posorient2 = pd.Series(index=['x', 'y', 'z',
@@ -141,9 +138,8 @@ class TestCase(unittest.TestCase):
         posorient2.alpha_0 = posorient.alpha_0
         posorient2.alpha_1 = posorient.alpha_1
         posorient2.alpha_2 = posorient.alpha_2
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(ValueError):
             image = processing.scene(self.mydb, posorient=posorient2)
-        print(cm.exception)
 
         # incorrect case no pandas series but dict
         posorient2 = {}
@@ -153,17 +149,15 @@ class TestCase(unittest.TestCase):
         posorient2['alpha_0'] = posorient.alpha_0
         posorient2['alpha_1'] = posorient.alpha_1
         posorient2['alpha_2'] = posorient.alpha_2
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(TypeError):
             image = processing.scene(self.mydb, posorient=posorient2)
-        print(cm.exception)
 
         # not working case empty
         posorient2 = pd.Series(index=['x', 'y', 'z',
                                       'alpha_0', 'alpha_1', 'alpha_2'])
 
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(Exception):
             image = processing.scene(self.mydb, posorient=posorient2)
-        print(cm.exception)
 
     """
     def test_db(self):
@@ -201,10 +195,13 @@ class TestCase(unittest.TestCase):
         scene3 = np.array(scene3)
         scene4 = np.zeros((3, 4, 5, 0))
 
-        for s in [scene2, scene3, scene4]:  # put useless stuff here
-            with self.assertRaises(Exception) as cm:
-                processing.skyline(s)
-            print("wanted exception occured", cm.exception)
+        # put useless stuff here
+        with self.assertRaises(ValueError):
+            processing.skyline(scene2)
+        with self.assertRaises(TypeError):
+            processing.skyline(scene3)
+        with self.assertRaises(Exception):
+            processing.skyline(scene4)
 
         # should be working -> check if result(skyline) is correct
         for s in [scene]:
@@ -222,13 +219,18 @@ class TestCase(unittest.TestCase):
         # print("test_id")
         # check for wrong cases
         # my_scene = processing.scene(self.mydb, rowid=-2)
-        for rowid in [0, 't', -2, 4.5, np.nan, None]:
-
-            with self.assertRaises(Exception) as cm:
+        for rowid in [0, -2]:
+            with self.assertRaises(ValueError):
                 # print("rowid",rowid)
                 processing.scene(self.mydb, rowid=rowid)
-            the_exception = cm.exception
-            print("error occured", the_exception)
+        with self.assertRaises(TypeError):
+            processing.scene(self.mydb, rowid='T')
+        with self.assertRaises(ValueError):
+            processing.scene(self.mydb, rowid=None)
+        with self.assertRaises(TypeError):
+            processing.scene(self.mydb, rowid=np.nan)
+        with self.assertRaises(TypeError):
+            processing.scene(self.mydb, rowid=4.5)
 
         for rowid in [1, 2, 3, 4, 5]:
             image = processing.scene(self.mydb, rowid=rowid)
@@ -246,11 +248,13 @@ class TestCase(unittest.TestCase):
         scene = processing.scene(self.mydb, rowid=1)
         # print("scene sizejhghghhg",scene.shape)
         # should not be working
-        for d in [-1, 'g', None, np.nan, 8.4]:
-            with self.assertRaises(Exception) as cm:
+        for d in ['g', None, np.nan, 8.4]:
+            with self.assertRaises(TypeError):
                 processing.contrast_weighted_nearness(scene,
                                                       distance_channel=d)
-            print("wanted error occured", cm.exception)
+        with self.assertRaises(ValueError):
+                processing.contrast_weighted_nearness(scene,
+                                                      distance_channel=-1)
 
         # should work
         for d in [0, 1, 2, 3]:
@@ -287,19 +291,25 @@ class TestCase(unittest.TestCase):
         scene3 = [scene3, scene3, scene3]
         scene3 = np.array(scene3)
         scene4 = np.zeros((3, 4, 5, 0))
-        for s in [scene2, scene3, scene4]:
-            with self.assertRaises(Exception) as cm:
-                contrast = processing.contrast_weighted_nearness(scene)
-            print("wanted excption occured", cm.exception)
+        with self.assertRaises(ValueError):
+            contrast = processing.contrast_weighted_nearness(scene2)
+        with self.assertRaises(ValueError):
+            contrast = processing.contrast_weighted_nearness(scene3)
+        with self.assertRaises(Exception):
+            contrast = processing.contrast_weighted_nearness(scene4)
 
     def test_contr_weight_contrast(self):
         scene = processing.scene(self.mydb, rowid=1)
-        for size in [8, 1, 0, -4, 9.4, 'g', None, np.nan]:
-            with self.assertRaises(Exception) as cm:
+        for size in [9.4, 'g', None, np.nan]:
+            with self.assertRaises(TypeError):
+                contrast = \
+                    processing.contrast_weighted_nearness(scene,
+                                                          contrast_size=size)
+        for size in [8, 1, 0, -4]:
+            with self.assertRaises(ValueError):
                 contrast = \
                     processing.contrast_weighted_nearness(scene,
                                                           contrast_size=size)
-            print("wanted error occured", cm.exception)
 
         # working cases
         for size in [2, 3, 4, 5]:
@@ -336,34 +346,29 @@ class TestCase(unittest.TestCase):
 
         # not working cases doesnt match with shape of place code
         testdirection = np.zeros((2, 4, 2))
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(Exception):
             my_pcv = processing.pcv(my_scene, testdirection)
-        print("wanted exception occured", cm.exception)
 
         # not working cases wrong last dimension
         testdirection = np.zeros((180, 360, 1))
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(Exception):
             my_pcv = processing.pcv(my_scene, testdirection)
-        print("wanted exception occured", cm.exception)
 
         # not working cases too many dimensions
         testdirection = np.zeros((180, 360, 2, 4))
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(Exception):
             my_pcv = processing.pcv(my_scene, testdirection)
-        print("wanted exception occured", cm.exception)
 
         # not working cases empty
         testdirection = np.zeros(())
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(Exception):
             my_pcv = processing.pcv(my_scene, testdirection)
-        print("wanted exception occured", cm.exception)
 
         # not working cases nans
         testdirection = np.zeros((180, 360, 2, 4))
         testdirection[2, 3, 0] = np.nan
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(ValueError):
             my_pcv = processing.pcv(my_scene, testdirection)
-        print("wanted exception occured", cm.exception)
 
     def test_apcv(self):
         # working case
@@ -373,7 +378,6 @@ class TestCase(unittest.TestCase):
         directions = self.mydb.viewing_directions
         # print("directions",directions.shape)
         my_pcv = processing.apcv(my_scene, directions)
-        print("place code shape", my_pcv.shape)
 
         self.assertIsNotNone(my_pcv)
         self.assertFalse(sum(my_pcv.shape) == 0)
@@ -386,42 +390,39 @@ class TestCase(unittest.TestCase):
 
         # not working cases doesnt match with shape of place code
         testdirection = np.zeros((2, 4, 2))
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(Exception):
             my_pcv = processing.apcv(my_scene, testdirection)
-        print("wanted exception occured", cm.exception)
 
         # not working cases wrong last dimension
         testdirection = np.zeros((180, 360, 1))
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(Exception):
             my_pcv = processing.apcv(my_scene, testdirection)
-        print("wanted exception occured", cm.exception)
 
         # not working cases too many dimensions
         testdirection = np.zeros((180, 360, 2, 4))
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(Exception):
             my_pcv = processing.apcv(my_scene, testdirection)
-        print("wanted exception occured", cm.exception)
 
         # not working cases empty
         testdirection = np.zeros(())
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(Exception):
             my_pcv = processing.apcv(my_scene, testdirection)
-        print("wanted exception occured", cm.exception)
 
         # not working cases nans
         testdirection = np.zeros((180, 360, 2, 4))
         testdirection[2, 3, 0] = np.nan
-        with self.assertRaises(Exception) as cm:
+        with self.assertRaises(ValueError):
             my_pcv = processing.apcv(my_scene, testdirection)
-        print("wanted exception occured", cm.exception)
 
     def test_size(self):
         # not working cases:
         scene = processing.scene(self.mydb, rowid=1)
-        for size in [8, 1, 0, -4, 9.4, 'g', None, np.nan]:
-            with self.assertRaises(Exception) as cm:
+        for size in [8, 1, 0, -4]:
+            with self.assertRaises(ValueError):
+                contrast = processing.michelson_contrast(scene, size=size)
+        for size in [9.4, 'g', None, np.nan]:
+            with self.assertRaises(TypeError):
                 contrast = processing.michelson_contrast(scene, size=size)
-            print("wanted error occured", cm.exception)
 
         # working cases
         for size in [2, 3, 4, 5]:
-- 
GitLab