Skip to content
Snippets Groups Projects
Commit 31d2f3cf authored by Luise Odenthal's avatar Luise Odenthal
Browse files

did things on todo list

parent 2fc76cfd
No related branches found
No related tags found
No related merge requests found
...@@ -5,60 +5,11 @@ memorised places. ...@@ -5,60 +5,11 @@ memorised places.
""" """
import numpy as np import numpy as np
from navipy.processing.tools import is_ibpc, is_obpc from navipy.processing.tools import is_ibpc, is_obpc
from navipy.processing.__init__ import check_scene
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)
def simple_imagediff(current, memory): def simple_imagediff(current, memory):
"""Compute the root mean square difference between """Compute the difference between
the current and memorised place code the current and memorised place code
:param current: current place code :param current: current place code
...@@ -70,12 +21,13 @@ the current and memorised place code ...@@ -70,12 +21,13 @@ the current and memorised place code
Current opinion in neurobiology Current opinion in neurobiology
""" """
assert isinstance(current, np.ndarray),\ if not isinstance(current, np.ndarray):
'current place code should be a numpy array' raise TypeError('current place code should be a numpy array')
assert isinstance(memory, np.ndarray),\ if not isinstance(memory, np.ndarray):
'memory place code should be a numpy array' raise TypeError('memory place code should be a numpy array')
assert np.all(current.shape == memory.shape),\ if not np.all(current.shape == memory.shape):
'memory and current place code should have the same shape' raise Exception('memory and current place code should\
have the same shape')
check_scene(current) check_scene(current)
check_scene(memory) check_scene(memory)
diff = current - memory diff = current - memory
...@@ -100,15 +52,8 @@ the current and memorised place code ...@@ -100,15 +52,8 @@ the current and memorised place code
Current opinion in neurobiology Current opinion in neurobiology
""" """
assert isinstance(current, np.ndarray),\ simple_diff = simple_imagediff(current, memory)
'current place code should be a numpy array' diff = np.power(simple_diff, 2)
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)
if is_ibpc(current): if is_ibpc(current):
return np.sqrt(diff.mean(axis=0).mean(axis=0)) # 1 return np.sqrt(diff.mean(axis=0).mean(axis=0)) # 1
elif is_obpc(current): elif is_obpc(current):
...@@ -131,10 +76,12 @@ the current and memorised place code. ...@@ -131,10 +76,12 @@ the current and memorised place code.
..note: assume that the image is periodic along the x axis ..note: assume that the image is periodic along the x axis
(the left-right axis) (the left-right axis)
""" """
assert is_ibpc(current),\ if not is_ibpc(current):
'The current and memory place code should be image based' raise TypeError('The current and memory place code\
assert is_ibpc(memory),\ should be image based')
'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(current)
check_scene(memory) check_scene(memory)
ridf = np.zeros((current.shape[1], current.shape[2])) ridf = np.zeros((current.shape[1], current.shape[2]))
...@@ -145,11 +92,36 @@ the current and memorised place code. ...@@ -145,11 +92,36 @@ the current and memorised place code.
def diff_optic_flow(current, memory): def diff_optic_flow(current, memory):
print("shape of current", current.shape) """Computes the direction of motion from current
assert is_ibpc(current),\ to memory by using the optic flow under the
'The current and memory place code should be image based' constrain that the brightness is constant, (small movement),
assert is_ibpc(memory),\ using a taylor expansion and solving the equation:
'The current and memory place code should be image based' 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(current)
check_scene(memory) check_scene(memory)
currroll = np.roll(current, 1, axis=1) currroll = np.roll(current, 1, axis=1)
...@@ -160,10 +132,10 @@ def diff_optic_flow(current, memory): ...@@ -160,10 +132,10 @@ def diff_optic_flow(current, memory):
dx = np.reshape(dx, (np.prod(dx.shape), 1)) dx = np.reshape(dx, (np.prod(dx.shape), 1))
di = current-memory di = current-memory
di = np.reshape(di, (np.prod(di.shape), 1)) di = np.reshape(di, (np.prod(di.shape), 1))
A = np.column_stack([dy, dx]) a_matrix = np.column_stack([dy, dx])
ATA = np.dot(np.transpose(A), A) a_matrix_sqr = np.dot(np.transpose(a_matrix), a_matrix)
b = np.dot(np.transpose(A), di) b_vector = np.dot(np.transpose(a_matrix), di)
res = np.linalg.solve(ATA, b) res = np.linalg.solve(a_matrix_sqr, b_vector)
return res return res
......
...@@ -51,10 +51,13 @@ class TestCase(unittest.TestCase): ...@@ -51,10 +51,13 @@ class TestCase(unittest.TestCase):
curr3 = np.array(curr3) curr3 = np.array(curr3)
curr4 = np.zeros((3, 4, 5, 0)) curr4 = np.zeros((3, 4, 5, 0))
for s in [curr2, curr3, curr4]: # put useless stuff here # put useless stuff here
with self.assertRaises(Exception) as cm: with self.assertRaises(ValueError):
comparing.imagediff(s, mem) comparing.imagediff(curr2, mem)
print("wanted exception occured", cm.exception) with self.assertRaises(Exception):
comparing.imagediff(curr3, mem)
with self.assertRaises(Exception):
comparing.imagediff(curr4, mem)
# should be working -> check if result is correct # should be working -> check if result is correct
for s in [curr]: for s in [curr]:
...@@ -74,10 +77,12 @@ class TestCase(unittest.TestCase): ...@@ -74,10 +77,12 @@ class TestCase(unittest.TestCase):
mem3 = np.array(mem3) mem3 = np.array(mem3)
mem4 = np.zeros((3, 4, 5, 0)) mem4 = np.zeros((3, 4, 5, 0))
for s in [mem2, mem3, mem4]: # put useless stuff here with self.assertRaises(ValueError):
with self.assertRaises(Exception) as cm: comparing.imagediff(curr, mem2)
comparing.imagediff(curr, s) with self.assertRaises(Exception):
print("wanted exception occured", cm.exception) comparing.imagediff(curr, mem3)
with self.assertRaises(Exception):
comparing.imagediff(curr, mem4)
# should be working -> check if result is correct # should be working -> check if result is correct
for s in [mem]: for s in [mem]:
...@@ -97,10 +102,12 @@ class TestCase(unittest.TestCase): ...@@ -97,10 +102,12 @@ class TestCase(unittest.TestCase):
curr3 = np.array(curr3) curr3 = np.array(curr3)
curr4 = np.zeros((3, 4, 5, 0)) curr4 = np.zeros((3, 4, 5, 0))
for s in [curr2, curr3, curr4]: # put useless stuff here with self.assertRaises(ValueError):
with self.assertRaises(Exception) as cm: comparing.rot_imagediff(curr2, mem)
comparing.rot_imagediff(s, mem) with self.assertRaises(Exception):
print("wanted exception occured", cm.exception) comparing.rot_imagediff(curr3, mem)
with self.assertRaises(Exception):
comparing.rot_imagediff(curr4, mem)
# should be working -> check if result is correct # should be working -> check if result is correct
for s in [curr]: for s in [curr]:
...@@ -120,10 +127,12 @@ class TestCase(unittest.TestCase): ...@@ -120,10 +127,12 @@ class TestCase(unittest.TestCase):
mem3 = np.array(mem3) mem3 = np.array(mem3)
mem4 = np.zeros((3, 4, 5, 0)) mem4 = np.zeros((3, 4, 5, 0))
for s in [mem2, mem3, mem4]: # put useless stuff here with self.assertRaises(ValueError):
with self.assertRaises(Exception) as cm: comparing.rot_imagediff(curr, mem2)
comparing.rot_imagediff(curr, s) with self.assertRaises(Exception):
print("wanted exception occured", cm.exception) comparing.rot_imagediff(curr, mem3)
with self.assertRaises(Exception):
comparing.rot_imagediff(curr, mem4)
# should be working -> check if result is correct # should be working -> check if result is correct
for s in [mem]: for s in [mem]:
...@@ -143,10 +152,12 @@ class TestCase(unittest.TestCase): ...@@ -143,10 +152,12 @@ class TestCase(unittest.TestCase):
curr3 = np.array(curr3) curr3 = np.array(curr3)
curr4 = np.zeros((3, 4, 5, 0)) curr4 = np.zeros((3, 4, 5, 0))
for s in [curr2, curr3, curr4]: # put useless stuff here with self.assertRaises(ValueError):
with self.assertRaises(Exception) as cm: comparing.simple_imagediff(curr2, mem)
comparing.simple_imagediff(s, mem) with self.assertRaises(Exception):
print("wanted exception occured", cm.exception) comparing.simple_imagediff(curr3, mem)
with self.assertRaises(Exception):
comparing.simple_imagediff(curr4, mem)
# should be working -> check if result is correct # should be working -> check if result is correct
for s in [curr]: for s in [curr]:
...@@ -161,17 +172,19 @@ class TestCase(unittest.TestCase): ...@@ -161,17 +172,19 @@ class TestCase(unittest.TestCase):
def test_simple_imagediff_mem(self): def test_simple_imagediff_mem(self):
curr = processing.scene(self.mydb, rowid=1) curr = processing.scene(self.mydb, rowid=1)
mem = processing.scene(self.mydb, rowid=2) mem = processing.scene(self.mydb, rowid=2)
curr2 = curr.copy() mem2 = curr.copy()
curr2[3, 5, 2, 0] = np.nan mem2[3, 5, 2, 0] = np.nan
curr3 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] mem3 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
curr3 = [curr3, curr3, curr3] mem3 = [mem3, mem3, mem3]
curr3 = np.array(curr3) mem3 = np.array(mem3)
curr4 = np.zeros((3, 4, 5, 0)) mem4 = np.zeros((3, 4, 5, 0))
for s in [curr2, curr3, curr4]: # put useless stuff here with self.assertRaises(ValueError):
with self.assertRaises(Exception) as cm: comparing.simple_imagediff(curr, mem2)
comparing.simple_imagediff(s, mem) with self.assertRaises(Exception):
print("wanted exception occured", cm.exception) comparing.simple_imagediff(curr, mem3)
with self.assertRaises(Exception):
comparing.simple_imagediff(curr, mem4)
# should be working -> check if result is correct # should be working -> check if result is correct
for s in [mem]: for s in [mem]:
...@@ -193,10 +206,12 @@ class TestCase(unittest.TestCase): ...@@ -193,10 +206,12 @@ class TestCase(unittest.TestCase):
mem3 = np.array(mem3) mem3 = np.array(mem3)
mem4 = np.zeros((3, 4, 5, 0)) mem4 = np.zeros((3, 4, 5, 0))
for s in [mem2, mem3, mem4]: # put useless stuff here with self.assertRaises(ValueError):
with self.assertRaises(Exception) as cm: comparing.diff_optic_flow(curr, mem2)
comparing.diff_optic_flow(curr, s) with self.assertRaises(Exception):
print("wanted exception occured", cm.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 # should be working -> check if result is correct
for s in [mem]: for s in [mem]:
...@@ -205,6 +220,30 @@ class TestCase(unittest.TestCase): ...@@ -205,6 +220,30 @@ class TestCase(unittest.TestCase):
self.assertFalse(np.any(np.isnan(vec))) self.assertFalse(np.any(np.isnan(vec)))
self.assertTrue(is_numeric_array(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__': if __name__ == '__main__':
unittest.main() unittest.main()
...@@ -116,8 +116,10 @@ It creates three sql table on initialisation. ...@@ -116,8 +116,10 @@ It creates three sql table on initialisation.
def __init__(self, filename, channels=['R', 'G', 'B', 'D']): def __init__(self, filename, channels=['R', 'G', 'B', 'D']):
"""Initialisation of the database """ """Initialisation of the database """
assert isinstance(filename, str), 'filename should be a string' if not isinstance(filename, str):
assert isinstance(channels, list), 'nb_channel should be an integer' raise TypeError('filename should be a string')
if not isinstance(channels, list):
raise TypeError('nb_channel should be a list')
self.filename = filename self.filename = filename
self.channels = channels self.channels = channels
self.normalisation_columns = list() self.normalisation_columns = list()
...@@ -146,9 +148,9 @@ It creates three sql table on initialisation. ...@@ -146,9 +148,9 @@ It creates three sql table on initialisation.
filename, detect_types=sqlite3.PARSE_DECLTYPES) filename, detect_types=sqlite3.PARSE_DECLTYPES)
self.db_cursor = self.db.cursor() self.db_cursor = self.db.cursor()
for tablename, _ in self.tablecolumns.items(): for tablename, _ in self.tablecolumns.items():
assert self.table_exist(tablename),\ if not self.table_exist(tablename):
'{} does not contain a table named {}'.format( raise Exception('{} does not contain a table named {}'.format(
filename, tablename) filename, tablename))
elif self.create(): elif self.create():
# Create database # Create database
self.db = sqlite3.connect( self.db = sqlite3.connect(
...@@ -173,7 +175,8 @@ It creates three sql table on initialisation. ...@@ -173,7 +175,8 @@ It creates three sql table on initialisation.
self.viewing_directions[..., 1] = ma self.viewing_directions[..., 1] = ma
def table_exist(self, tablename): 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( self.db_cursor.execute(
""" """
SELECT count(*) SELECT count(*)
...@@ -305,8 +308,8 @@ database ...@@ -305,8 +308,8 @@ database
return posorient return posorient
def read_posorient(self, posorient=None, rowid=None): def read_posorient(self, posorient=None, rowid=None):
assert (posorient is None) or (rowid is None),\ if (posorient is None) and (rowid is None):
'posorient and rowid can not be both None' raise ValueError('posorient and rowid can not be both None')
if posorient is not None: if posorient is not None:
rowid = self.get_posid(posorient) rowid = self.get_posid(posorient)
# Read images # Read images
...@@ -332,8 +335,8 @@ database ...@@ -332,8 +335,8 @@ database
:returns: an image :returns: an image
:rtype: numpy.ndarray :rtype: numpy.ndarray
""" """
assert (posorient is None) or (rowid is None),\ if (posorient is None) and (rowid is None):
'posorient and rowid can not be both None' raise ValueError('posorient and rowid can not be both None')
if posorient is not None: if posorient is not None:
rowid = self.get_posid(posorient) rowid = self.get_posid(posorient)
# Read images # Read images
...@@ -353,19 +356,19 @@ database ...@@ -353,19 +356,19 @@ database
FROM {} FROM {}
WHERE (rowid={}) WHERE (rowid={})
""".format(tablename, rowid), self.db) """.format(tablename, rowid), self.db)
assert cmaxminrange.shape[0] == 1,\ if not cmaxminrange.shape[0] == 1:
'Error while reading normalisation factors' raise Exception('Error while reading normalisation factors')
cmaxminrange = cmaxminrange.iloc[0, :] cmaxminrange = cmaxminrange.iloc[0, :]
return self.denormalise_image(image, cmaxminrange) return self.denormalise_image(image, cmaxminrange)
def denormalise_image(self, image, cmaxminrange): def denormalise_image(self, image, cmaxminrange):
assert len(image.shape) == 3,\ if not len(image.shape) == 3:
'image should be 3D array' raise Exception('image should be 3D array')
assert image.shape[2] == len(self.channels),\ if not image.shape[2] == len(self.channels):
'image does not have the required number of channels {}'.format( raise Exception('image does not have the required number of channels {}'.format(
len(self.channels)) len(self.channels)))
assert isinstance(cmaxminrange, pd.Series),\ if not isinstance(cmaxminrange, pd.Series):
'cmaxminrange should be a pandas Series' raise TypeError('cmaxminrange should be a pandas Series')
denormed_im = np.zeros(image.shape, dtype=np.float) denormed_im = np.zeros(image.shape, dtype=np.float)
maxval_nim = np.iinfo(image.dtype).max maxval_nim = np.iinfo(image.dtype).max
# #
...@@ -378,8 +381,8 @@ database ...@@ -378,8 +381,8 @@ database
cimage *= crange cimage *= crange
cimage += cmin cimage += cmin
denormed_im[:, :, chan_i] = cimage denormed_im[:, :, chan_i] = cimage
assert np.max(cimage) == cmax,\ if not np.max(cimage) == cmax:
'denormalisation failed {}!={}'.format(np.max(cimage), cmax) raise Exception('denormalisation failed {}!={}'.format(np.max(cimage), cmax))
return denormed_im return denormed_im
...@@ -415,10 +418,10 @@ class DataBaseSave(DataBase): ...@@ -415,10 +418,10 @@ class DataBaseSave(DataBase):
self.insert_replace(tablename, params) self.insert_replace(tablename, params)
def insert_replace(self, tablename, params): def insert_replace(self, tablename, params):
assert isinstance(tablename, str),\ if not isinstance(tablename, str):
'table are named by string' raise TypeError('table are named by string')
assert isinstance(params, dict),\ if not isinstance(params, dict):
'params should be dictionary columns:val' raise TypeError('params should be dictionary columns:val')
params_list = list() params_list = list()
columns_str = '' columns_str = ''
for key, val in params.items(): for key, val in params.items():
......
...@@ -110,63 +110,96 @@ def scene(database, posorient=None, rowid=None): ...@@ -110,63 +110,96 @@ def scene(database, posorient=None, rowid=None):
# where to check if db is okay? in database? # where to check if db is okay? in database?
if posorient is not None: if posorient is not None:
assert isinstance(posorient, pd.Series),\ if not isinstance(posorient, pd.Series):
'posorient should be a pandas Series' raise TypeError('posorient should be a pandas Series')
assert ~posorient.empty, 'position must not be empty' if posorient.empty:
assert ('x' in posorient.index),\ raise Exception('position must not be empty')
'missing index x' if 'x' not in posorient.index:
assert ('y' in posorient.index), 'missing index y' raise ValueError('missing index x')
assert 'z' in posorient.index, 'missing index z' if 'y' not in posorient.index:
assert 'alpha_0' in posorient.index, 'missing index alpha_0' raise ValueError('missing index y')
assert 'alpha_1' in posorient.index, 'missing index alpha_1' if 'z' not in posorient.index:
assert 'alpha_2' in posorient.index, 'missing index alpha_2' raise ValueError('missing index z')
assert ~np.any(np.isnan(posorient)) 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: if rowid is not None:
assert rowid > 0 if not isinstance(rowid, int):
assert isinstance(rowid, int) raise TypeError('rowid must be of type integer')
assert rowid is not None if rowid <= 0:
assert rowid is not np.nan 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 in database.index#??
assert rowid is not None or posorient is not None if rowid is not None or posorient is not None:
scene = database.read_image(posorient=posorient, scene = database.read_image(posorient=posorient,
rowid=rowid rowid=rowid)
) # print(np.array(scene).shape)
# print(np.array(scene).shape) scene = scene[..., np.newaxis]
scene = scene[..., np.newaxis] # print(np.array(scene).shape)
# print(np.array(scene).shape) return scene
return scene else:
raise ValueError('either rowid or posoriend must be given')
def check_scene(scene): def check_scene(scene):
if is_ibpc(scene): if is_ibpc(scene):
# print("normal") # print("normal")
assert is_numeric_array(scene) # np.isscalar(scene) if not is_numeric_array(scene):
assert ~np.any(np.isnan(scene)) raise TypeError('scene is of non numeric type')
assert len(scene.shape) == 4 if not ~np.any(np.isnan(scene)):
assert (scene.shape[1] > 0) raise ValueError('scene contains nans')
assert (scene.shape[0] > 0) if not len(scene.shape) == 4:
assert (scene.shape[2] == 4) raise Exception('scene has wrong shape, must have 4 dimensions')
assert (scene.shape[3] == 1) 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))) # assert ~(np.any(np.isNone(scene)))
return True
elif is_obpc(scene): elif is_obpc(scene):
assert is_numeric_array(scene) # np.isscalar(scene) if not is_numeric_array(scene):
assert ~np.any(np.isnan(scene)) raise TypeError('scene is of non numeric type')
assert len(scene.shape) == 3 if not ~np.any(np.isnan(scene)):
assert ~(scene.shape[1] <= 0) raise ValueError('scene contains nans')
assert ~(scene.shape[0] <= 0) if not len(scene.shape) == 3:
assert (scene.shape[2] == 4) raise Exception('scene has wrong shape, must have 4 dimensions')
assert (scene.shape[3] == 1) 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))) # assert ~(np.any(np.isNone(scene)))
return True
def check_viewing_direction(viewing_direction): def check_viewing_direction(viewing_direction):
assert is_numeric_array(viewing_direction) if not is_numeric_array(viewing_direction):
assert ~np.any(np.isnan(viewing_direction)) raise TypeError('viewing direction is of non numeric type')
assert len(viewing_direction.shape) == 3 if not ~np.any(np.isnan(viewing_direction)):
assert (viewing_direction.shape[1] > 0) raise ValueError('viewing direction contains nans')
assert (viewing_direction.shape[0] > 0) if not len(viewing_direction.shape) == 3:
assert (viewing_direction.shape[2] == 2) 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): def skyline(scene):
...@@ -181,10 +214,9 @@ def skyline(scene): ...@@ -181,10 +214,9 @@ def skyline(scene):
.. plot:: example/processing/skyline.py .. plot:: example/processing/skyline.py
""" """
assert is_ibpc(scene),\ if not is_ibpc(scene):
'scene should be image based to compute a skyline' raise TypeError('scene should be image based to compute a skyline')
check_scene(scene) check_scene(scene)
skyline = scene.mean(axis=__ibpc_indeces__['elevation']) skyline = scene.mean(axis=__ibpc_indeces__['elevation'])
return skyline[np.newaxis, :] return skyline[np.newaxis, :]
...@@ -212,9 +244,13 @@ and minimum of the local image intensity ...@@ -212,9 +244,13 @@ and minimum of the local image intensity
""" """
check_scene(scene) check_scene(scene)
assert is_ibpc(scene), \ if not is_ibpc(scene):
'scene should be image based to compute the michelson constrast' raise TypeError('scene should be image based\
assert size >= 2 and size <= 5 # in range(2,6) 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) contrast = np.zeros_like(scene)
for channel in range(scene.shape[__ibpc_indeces__['channel']]): for channel in range(scene.shape[__ibpc_indeces__['channel']]):
i_max = maximum_filter(scene[..., channel, 0], i_max = maximum_filter(scene[..., channel, 0],
...@@ -240,10 +276,17 @@ and minimum of the local image intensity in the michelson-contrast. ...@@ -240,10 +276,17 @@ and minimum of the local image intensity in the michelson-contrast.
""" """
check_scene(scene) check_scene(scene)
assert contrast_size >= 2 and contrast_size <= 5 # in range(2,6) if not isinstance(contrast_size, int):
assert distance_channel in [0, 1, 2, 3] raise TypeError('constrast size must be of type integer')
assert is_ibpc(scene), \ if not isinstance(distance_channel, int):
'scene should be image based to compute the contrast weighted nearness' 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) contrast = michelson_contrast(scene, size=contrast_size)
distance = scene[..., distance_channel, 0] distance = scene[..., distance_channel, 0]
distance = distance[..., np.newaxis, np.newaxis] distance = distance[..., np.newaxis, np.newaxis]
...@@ -277,13 +320,17 @@ def pcv(place_code, viewing_directions): ...@@ -277,13 +320,17 @@ def pcv(place_code, viewing_directions):
check_scene(place_code) check_scene(place_code)
check_viewing_direction(viewing_directions) check_viewing_direction(viewing_directions)
assert place_code.shape[0] == viewing_directions.shape[0] if not place_code.shape[0] == viewing_directions.shape[0]:
assert place_code.shape[1] == viewing_directions.shape[1] raise Exception('dimensions of place code and viewing\
assert isinstance(viewing_directions, np.ndarray), \ direction do not match')
'viewing_directions should be a numpy array' if not place_code.shape[1] == viewing_directions.shape[1]:
assert place_code.shape[component_dim] == 1, \ raise Exception('dimensions of place code and viewing\
'the last dimension ({}) of the place-code should be 1'.format( direction do not match')
place_code.shape[component_dim]) 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']] elevation = viewing_directions[..., __spherical_indeces__['elevation']]
azimuth = viewing_directions[..., __spherical_indeces__['azimuth']] azimuth = viewing_directions[..., __spherical_indeces__['azimuth']]
unscaled_lv = spherical_to_cartesian(elevation, azimuth, radius=1) unscaled_lv = spherical_to_cartesian(elevation, azimuth, radius=1)
...@@ -313,8 +360,12 @@ def apcv(place_code, viewing_directions): ...@@ -313,8 +360,12 @@ def apcv(place_code, viewing_directions):
""" """
check_scene(place_code) check_scene(place_code)
check_viewing_direction(viewing_directions) check_viewing_direction(viewing_directions)
assert place_code.shape[0] == viewing_directions.shape[0] if not place_code.shape[0] == viewing_directions.shape[0]:
assert place_code.shape[1] == viewing_directions.shape[1] 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) scaled_lv = pcv(place_code, viewing_directions)
if is_ibpc(place_code): if is_ibpc(place_code):
return (scaled_lv.sum(axis=0).sum(axis=0))[np.newaxis, np.newaxis, ...] return (scaled_lv.sum(axis=0).sum(axis=0))[np.newaxis, np.newaxis, ...]
......
...@@ -2,7 +2,7 @@ import unittest ...@@ -2,7 +2,7 @@ import unittest
import sqlite3 import sqlite3
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from navipy.database import database import navipy.database as database
import navipy.processing as processing import navipy.processing as processing
import pkg_resources import pkg_resources
...@@ -114,10 +114,8 @@ class TestCase(unittest.TestCase): ...@@ -114,10 +114,8 @@ class TestCase(unittest.TestCase):
posorient2.alpha_0 = posorient.alpha_0 posorient2.alpha_0 = posorient.alpha_0
posorient2.alpha_1 = posorient.alpha_1 posorient2.alpha_1 = posorient.alpha_1
posorient2.alpha_2 = posorient.alpha_2 posorient2.alpha_2 = posorient.alpha_2
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
image = processing.scene(self.mydb, posorient=posorient2) image = processing.scene(self.mydb, posorient=posorient2)
# print("missing column")
print(cm.exception)
# incorrect case None # incorrect case None
posorient2 = pd.Series(index=['x', 'y', 'z', posorient2 = pd.Series(index=['x', 'y', 'z',
...@@ -128,9 +126,8 @@ class TestCase(unittest.TestCase): ...@@ -128,9 +126,8 @@ class TestCase(unittest.TestCase):
posorient2.alpha_0 = posorient.alpha_0 posorient2.alpha_0 = posorient.alpha_0
posorient2.alpha_1 = posorient.alpha_1 posorient2.alpha_1 = posorient.alpha_1
posorient2.alpha_2 = posorient.alpha_2 posorient2.alpha_2 = posorient.alpha_2
with self.assertRaises(Exception) as cm: with self.assertRaises(ValueError):
image = processing.scene(self.mydb, posorient=posorient2) image = processing.scene(self.mydb, posorient=posorient2)
print(cm.exception)
# incorrect case nan # incorrect case nan
posorient2 = pd.Series(index=['x', 'y', 'z', posorient2 = pd.Series(index=['x', 'y', 'z',
...@@ -141,9 +138,8 @@ class TestCase(unittest.TestCase): ...@@ -141,9 +138,8 @@ class TestCase(unittest.TestCase):
posorient2.alpha_0 = posorient.alpha_0 posorient2.alpha_0 = posorient.alpha_0
posorient2.alpha_1 = posorient.alpha_1 posorient2.alpha_1 = posorient.alpha_1
posorient2.alpha_2 = posorient.alpha_2 posorient2.alpha_2 = posorient.alpha_2
with self.assertRaises(Exception) as cm: with self.assertRaises(ValueError):
image = processing.scene(self.mydb, posorient=posorient2) image = processing.scene(self.mydb, posorient=posorient2)
print(cm.exception)
# incorrect case no pandas series but dict # incorrect case no pandas series but dict
posorient2 = {} posorient2 = {}
...@@ -153,17 +149,15 @@ class TestCase(unittest.TestCase): ...@@ -153,17 +149,15 @@ class TestCase(unittest.TestCase):
posorient2['alpha_0'] = posorient.alpha_0 posorient2['alpha_0'] = posorient.alpha_0
posorient2['alpha_1'] = posorient.alpha_1 posorient2['alpha_1'] = posorient.alpha_1
posorient2['alpha_2'] = posorient.alpha_2 posorient2['alpha_2'] = posorient.alpha_2
with self.assertRaises(Exception) as cm: with self.assertRaises(TypeError):
image = processing.scene(self.mydb, posorient=posorient2) image = processing.scene(self.mydb, posorient=posorient2)
print(cm.exception)
# not working case empty # not working case empty
posorient2 = pd.Series(index=['x', 'y', 'z', posorient2 = pd.Series(index=['x', 'y', 'z',
'alpha_0', 'alpha_1', 'alpha_2']) 'alpha_0', 'alpha_1', 'alpha_2'])
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
image = processing.scene(self.mydb, posorient=posorient2) image = processing.scene(self.mydb, posorient=posorient2)
print(cm.exception)
""" """
def test_db(self): def test_db(self):
...@@ -201,10 +195,13 @@ class TestCase(unittest.TestCase): ...@@ -201,10 +195,13 @@ class TestCase(unittest.TestCase):
scene3 = np.array(scene3) scene3 = np.array(scene3)
scene4 = np.zeros((3, 4, 5, 0)) scene4 = np.zeros((3, 4, 5, 0))
for s in [scene2, scene3, scene4]: # put useless stuff here # put useless stuff here
with self.assertRaises(Exception) as cm: with self.assertRaises(ValueError):
processing.skyline(s) processing.skyline(scene2)
print("wanted exception occured", cm.exception) with self.assertRaises(TypeError):
processing.skyline(scene3)
with self.assertRaises(Exception):
processing.skyline(scene4)
# should be working -> check if result(skyline) is correct # should be working -> check if result(skyline) is correct
for s in [scene]: for s in [scene]:
...@@ -222,13 +219,18 @@ class TestCase(unittest.TestCase): ...@@ -222,13 +219,18 @@ class TestCase(unittest.TestCase):
# print("test_id") # print("test_id")
# check for wrong cases # check for wrong cases
# my_scene = processing.scene(self.mydb, rowid=-2) # my_scene = processing.scene(self.mydb, rowid=-2)
for rowid in [0, 't', -2, 4.5, np.nan, None]: for rowid in [0, -2]:
with self.assertRaises(ValueError):
with self.assertRaises(Exception) as cm:
# print("rowid",rowid) # print("rowid",rowid)
processing.scene(self.mydb, rowid=rowid) processing.scene(self.mydb, rowid=rowid)
the_exception = cm.exception with self.assertRaises(TypeError):
print("error occured", the_exception) 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]: for rowid in [1, 2, 3, 4, 5]:
image = processing.scene(self.mydb, rowid=rowid) image = processing.scene(self.mydb, rowid=rowid)
...@@ -246,11 +248,13 @@ class TestCase(unittest.TestCase): ...@@ -246,11 +248,13 @@ class TestCase(unittest.TestCase):
scene = processing.scene(self.mydb, rowid=1) scene = processing.scene(self.mydb, rowid=1)
# print("scene sizejhghghhg",scene.shape) # print("scene sizejhghghhg",scene.shape)
# should not be working # should not be working
for d in [-1, 'g', None, np.nan, 8.4]: for d in ['g', None, np.nan, 8.4]:
with self.assertRaises(Exception) as cm: with self.assertRaises(TypeError):
processing.contrast_weighted_nearness(scene, processing.contrast_weighted_nearness(scene,
distance_channel=d) distance_channel=d)
print("wanted error occured", cm.exception) with self.assertRaises(ValueError):
processing.contrast_weighted_nearness(scene,
distance_channel=-1)
# should work # should work
for d in [0, 1, 2, 3]: for d in [0, 1, 2, 3]:
...@@ -287,19 +291,25 @@ class TestCase(unittest.TestCase): ...@@ -287,19 +291,25 @@ class TestCase(unittest.TestCase):
scene3 = [scene3, scene3, scene3] scene3 = [scene3, scene3, scene3]
scene3 = np.array(scene3) scene3 = np.array(scene3)
scene4 = np.zeros((3, 4, 5, 0)) scene4 = np.zeros((3, 4, 5, 0))
for s in [scene2, scene3, scene4]: with self.assertRaises(ValueError):
with self.assertRaises(Exception) as cm: contrast = processing.contrast_weighted_nearness(scene2)
contrast = processing.contrast_weighted_nearness(scene) with self.assertRaises(ValueError):
print("wanted excption occured", cm.exception) contrast = processing.contrast_weighted_nearness(scene3)
with self.assertRaises(Exception):
contrast = processing.contrast_weighted_nearness(scene4)
def test_contr_weight_contrast(self): def test_contr_weight_contrast(self):
scene = processing.scene(self.mydb, rowid=1) scene = processing.scene(self.mydb, rowid=1)
for size in [8, 1, 0, -4, 9.4, 'g', None, np.nan]: for size in [9.4, 'g', None, np.nan]:
with self.assertRaises(Exception) as cm: 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 = \ contrast = \
processing.contrast_weighted_nearness(scene, processing.contrast_weighted_nearness(scene,
contrast_size=size) contrast_size=size)
print("wanted error occured", cm.exception)
# working cases # working cases
for size in [2, 3, 4, 5]: for size in [2, 3, 4, 5]:
...@@ -336,34 +346,29 @@ class TestCase(unittest.TestCase): ...@@ -336,34 +346,29 @@ class TestCase(unittest.TestCase):
# not working cases doesnt match with shape of place code # not working cases doesnt match with shape of place code
testdirection = np.zeros((2, 4, 2)) testdirection = np.zeros((2, 4, 2))
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
my_pcv = processing.pcv(my_scene, testdirection) my_pcv = processing.pcv(my_scene, testdirection)
print("wanted exception occured", cm.exception)
# not working cases wrong last dimension # not working cases wrong last dimension
testdirection = np.zeros((180, 360, 1)) testdirection = np.zeros((180, 360, 1))
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
my_pcv = processing.pcv(my_scene, testdirection) my_pcv = processing.pcv(my_scene, testdirection)
print("wanted exception occured", cm.exception)
# not working cases too many dimensions # not working cases too many dimensions
testdirection = np.zeros((180, 360, 2, 4)) testdirection = np.zeros((180, 360, 2, 4))
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
my_pcv = processing.pcv(my_scene, testdirection) my_pcv = processing.pcv(my_scene, testdirection)
print("wanted exception occured", cm.exception)
# not working cases empty # not working cases empty
testdirection = np.zeros(()) testdirection = np.zeros(())
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
my_pcv = processing.pcv(my_scene, testdirection) my_pcv = processing.pcv(my_scene, testdirection)
print("wanted exception occured", cm.exception)
# not working cases nans # not working cases nans
testdirection = np.zeros((180, 360, 2, 4)) testdirection = np.zeros((180, 360, 2, 4))
testdirection[2, 3, 0] = np.nan testdirection[2, 3, 0] = np.nan
with self.assertRaises(Exception) as cm: with self.assertRaises(ValueError):
my_pcv = processing.pcv(my_scene, testdirection) my_pcv = processing.pcv(my_scene, testdirection)
print("wanted exception occured", cm.exception)
def test_apcv(self): def test_apcv(self):
# working case # working case
...@@ -373,7 +378,6 @@ class TestCase(unittest.TestCase): ...@@ -373,7 +378,6 @@ class TestCase(unittest.TestCase):
directions = self.mydb.viewing_directions directions = self.mydb.viewing_directions
# print("directions",directions.shape) # print("directions",directions.shape)
my_pcv = processing.apcv(my_scene, directions) my_pcv = processing.apcv(my_scene, directions)
print("place code shape", my_pcv.shape)
self.assertIsNotNone(my_pcv) self.assertIsNotNone(my_pcv)
self.assertFalse(sum(my_pcv.shape) == 0) self.assertFalse(sum(my_pcv.shape) == 0)
...@@ -386,42 +390,39 @@ class TestCase(unittest.TestCase): ...@@ -386,42 +390,39 @@ class TestCase(unittest.TestCase):
# not working cases doesnt match with shape of place code # not working cases doesnt match with shape of place code
testdirection = np.zeros((2, 4, 2)) testdirection = np.zeros((2, 4, 2))
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
my_pcv = processing.apcv(my_scene, testdirection) my_pcv = processing.apcv(my_scene, testdirection)
print("wanted exception occured", cm.exception)
# not working cases wrong last dimension # not working cases wrong last dimension
testdirection = np.zeros((180, 360, 1)) testdirection = np.zeros((180, 360, 1))
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
my_pcv = processing.apcv(my_scene, testdirection) my_pcv = processing.apcv(my_scene, testdirection)
print("wanted exception occured", cm.exception)
# not working cases too many dimensions # not working cases too many dimensions
testdirection = np.zeros((180, 360, 2, 4)) testdirection = np.zeros((180, 360, 2, 4))
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
my_pcv = processing.apcv(my_scene, testdirection) my_pcv = processing.apcv(my_scene, testdirection)
print("wanted exception occured", cm.exception)
# not working cases empty # not working cases empty
testdirection = np.zeros(()) testdirection = np.zeros(())
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
my_pcv = processing.apcv(my_scene, testdirection) my_pcv = processing.apcv(my_scene, testdirection)
print("wanted exception occured", cm.exception)
# not working cases nans # not working cases nans
testdirection = np.zeros((180, 360, 2, 4)) testdirection = np.zeros((180, 360, 2, 4))
testdirection[2, 3, 0] = np.nan testdirection[2, 3, 0] = np.nan
with self.assertRaises(Exception) as cm: with self.assertRaises(ValueError):
my_pcv = processing.apcv(my_scene, testdirection) my_pcv = processing.apcv(my_scene, testdirection)
print("wanted exception occured", cm.exception)
def test_size(self): def test_size(self):
# not working cases: # not working cases:
scene = processing.scene(self.mydb, rowid=1) scene = processing.scene(self.mydb, rowid=1)
for size in [8, 1, 0, -4, 9.4, 'g', None, np.nan]: for size in [8, 1, 0, -4]:
with self.assertRaises(Exception) as cm: 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) contrast = processing.michelson_contrast(scene, size=size)
print("wanted error occured", cm.exception)
# working cases # working cases
for size in [2, 3, 4, 5]: for size in [2, 3, 4, 5]:
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment