From 2a329141a72c09cd7f067cd7cd50a1922a64cbfc Mon Sep 17 00:00:00 2001
From: "lodenthal@uni-bielefeld.de" <lodenthal@uni-bielefeld.de>
Date: Mon, 7 May 2018 13:24:18 +0300
Subject: [PATCH] updates everything to the new convention, but one test in
 moving/test_math.py is not working

---
 navipy/comparing/__init__.py |  9 +++--
 navipy/database/__init__.py  | 13 +-------
 navipy/moving/agent.py       | 10 +++---
 navipy/moving/maths.py       | 64 +++++++++++++++++++++++-------------
 navipy/moving/test_agent.py  | 24 ++++++++++----
 navipy/moving/test_maths.py  | 48 ++++++++++++++++++++++-----
 6 files changed, 110 insertions(+), 58 deletions(-)

diff --git a/navipy/comparing/__init__.py b/navipy/comparing/__init__.py
index 7d32eaa..a918ca3 100644
--- a/navipy/comparing/__init__.py
+++ b/navipy/comparing/__init__.py
@@ -92,12 +92,17 @@ def diff_optic_flow(current, memory):
 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
+.. math::
+
+   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
+.. math::
+
+    A=(I_x,I_y) and b = I_t
 
+The intput parameters are the following:
     :param current: current place code
     :param memory: memorised place code
     :returns: a directional vectors
diff --git a/navipy/database/__init__.py b/navipy/database/__init__.py
index 25aa1ac..06a87e2 100644
--- a/navipy/database/__init__.py
+++ b/navipy/database/__init__.py
@@ -400,7 +400,6 @@ class DataBase():
             self.db.commit()
             return rowid
         else:
-            print(posorient)
             raise ValueError('posorient not found')
 
     @property
@@ -459,7 +458,6 @@ class DataBaseLoad(DataBase):
         posorient = pd.read_sql_query(
             "select * from position_orientation;", self.db)
         posorient.set_index('id', inplace=True)
-
         if not isinstance(posorient.index, pd.core.index.MultiIndex):
             warnings.warn("you are loading a database with old conventions,\
                            it will be transformed automatically into the new one")
@@ -470,20 +468,11 @@ class DataBaseLoad(DataBase):
                     tuples.append(('location', n))
                 else:
                     tuples.append((convention, n))
-            #tuples = [('location', 'x'), ('location', 'y'),
-            #          ('location', 'z'), (convention, 'alpha_0'),
-            #          (convention, 'alpha_1'), (convention, 'alpha_2')]
             index = pd.MultiIndex.from_tuples(tuples,
                                           names=['position', 'orientation'])
-            #posorient.rename(columns = {'x':('location', 'x')})
-            #posorient.rename(columns = {'y':('location', 'y')})
-            #posorient.rename(columns = {'z':('location', 'z')})
-            #posorient.rename(columns = {'alph_0':(convention, 'alpha_0')})
-            #posorient.rename(columns = {'alpha_1':(convention, 'alpha_1')})
-            #posorient.rename(columns = {'alpha_2':(convention, 'alpha_2')})
             posorient.columns = index
             return posorient
-                 
+
         return posorient
 
     @property
diff --git a/navipy/moving/agent.py b/navipy/moving/agent.py
index d58ffd5..2d7f11c 100644
--- a/navipy/moving/agent.py
+++ b/navipy/moving/agent.py
@@ -68,12 +68,10 @@ class AbstractAgent():
                       ('location', 'dz'), (convention, 'dalpha_0'),
                       (convention, 'dalpha_1'), (convention, 'dalpha_2')]
         index_vel = pd.MultiIndex.from_tuples(tuples_vel,
-                                          names=['position',
-                                                 'orientation'])
+                                              names=['position',
+                                                     'orientation'])
         self._velocity_col = index_vel
         self._posorient_vel_col = self._velocity_col.copy()
-
-
         self._posorient_vel = pd.Series(
             index=self._posorient_vel_col,
             data=np.nan)
@@ -224,8 +222,9 @@ GridAgent is a close loop agent here its position is snap to a grid.
             posorient_vel,
             move_mode=self._mode_move['mode'],
             move_param=self._mode_move['param'])
+        tmppos = self._brain.posorients
         tmp = navimomath.closest_pos(
-            posorient_vel, self._brain.posorients)
+            posorient_vel, tmppos)  # self._brain.posorients)
         posorient_vel.loc[self._posorient_col] = \
             tmp.loc[self._posorient_col]
         posorient_vel.name = tmp.name
