Skip to content
test_func.py 8.77 KiB
Newer Older
""" Unit tests

Copyright (C) 2016-2018 European Synchrotron Radiation Facility

Permission is hereby granted, free of charge, to any person obtaining a 
copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject to 
the following conditions:

The above copyright notice and this permission notice shall be included 
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

__author__ = ['Ruxandra Cojocaru', 'Sebastien Berujon']
__contact__ = 'cojocaru@esrf.fr; sebastien.berujon@esrf.fr'
__license__ = 'MIT'
__copyright__ = 'European Synchrotron Radiation Facility, Grenoble, France'
__date__ = '13/08/2018'

Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
import unittest
import numpy as np
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed

class FuncTestCase(unittest.TestCase):
    """Tests for `func.py`."""

    #~ def test_test_err_false_assert(self):
        #~ """Do false assertions successfully trigger an error?"""
        #~ for assertion in [3==5]:#, False, 'False', 0]:
             #~ with self.assertRaises(SystemError):
                #~ func.test_err(assertion)


    def test_test_err_true_assert(self):
        """Do true assertions fail to trigger an error?"""
        for assertion in [3==3, True, 'string', -1, 1, 5]:
            self.assertFalse(func.test_err(assertion, verbose = False))


    def test_test_warn_false_assert(self):
        """Do false assertions successfully trigger a warning?"""
        for assertion in [3==5, False, 0]:
            self.assertTrue(func.test_warn(assertion, verbose = False))



    def test_test_warn_true_assert(self):
        """Do true assertions fail to trigger a warning?"""
        for assertion in [3==3, True, 'True', 1]:
            self.assertFalse(func.test_warn(assertion, verbose = False))


Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
        """Test if ROI applied correctly to input image"""
        
        image = np.random.rand(20, 20)
        ROI1 = [2, 18, 2, 18]
        ROI2 = [5, 10, 4, 11]
        ROI3 = [7, 17, 3, 16]
        for ROI in [ROI1, ROI2, ROI3]:
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
            shape_exp = (ROI[1] - ROI[0] + 1, ROI[3] - ROI[2] + 1)
            shape_out = func.roi_select(image, ROI).shape
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
            self.assertEqual(shape_out, shape_exp)

    
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
        """Test if we obtain expected recalculated ROI"""

Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed

        roi_IO1 = np.array([[1, 1, 1, 1], [1, 1, 1, 1]])
        roi_IO2 = np.array([[1, 20, 1, 20], [1, 20, 1, 20]])
        roi_IO3 = np.array([[2, 19, 1, 21], [1, 18, 1, 20]])
        #~ roi_IO4 = [[30, 40, 10, 15], []] # no overlap, gives error
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed

        for roi_IO in [roi_IO1, roi_IO2, roi_IO3]:
            np.testing.assert_array_equal(roi_IO[1],
                                          func.roi_recalc(ROI, roi_IO[0]))
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed

    def test_crop_rect(self):
        """Test if cropperd image has expected shape"""
        
        image = np.random.rand(20, 20)
        rect1 = [2, 2, 17, 17]
        rect2 = [5, 4, 6, 8]
        rect3 = [7, 3, 11, 14]

        for rect in [rect1, rect2, rect3]:
            shape_exp = (rect[3], rect[2])
            shape_out = func.crop_rect(image, rect).shape
            self.assertEqual(shape_out, shape_exp)

    def test_plane_fit(self):
        """Is the input of a perfect plane equal to the output (offset = 0)?"""
        
        a = 1.0
        b = 2.0
        c = 3.0
        d = 4.0
        unit = 1.5
        steps = 20
        x = np.linspace(0, unit*steps, num = steps+1)
        y = np.linspace(0, unit*steps, num = steps+1)
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
        X, Y = np.meshgrid(x, y)

Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
        input_plane = np.around(input_plane - np.mean(input_plane), 
                                 decimals = 4)
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
        np.testing.assert_array_equal(input_plane, 
                                      np.around(func.plane_fit(input_plane)[0], 
                                      decimals = 4))
        # Test slope in X (horizontal) direction
        np.testing.assert_array_equal(a / d * unit, 
                                      np.around(func.plane_fit(input_plane)[1], 
                                      decimals = 4))
        # Test slope in Y (vertical) direction
        np.testing.assert_array_equal(b / d * unit, 
                                      np.around(func.plane_fit(input_plane)[2], 
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
                                      decimals = 4))
                                      
    #~ def test_mask_builder(self):
        #~ """Test returns expected mask center"""
        #~ 
        #~ image = np.random.rand(99, 99)
    
    def test_mask_builder_centre(self):
        """Test it it returns expected mask center"""
        
        def makeGaussian(size, fwhm = 3, center=None):
            """ Make a square gaussian kernel.

            size is the length of a side of the square
            fwhm is full-width-half-maximum, which
            can be thought of as an effective radius.
            """

            x = np.arange(0, size, 1, float)
            y = x[:,np.newaxis]

            if center is None:
                x0 = y0 = size // 2
            else:
                x0 = center[0]
                y0 = center[1]

            return np.exp(-4*np.log(2) * ((x-x0)**2 + (y-y0)**2) / fwhm**2)
        
        m_hsize = 15
        xshift = 5
        yshift = 15

        for g_size in [99, 100]:
            image = makeGaussian(g_size)

            np.testing.assert_array_equal(func.mask_builder(image, m_hsize)[1], 
                                          (g_size//2, g_size//2))

            image[yshift:, :] = image[:-yshift, :]
            image [:yshift, :]= np.zeros((yshift, g_size))

            np.testing.assert_array_equal(func.mask_builder(image, m_hsize)[1],  
                                          (g_size//2 + yshift, g_size//2))

            image[:, xshift:] = image[:, :-xshift]
            image [:, :xshift]= np.zeros((g_size, xshift))

            np.testing.assert_array_equal(func.mask_builder(image, m_hsize)[1],  
                                          (g_size//2 + yshift, 
                                          g_size//2 + xshift))
        
    def test_mask_builder_mask(self):
        """Test it it returns expected output (big) mask
        NOT SURE: I am kind of testing two things in one test...
        """
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
        
        def makeGaussian(size, fwhm = 3, center=None):
            """ Make a square gaussian kernel.
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed

            size is the length of a side of the square
            fwhm is full-width-half-maximum, which
            can be thought of as an effective radius.
            """

            x = np.arange(0, size, 1, float)
            y = x[:,np.newaxis]

            if center is None:
                x0 = y0 = size // 2
            else:
                x0 = center[0]
                y0 = center[1]

            return np.exp(-4*np.log(2) * ((x-x0)**2 + (y-y0)**2) / fwhm**2)
        
        for m_half_size in [15, 20, 48]:
            for g_size in [99, 100]:
                image = makeGaussian(g_size)
                [big_mask, mask_centre] = func.mask_builder(image, m_half_size)
                # Test if output (big) mask has correct shape (same as input)
                np.testing.assert_array_equal(big_mask.shape, image.shape)
                # Test if output (big) mask has correct mask size (diameter)
                # Horizontal direction
                # Left
                i1 = (big_mask[mask_centre[0], :] == True).argmax()
                # Right
                i2 = (big_mask.shape[1] 
                      - (big_mask[mask_centre[0], ::-1] == True).argmax())
                self.assertEqual(i2 - i1, 2 * m_half_size + 1)
                # Vertical direction
                # Left
                i1 = (big_mask[:, mask_centre[1]] == True).argmax()
                # Right
                i2 = (big_mask.shape[0] 
                      - (big_mask[::-1, mask_centre[1]] == True).argmax())
                self.assertEqual(i2 - i1, 2 * m_half_size + 1)
                
Ruxandra Cojocaru's avatar
Ruxandra Cojocaru committed
#~ class MyTest(unittest.TestCase)
#~ 
   #~ def setUp(self):
       #~ self.testdata = open(TESTDATA_FILENAME).read()
#~ 
   #~ def test_something(self):
       #~ ....

if __name__ == '__main__':

    unittest.main()