@@ -264,7 +263,6 @@ GridAgent is a close loop agent here its position is snap to a grid.
             self._posorient_vel.loc[common_id] = start_posorient.loc[common_id]
             self.move()
             next_posorient = self._posorient_vel
-
             self._posorients_queue.task_done()
             self._results_queue.put((start_posorient, next_posorient))
         self._posorients_queue.task_done()
diff --git a/navipy/moving/maths.py b/navipy/moving/maths.py
index 4d845e3..faf8753 100644
--- a/navipy/moving/maths.py
+++ b/navipy/moving/maths.py
@@ -35,38 +35,51 @@ def next_pos(motion_vec, move_mode, move_param=None):
     if move_mode not in mode_moves_supported().keys():
         raise KeyError(
             'move mode must is not supported {}'.format(move_mode))
-
-    speed = pd.Series(index=['dx', 'dy', 'dz'])
-    speed.loc['dx'] = motion_vec['location']['dx']
-    speed.loc['dy'] = motion_vec['location']['dy']
-    speed.loc['dz'] = motion_vec['location']['dz']
+    tuples = [('location', 'dx'), ('location', 'dy'),
+              ('location', 'dz')]
+    index = pd.MultiIndex.from_tuples(tuples,
+                                      names=['position',
+                                             'orientation'])
+    speed = pd.Series(index=index)
+    speed['location']['dx'] = motion_vec['location']['dx']
+    speed['location']['dy'] = motion_vec['location']['dy']
+    speed['location']['dz'] = motion_vec['location']['dz']
     # speed = motion_vec.loc[['dx', 'dy', 'dz']]
     if move_mode == 'on_cubic_grid':
         # speed in spherical coord
-        epsilon = np.arctan2(speed.dz, np.sqrt(speed.dx**2 + speed.dy**2))
-        phi = np.arctan2(speed.dy, speed.dx)
+        epsilon = np.arctan2(speed['location']['dz'],
+                             np.sqrt(speed['location']['dx']**2 +
+                             speed['location']['dy']**2))
+        phi = np.arctan2(speed['location']['dy'], speed['location']['dx'])
         radius = np.sqrt(np.sum(speed**2))
         if np.isclose(radius, 0):
             scaling = 0
             speed = 0 * speed
         else:
-            deltas = pd.Series(index=['dx', 'dy', 'dz'])
-            deltas.dz = epsilon > (np.pi / 8) - epsilon < (np.pi / 8)
+            tuples = [('location', 'dx'), ('location', 'dy'),
+                      ('location', 'dz')]
+            index = pd.MultiIndex.from_tuples(tuples,
+                                              names=['position',
+                                                     'orientation'])
+            deltas = pd.Series(index=index)
+            deltas['location']['dz'] = float(epsilon > (np.pi / 8) -
+                                             epsilon < (np.pi / 8))
             edgecases = np.linspace(-np.pi, np.pi, 9)
             case_i = np.argmin(np.abs(phi - edgecases))
             if case_i == 8 or case_i == 0 or case_i == 1 or case_i == 7:
-                deltas.dx = -1
+                deltas['location']['dx'] = -1
             elif case_i == 3 or case_i == 4 or case_i == 5:
-                deltas.dx = 1
+                deltas['location']['dx'] = 1
             else:
-                deltas.dx = 0
+                deltas['location']['dx'] = 0
 
             if case_i == 1 or case_i == 2 or case_i == 3:
-                deltas.dy = -1
+                deltas['location']['dy'] = -1
             elif case_i == 5 or case_i == 6 or case_i == 7:
-                deltas.dy = 1
+                deltas['location']['dy'] = 1
+
             else:
-                deltas.dy = 0
+                deltas['location']['dy'] = 0
             scaling = 1
             speed = move_param['grid_spacing'] * deltas
     elif move_mode is 'free_run':
@@ -74,9 +87,12 @@ def next_pos(motion_vec, move_mode, move_param=None):
     else:
         raise ValueError('grid_mode is not supported')
     toreturn = motion_vec
-    toreturn['location']['x'] = toreturn['location']['x'] + speed['dx']
-    toreturn['location']['y'] = toreturn['location']['y'] + speed['dy']
-    toreturn['location']['z'] = toreturn['location']['z'] + speed['dz']
+    toreturn['location']['x'] = (toreturn['location']['x'] +
+                                 speed['location']['dx'])
+    toreturn['location']['y'] = (toreturn['location']['y'] +
+                                 speed['location']['dy'])
+    toreturn['location']['z'] = (toreturn['location']['z'] +
+                                 speed['location']['dz'])
     # toreturn.loc[['x', 'y', 'z']] += speed.rename({'dx': 'x',
     #                                               'dy': 'y',
     #                                               'dz': 'z'}) * scaling
@@ -88,13 +104,15 @@ def closest_pos(pos, positions):
 
     :param pos: the position to find (a pandas Series with ['x','y','z']
     :param positions: the possible closest positions
-    (a pandas dataframe with ['x','y','z'])
+    (a pandas dataframe with
+    [['location','x'],['location','y'],['location','z']])
     """
+
     euclidian_dist = np.sqrt(
-        (pos['location']['x'] - positions['location']['x'])**2
-        + (pos['location']['y'] - positions['location']['y'])**2
-        + (pos['location']['z'] - positions['location']['z'])**2)
-    return positions.loc[euclidian_dist.idxmin(), :]
+             (pos['location']['x'] - positions['location']['x'])**2
+             + (pos['location']['y'] - positions['location']['y'])**2
+             + (pos['location']['z'] - positions['location']['z'])**2)
+    return positions.loc[euclidian_dist.idxmin()]
 
 
 def closest_pos_memory_friendly(pos, database):
diff --git a/navipy/moving/test_agent.py b/navipy/moving/test_agent.py
index 68b8406..b951ce6 100644
--- a/navipy/moving/test_agent.py
+++ b/navipy/moving/test_agent.py
@@ -33,8 +33,8 @@ class BrainTest(Brain):
                       ('location', 'dz'), (convention, 'dalpha_0'),
                       (convention, 'dalpha_1'), (convention, 'dalpha_2')]
         index_vel = pd.MultiIndex.from_tuples(tuples_vel,
-                                          names=['position',
-                                                 'orientation'])
+                                              names=['position',
+                                                     'orientation'])
         self.__velocity_col = index_vel
         self.__posorient_vel_col = self.__velocity_col.copy()
         # self.__posorient_vel_col.extend(self.__velocity_col)
@@ -64,8 +64,8 @@ class TestNavipyMovingAgent(unittest.TestCase):
                       ('location', 'dz'), (convention, 'dalpha_0'),
                       (convention, 'dalpha_1'), (convention, 'dalpha_2')]
         index_vel = pd.MultiIndex.from_tuples(tuples_vel,
-                                          names=['position',
-                                                 'orientation'])
+                                              names=['position',
+                                                     'orientation'])
         self.__velocity_col = index_vel
         self.__posorient_vel_col = self.__posorient_col
         # self.__posorient_vel_col.extend(self.__velocity_col)
@@ -89,7 +89,7 @@ class TestNavipyMovingAgent(unittest.TestCase):
     def test_move_gridagent(self):
         agent = naviagent.GridAgent(self.brain)
         initposorient = None
-        with warnings.catch_warnings(record=True) as w:
+        with warnings.catch_warnings(record=True):
             initposorient = self.brain.posorients.loc[13, :]
         initposovel = pd.Series(data=0,
                                 index=self.__posorient_vel_col)
@@ -97,10 +97,15 @@ class TestNavipyMovingAgent(unittest.TestCase):
         agent.posorient = initposovel
         with self.assertRaises(AttributeError):
             agent.move()
+        tuples = [('location', 'dx'), ('location', 'dy'),
+                  ('location', 'dz')]
+        index = pd.MultiIndex.from_tuples(tuples,
+                                          names=['position',
+                                                 'orientation'])
         mode_move = {'mode': 'on_cubic_grid',
                      'param': {'grid_spacing':
                                pd.Series(data=1,
-                                         index=['dx', 'dy', 'dz'])}}
+                                         index=index)}}
         agent.mode_of_motion = mode_move
         with warnings.catch_warnings(record=True) as w:
             agent.move()
@@ -119,10 +124,15 @@ class TestNavipyMovingAgent(unittest.TestCase):
         agent.posorient = initposovel
         with self.assertRaises(AttributeError):
             agent.fly(max_nstep=10)
+        tuples = [('location', 'dx'), ('location', 'dy'),
+                  ('location', 'dz')]
+        index = pd.MultiIndex.from_tuples(tuples,
+                                          names=['position',
+                                                 'orientation'])
         mode_move = {'mode': 'on_cubic_grid',
                      'param': {'grid_spacing':
                                pd.Series(data=1,
-                                         index=['dx', 'dy', 'dz'])}}
+                                         index=index)}}
         agent.mode_of_motion = mode_move
         agent.fly(max_nstep=10)
         obtained = agent.posorient
diff --git a/navipy/moving/test_maths.py b/navipy/moving/test_maths.py
index 0917850..41a446f 100644
--- a/navipy/moving/test_maths.py
+++ b/navipy/moving/test_maths.py
@@ -26,8 +26,14 @@ class TestNavipyMovingMaths(unittest.TestCase):
     def test_notsupported_mofm(self):
         """ Test that a TypeError is correctly raised
         """
+        tuples = [('location', 'x'), ('location', 'y'),
+                  ('location', 'z'), ('location', 'dx'),
+                  ('location', 'dy'), ('location', 'dz')]
+        index = pd.MultiIndex.from_tuples(tuples,
+                                          names=['position',
+                                                 'orientation'])
         motion_vec = pd.Series(data=0,
-                               index=['x', 'y', 'z', 'dx', 'dy', 'dz'])
+                               index=index)
         move_mode = 'NotSupportedMode'
         mode_param = dict()
         mode_param['grid_spacing'] = 1
@@ -44,8 +50,14 @@ class TestNavipyMovingMaths(unittest.TestCase):
         test this by series equality.
         """
         # Test if stay at same position.
+        tuples = [('location', 'x'), ('location', 'y'),
+                  ('location', 'z'), ('location', 'dx'),
+                  ('location', 'dy'), ('location', 'dz')]
+        index = pd.MultiIndex.from_tuples(tuples,
+                                          names=['position',
+                                                 'orientation'])
         motion_vec = pd.Series(data=0,
-                               index=['x', 'y', 'z', 'dx', 'dy', 'dz'])
+                               index=index)
         move_mode = 'on_cubic_grid'
         mode_param = dict()
         mode_param['grid_spacing'] = 1
@@ -61,14 +73,30 @@ class TestNavipyMovingMaths(unittest.TestCase):
         22.5 degrees modulo 45 degrees. We therefore test the functions
         close to each instability.
         """
-        positions = pd.DataFrame({'x': [0, 0, 0, 1, 1, 1, 2, 2, 2],
-                                  'y': [0, 1, 2, 0, 1, 2, 0, 1, 2],
-                                  'z': [0, 0, 0, 0, 0, 0, 0, 0, 0]},
+        tuples = [('location', 'x'), ('location', 'y'),
+                  ('location', 'z')]
+        index = pd.MultiIndex.from_tuples(tuples,
+                                          names=['position',
+                                                 'orientation'])
+        positions = pd.DataFrame(data=[[0, 0, 0],
+                                       [0, 1, 0],
+                                       [0, 2, 0],
+                                       [1, 0, 0],
+                                       [1, 1, 0],
+                                       [1, 2, 0],
+                                       [2, 0, 0],
+                                       [2, 1, 0],
+                                       [2, 2, 0]],
+                                 columns=index,
                                  dtype=np.float)
         move_mode = 'on_cubic_grid'
         move_param = dict()
+        tuples = [('location', 'dx'), ('location', 'dy'),
+                  ('location', 'dz')]
+        index = pd.MultiIndex.from_tuples(tuples,
+                                          names=['position', 'orientation'])
         move_param['grid_spacing'] = pd.Series(data=1,
-                                               index=['dx', 'dy', 'dz'])
+                                               index=index)
         expected_dict = dict()
         expected_dict[-22] = 7  # [2,1]
         expected_dict[22] = 7
@@ -87,14 +115,18 @@ class TestNavipyMovingMaths(unittest.TestCase):
         expected_dict[293] = 6  # [2, 0]
         expected_dict[337] = 6
         expected_dict[338] = 7  # equivalent to -22
+        tuples = [('location', 'dx'), ('location', 'dy'),
+                  ('location', 'dz'), ('location', 'x'),
+                  ('location', 'y'), ('location', 'z')]
+        index = pd.MultiIndex.from_tuples(tuples,
+                                          names=['position', 'orientation'])
 
         for angle, exp_i in expected_dict.items():
             alpha = np.deg2rad(angle)
             motion_vec = pd.Series(
                 data=[1, 1, 0,
                       np.cos(alpha), np.sin(alpha), 0],
-                index=['x', 'y', 'z',
-                       'dx', 'dy', 'dz'],
+                index=index,
                 dtype=np.float)
             newpos = navimaths.next_pos(motion_vec,
                                         move_mode,
-- 
GitLab