Example #1
0
    def makeBox(self):
        self.box = BoundingBox(points=((self.left, self.bottom), (self.right,
                                                                  self.top)))

        self.ct = SheetCoordinateSystem(self.box, self.density, self.density)

        # float bounds for matrix coordinates: these
        # values are actually outside the matrix
        self.rbound = self.density * (self.top - self.bottom)
        self.cbound = self.density * (self.right - self.left)

        #self.cbound = int(self.density*(self.right-self.left)) / float((self.right-self.left))
        #self.rbound = int(self.density*(self.top-self.bottom)) / float((self.top-self.bottom))

        # CEBALERT: this is supposed to be a small distance
        D = 0.00001

        # Sheet values around the edge of the BoundingBox
        self.just_in_right_x = self.right - D
        self.just_in_bottom_y = self.bottom + D
        self.just_out_top_y = self.top + D
        self.just_out_left_x = self.left - D

        # Matrix values around the edge of the matrix
        self.just_out_right_idx = self.rbound + D
        self.just_out_bottom_idx = self.cbound + D
        self.just_out_top_idx = 0.0 - D
        self.just_out_left_idx = 0.0 - D
    def test_composite_pattern_basic(self):
        """
        Test that a composite pattern consisting of just one Gaussian
        is the same as that actual Gaussian pattern, and that a
        composite pattern of two rectangles is the same as adding the
        two individual matrices.
        """
        bbox = BoundingBox(radius=0.5)
        g = Gaussian(size=0.2, aspect_ratio=0.5, orientation=0, x=0.2, y=-0.03)
        c = Composite(generators=[g], bounds=bbox, xdensity=7, ydensity=7)
        assert_array_equal(g(bounds=bbox, xdensity=7, ydensity=7), c())

        r1 = Rectangle(size=0.2,
                       aspect_ratio=1,
                       x=0.3,
                       y=0.3,
                       orientation=0,
                       smoothing=0.0)
        r2 = Rectangle(size=0.2,
                       aspect_ratio=1,
                       x=-0.3,
                       y=-0.3,
                       orientation=0,
                       bounds=BoundingBox(radius=0.8),
                       xdensity=2,
                       smoothing=0.0)
        c_true = r1(bounds=bbox, xdensity=7, ydensity=7) + r2(
            bounds=bbox, xdensity=7, ydensity=7)
        c = Composite(generators=[r1, r2], bounds=bbox, xdensity=7, ydensity=7)
        assert_array_equal(c(), c_true)
Example #3
0
    def setUp(self):

        self.sim = Simulation()

        self.sim['Dest'] = CFSheet(nominal_density=10,nominal_bounds=BoundingBox(radius=0.5))
        self.sim['Src'] = CFSheet(nominal_density=10,nominal_bounds=BoundingBox(radius=0.5))

        self.sim.connect('Src','Dest',
                         connection_type = ResizableCFProjection,
                         )
Example #4
0
    def test_coordinate_position(self):
        """
        these tests duplicate some of the earlier ones,
        except these use a matrix with non-integer
        (right-left) and (top-bottom). This is an important
        test case for the definition of density; without it,
        the tests above could be passed by a variety of
        sheet2matrix, bounds2shape functions, etc.

        CEBALERT: transfer the box to TestBox3Coordinates and have
        these tests run in the framework.
        """
        l, b, r, t = (-0.8, -0.8, 0.8, 0.8)
        # mimics that a sheet recalculates its density)
        density = int(16 * (r - l)) / float(r - l)

        bounds = BoundingBox(points=((l, b), (r, t)))

        ct = SheetCoordinateSystem(bounds, density, density)

        self.assertEqual(ct.sheet2matrixidx(0.8, 0.8), (0, 24 + 1))
        self.assertEqual(ct.sheet2matrixidx(0.0, 0.0), (12, 12))
        self.assertEqual(ct.sheet2matrixidx(-0.8, -0.8), (24 + 1, 0))
        self.assertEqual(
            ct.matrixidx2sheet(24, 0),
            (((r - l) / int(density * (r - l)) / 2.0) + l, (t - b) / int(density * (t - b)) / 2.0 + b),
        )
        self.assertEqual(
            ct.matrixidx2sheet(0, 0),
            (
                ((r - l) / int(density * (r - l)) / 2.0) + l,
                (t - b) / int(density * (t - b)) * (int(density * (t - b)) - 0.5) + b,
            ),
        )

        x, y = ct.matrixidx2sheet(0, 0)
        self.assertTrue(bounds.contains(x, y))
        self.assertEqual((0, 0), ct.sheet2matrixidx(x, y))

        x, y = ct.matrixidx2sheet(25, 25)
        self.assertFalse(bounds.contains(x, y))
        self.assertNotEqual((24, 24), ct.sheet2matrixidx(x, y))

        x, y = ct.matrixidx2sheet(0, 24)
        self.assertTrue(bounds.contains(x, y))
        self.assertEqual((0, 24), ct.sheet2matrixidx(x, y))

        x, y = ct.matrixidx2sheet(24, 0)
        self.assertTrue(bounds.contains(x, y))
        self.assertEqual((24, 0), ct.sheet2matrixidx(x, y))
Example #5
0
    def __init__(self,cf,input_sheet,x=0.0,y=0.0,template=BoundingBox(radius=0.1),
                 mask=patterngenerator.Constant(),
                 min_matrix_radius=1):
        """
        From an existing copy of ConnectionField (CF) that acts as a
        template, create a new CF that shares weights with the
        template CF.  Copies all the properties of CF to stay
        identical except the weights variable that actually contains
        the data.
        
        The only difference from a normal CF is that the weights of
        the CF are implemented as a numpy view into the single master
        copy of the weights stored in the CF template.
        """
        # CEBALERT: There's no call to super's __init__; see JAHACKALERT
        # below.
        template = copy(template)

        if not isinstance(template,Slice):
            template = Slice(template,input_sheet,force_odd=True,
                             min_matrix_radius=min_matrix_radius)

        # Note: if passed in, mask is shared between CFs (but not if created here)
        if not hasattr(mask,'view'):
            mask = _create_mask(patterngenerator.Constant(),
                               template.compute_bounds(input_sheet),
                               input_sheet,True,0.5) 



        self._has_norm_total=False
        self.mask=mask 
        weights_slice = self._create_input_sheet_slice(input_sheet,x,y,template,min_matrix_radius=min_matrix_radius)
        self.weights = weights_slice.submatrix(cf.weights)
    def test_vertical_oddimage_evensheet__horizontal_evenimage_evensheet(self):
        """
        Test vertical positioning for even sheet, odd image and horizontal
        positioning for even image, even sheet.
        """
        image_array = np.array(
[[  96.59090909,  96.59090909,  96.59090909,  96.59090909,  96.59090909,
         96.59090909,  96.59090909,  96.59090909,],
 [   0.        ,  34.        ,  68.        , 102.        , 136.        ,
        255.   ,   0.        ,   0.             ,],
 [   0.        ,  34.        ,  68.        , 102.        , 136.        ,
        255.        , 255.        ,   0.        ,],
 [   0.        ,  34.        ,  68.        , 102.        , 136.        ,
        255.        , 255.        , 255.        ,],
 [ 255.        ,   0.        , 255.        ,   0.        , 255.        ,
          0.        , 255.        ,   0.        ,],
 [   0.        , 255.        ,   0.        , 255.        ,   0.        ,
        255.        ,   0.        , 255.        ,],
 [  96.59090909,  96.59090909,  96.59090909,  96.59090909,  96.59090909,
         96.59090909,  96.59090909,  96.59090909,],
 [  96.59090909,  96.59090909,  96.59090909,  96.59090909,  96.59090909,
         96.59090909,  96.59090909,  96.59090909,]],dtype=np.float)


        image = FileImage(filename = resolve_path('topo/tests/unit/testimage.pgm'),
                      xdensity=8,
                      ydensity=8,
                      bounds=BoundingBox(radius=0.5),
                      output_fns=[])

        ps = image.pattern_sampler
        ps.size_normalization='original'
        ps.whole_pattern_output_fns=[]

        assert_array_almost_equal(image_array,image())
Example #7
0
    def __call__(self,x):
        rows,cols = x.shape
        radius = self.density*self.kernel_radius
        crop_radius = int(max(1.25,radius*self.crop_radius_multiplier))

        # find out the matrix coordinates of the winner
        wr,wc = array_argmax(x)

        # convert to sheet coordinates
        wy = rows-wr-1

        # Optimization: Calculate the bounding box around the winner
        # in which weights will be changed
        cmin = max(wc-crop_radius,  0)
        cmax = min(wc+crop_radius+1,cols)
        rmin = max(wr-crop_radius,  0)
        rmax = min(wr+crop_radius+1,rows)
        ymin = max(wy-crop_radius,  0)
        ymax = min(wy+crop_radius+1,rows)
        bb = BoundingBox(points=((cmin,ymin), (cmax,ymax)))

        # generate the kernel matrix and insert it into the correct
        # part of the output array
        kernel = self.neighborhood_kernel_generator(bounds=bb,xdensity=1,ydensity=1,
                                                    size=2*radius,x=wc+0.5,y=wy+0.5)
        x *= 0.0
        x[rmin:rmax,cmin:cmax] = kernel
Example #8
0
    def makeBox(self):
        self.box = BoundingBox(points=((self.left,self.bottom),
                                       (self.right,self.top)))

        self.ct = SheetCoordinateSystem(self.box,self.density,self.density)

        # float bounds for matrix coordinates: these
        # values are actually outside the matrix
        self.rbound = self.density*(self.top-self.bottom)
        self.cbound = self.density*(self.right-self.left)

        #self.cbound = int(self.density*(self.right-self.left)) / float((self.right-self.left))
        #self.rbound = int(self.density*(self.top-self.bottom)) / float((self.top-self.bottom))


        # CEBALERT: this is supposed to be a small distance
        D = 0.00001

        # Sheet values around the edge of the BoundingBox
        self.just_in_right_x = self.right - D
        self.just_in_bottom_y = self.bottom + D
        self.just_out_top_y = self.top + D
        self.just_out_left_x = self.left - D

        # Matrix values around the edge of the matrix
        self.just_out_right_idx = self.rbound + D
        self.just_out_bottom_idx = self.cbound + D
        self.just_out_top_idx = 0.0 - D
        self.just_out_left_idx = 0.0 - D
Example #9
0
    def test_bounds2slice(self):

        # test that if you ask to slice the matrix with the sheet's BoundingBox, you
        # get back the whole matrix
        sheet_bb = BoundingBox(points=((-0.5, -0.5), (0.5, 0.5)))
        ct = SheetCoordinateSystem(sheet_bb, 10)

        slice_ = Slice(sheet_bb, ct)
        true_slice = (0, 10, 0, 10
                      )  # inclusive left boundary, exclusive right boundary
        self.assertEqual(tuple(slice_.tolist()), true_slice)

        # for the following tests, the values have been all computed by hand and then
        # tested (by JC). The boundingbox and density tested have been chosen randomly,
        # then drawn to get the slice from it.

        # Test with 20 density.
        ct = SheetCoordinateSystem(sheet_bb, 20, 20)
        bb = BoundingBox(points=((-0.05, -0.20), (0.20, 0.05)))
        slice_ = Slice(bb, ct)

        true_slice = (9, 14, 9, 14)
        self.assertEqual(tuple(slice_.tolist()), true_slice)

        bb = BoundingBox(points=((-0.40, 0), (-0.30, 0.30)))
        slice_ = Slice(bb, ct)
        true_slice = (4, 10, 2, 4)
        self.assertEqual(tuple(slice_.tolist()), true_slice)

        bb = BoundingBox(points=((0.15, 0.10), (0.30, 0.30)))
        slice_ = Slice(bb, ct)
        true_slice = (4, 8, 13, 16)
        self.assertEqual(tuple(slice_.tolist()), true_slice)

        bb = BoundingBox(points=((-0.05, -0.45), (0.10, -0.25)))
        slice_ = Slice(bb, ct)
        true_slice = (15, 19, 9, 12)
        self.assertEqual(tuple(slice_.tolist()), true_slice)

        # test with 7 density sheet.

        bb = BoundingBox(points=((-0.5 + 2.0 / 7.0, 0.5 - 2.0 / 7.0),
                                 (-0.5 + 4.0 / 7.0, 0.5)))
        ct = SheetCoordinateSystem(sheet_bb, 7)

        slice_ = Slice(bb, ct)
        true_slice = (0, 2, 2, 4)
        self.assertEqual(tuple(slice_.tolist()), true_slice)

        #(4x4 matrix)
        ct = SheetCoordinateSystem(BoundingBox(radius=0.2),
                                   xdensity=10,
                                   ydensity=10)
        test_bounds = BoundingBox(radius=0.1)
        slice_ = Slice(test_bounds, ct)
        r1, r2, c1, c2 = slice_
        self.assertEqual((r1, r2, c1, c2), (1, 3, 1, 3))
Example #10
0
    def test_connection_field_like(self):
        # test a ConnectionField-like example
        sheet = Sheet(nominal_density=10,nominal_bounds=BoundingBox(radius=0.5))
        cf_bounds = BoundingBox(points=((0.3,0.3),(0.6,0.6)))

        slice_ = Slice(cf_bounds,sheet)
        slice_.crop_to_sheet(sheet)

        # check it's been cropped to fit onto sheet...
        self.assertEqual(slice_.tolist(),[0,2,8,10])

        # now check that it gives the correct bounds...
        cropped_bounds = slice_.compute_bounds(sheet)
        
        true_cropped_bounds = BoundingBox(points=((0.3,0.3),(0.5,0.5)))
        for a,b in zip(cropped_bounds.lbrt(),true_cropped_bounds.lbrt()):
            self.assertAlmostEqual(a,b)
Example #11
0
    def test_connection_field_like(self):
        # test a ConnectionField-like example
        sheet = Sheet(nominal_density=10,nominal_bounds=BoundingBox(radius=0.5))
        cf_bounds = BoundingBox(points=((0.3,0.3),(0.6,0.6)))

        slice_ = Slice(cf_bounds,sheet)
        slice_.crop_to_sheet(sheet)

        # check it's been cropped to fit onto sheet...
        self.assertEqual(slice_.tolist(),[0,2,8,10])

        # now check that it gives the correct bounds...
        cropped_bounds = slice_.compute_bounds(sheet)

        true_cropped_bounds = BoundingBox(points=((0.3,0.3),(0.5,0.5)))
        for a,b in zip(cropped_bounds.lbrt(),true_cropped_bounds.lbrt()):
            self.assertAlmostEqual(a,b)
    def test_constant(self):
        """
        Constant overrides PatternGenerator's usual matrix creation.
        """
        pattern_bounds = BoundingBox(points=((0.3, 0.2), (0.5, 0.5)))

        pattern_target = array([[1, 1], [1, 1], [1, 1]])

        c = Constant(bounds=pattern_bounds, xdensity=10.0, ydensity=10)
        assert_array_equal(c(), pattern_target)
Example #13
0
 def __call__(self,x):
     ###JABHACKALERT: Need to set it up to be independent of
     #density; right now only things like random numbers work
     #reasonably
     rows,cols = x.shape
     bb = BoundingBox(points=((0,0), (rows,cols)))
     generated_pattern = self.generator(bounds=bb,xdensity=1,ydensity=1).transpose()
     new_pattern = self.operator(x, generated_pattern)
     x *= 0.0
     x += new_pattern
Example #14
0
    def test_a_basic_patterngenerator(self):
        pattern_bounds = BoundingBox(points=((0.3,0.2),(0.5,0.5)))

        pattern_target = array([[1,1],
                                [1,1],
                                [1,1]])

        r = Rectangle(bounds=pattern_bounds,xdensity=10,
                      ydensity=10,aspect_ratio=1,size=1,smoothing=0.0)
        assert_array_equal(r(),pattern_target)
Example #15
0
    def test_composite_pattern_moves(self):
        """
        Test that moving a composite pattern yields the correct pattern.
        """
        bbox=BoundingBox(radius=0.5)
        g = Gaussian(size=0.2,aspect_ratio=0.5,orientation=pi/3,x=0,y=0)
        c = Composite(generators=[g],x=-0.3,y=0.4,xdensity=4,ydensity=4,bounds=bbox)
        g_moved = g(x=-0.3,y=0.4,xdensity=4,ydensity=4,bounds=bbox)

        assert_array_equal(c(),g_moved)
Example #16
0
    def _compute_depth_map(self, shape):
        (d1, d2) = shape

        (min_lim, max_lim) = self.limits
        self.raw_depth_map = self.distribution(name='ScatterDepth',
                                               xdensity=d1,
                                               ydensity=d2,
                                               bounds=BoundingBox(radius=0.5))

        bin_edges = list(np.linspace(min_lim, max_lim, self.depth))
        discretized = np.digitize(self.raw_depth_map.flatten(), bin_edges)
        # Out of bounds bins (to +inf) need to be pulled back in.
        discretized[discretized == len(bin_edges)] = len(bin_edges) - 1
        return discretized.reshape(*shape)
    def test_fit_shortest(self):
        """
        Test that the shorter dimension is made to fit 1.0, while the other
        is scaled by the same factor.
        """
        ### 15 units represent 1.0 in sheet coordinates.
        image_array = np.array(
 [[  34.,  68.,  68.,  68., 102., 102., 102., 136., 136., 136., 255., 255., 255.,
            0.,   0.,],
 [  34.,  68.,  68.,  68., 102., 102., 102., 136., 136., 136., 255., 255., 255.,
            0.,   0.,],
 [  34.,  68.,  68.,  68., 102., 102., 102., 136., 136., 136., 255., 255., 255.,
            0.,   0.,],
 [  34.,  68.,  68.,  68., 102., 102., 102., 136., 136., 136., 255., 255., 255.,
          255., 255.,],
 [  34.,  68.,  68.,  68., 102., 102., 102., 136., 136., 136., 255., 255., 255.,
          255., 255.,],
 [  34.,  68.,  68.,  68., 102., 102., 102., 136., 136., 136., 255., 255., 255.,
          255., 255.,],
 [  34.,  68.,  68.,  68., 102., 102., 102., 136., 136., 136., 255., 255., 255.,
          255., 255.,],
 [  34.,  68.,  68.,  68., 102., 102., 102., 136., 136., 136., 255., 255., 255.,
          255., 255.,],
 [  34.,  68.,  68.,  68., 102., 102., 102., 136., 136., 136., 255., 255., 255.,
          255., 255.,],
 [   0., 255., 255., 255.,   0.,   0.,   0., 255., 255., 255.,   0.,   0.,   0.,
          255., 255.,],
 [   0., 255., 255., 255.,   0.,   0.,   0., 255., 255., 255.,   0.,   0.,   0.,
          255., 255.,],
 [   0., 255., 255., 255.,   0.,   0.,   0., 255., 255., 255.,   0.,   0.,   0.,
          255., 255.,],
 [ 255.,   0.,   0.,   0., 255., 255., 255.,   0.,   0.,   0., 255., 255., 255.,
            0.,   0.,],
 [ 255.,   0.,   0.,   0., 255., 255., 255.,   0.,   0.,   0., 255., 255., 255.,
            0.,   0.,],
 [ 255.,   0.,   0.,   0., 255., 255., 255.,   0.,   0.,   0., 255., 255., 255.,
            0.,   0.,]])


        image = FileImage(filename = resolve_path('topo/tests/unit/testimage.pgm'),
                      xdensity=15,
                      ydensity=15,
                      output_fns=[],
                      bounds=BoundingBox(radius=0.5))

        ps = image.pattern_sampler
        ps.size_normalization='fit_shortest'
        ps.whole_pattern_output_fns=[]

        assert_array_almost_equal(image_array,image())
Example #18
0
    def test_orientation_and_rotation(self):
        """
        Test that a pattern is drawn with the correct orientation,
        and is rotated correctly.
        """
        ### Test initial orientation and 90-degree rotation
        target = array([[0, 0, 0, 0, 0, 0],
                        [0, 0, 1, 1, 0, 0],
                        [0, 0, 1, 1, 0, 0],
                        [0, 0, 1, 1, 0, 0],
                        [0, 0, 1, 1, 0, 0],
                        [0, 0, 0, 0, 0, 0]])

        bounds = BoundingBox(radius=0.3)
        xdensity = 10
        ydensity = 10
        width = 2.0/xdensity
        height = 4.0/ydensity
        
        rect = Rectangle(size=height,
                         aspect_ratio=width/height,smoothing=0.0,
                         xdensity=xdensity,ydensity=ydensity,bounds=bounds)

        assert_array_equal(rect(),target)
        assert_array_equal(rect(orientation=pi/2),rot90(target))


        ### 45-degree rotation about the origin
        rot_45 = array([[0, 0, 0, 0, 0, 0],
                        [0, 0, 1, 0, 0, 0],
                        [0, 1, 1, 1, 0, 0],
                        [0, 0, 1, 1, 1, 0],
                        [0, 0, 0, 1, 0, 0],
                        [0, 0, 0, 0, 0, 0]])
                       
        assert_array_equal(rect(orientation=pi/4),rot_45)


        ### 45-degree rotation that's not about the origin
        rot_45_offset = array([[0, 1, 0, 0, 0, 0],
                               [1, 1, 1, 0, 0, 0],
                               [0, 1, 1, 1, 0, 0],
                               [0, 0, 1, 0, 0, 0],
                               [0, 0, 0, 0, 0, 0],
                               [0, 0, 0, 0, 0, 0]])

        assert_array_equal(rect(x=-1.0/xdensity,y=1.0/ydensity,orientation=pi/4),
                           rot_45_offset)
Example #19
0
def new_simulation(name=None, register=True):

    from topo.base.simulation import Simulation
    from topo.base.cf import CFSheet, CFProjection
    from topo.sheet import GeneratorSheet
    from topo.base.boundingregion import BoundingBox

    sim = Simulation(register=register, name=name)
    b = BoundingBox(radius=0.5)
    sim['GS'] = GeneratorSheet(nominal_density=2, nominal_bounds=b)
    sim['GS2'] = GeneratorSheet(nominal_density=2, nominal_bounds=b)
    sim['S'] = CFSheet(nominal_density=2, nominal_bounds=b)
    sim['S2'] = CFSheet(nominal_density=2, nominal_bounds=b)
    sim.connect('GS', 'S', connection_type=CFProjection, delay=0.05)
    sim.connect('GS', 'S2', connection_type=CFProjection, delay=0.05)
    sim.connect('GS2', 'S2', connection_type=CFProjection, delay=0.05)
    return sim
Example #20
0
    def test_Sheet_creation(self):

        # Example where the nominal x and y densities would not be equal.
        # density along x =10
        # density along y <10
        # The density along y should become 10, by adjusting the height to be 2.0
        # in this case.
        # The y center of the bounds should remain -0.0025. Hence we should get
        # a bottom bound of -1.0025 and a top one of 0.9975.
        sheet = Sheet(nominal_density=10,
                      nominal_bounds=BoundingBox(points=((-0.5,-1.005),(0.5,1.0))))

        self.assertEqual(sheet.xdensity,10)
        self.assertEqual(sheet.xdensity,sheet.ydensity)

        l,b,r,t = sheet.lbrt
        self.assertEqual(l,-0.5)
        self.assertEqual(r,0.5)
        self.assertAlmostEqual(t,0.9975)
        self.assertAlmostEqual(b,-1.0025)
Example #21
0
    def setUp(self):

        # sheet to test. As it is, its activity matrix dimension is (3,2)
        Sheet.nominal_density = 1
        Sheet.nominal_bounds = BoundingBox(points=((-1, -2), (1, 1)))
        test_sheet = Sheet()
        # simple activity arrays use to update the feature maps
        self.a1 = array([[1, 1], [1, 1], [1, 1]])
        self.a2 = array([[3, 3], [3, 3], [3, 3]])
        self.a3 = array([[0, 1], [0, 1], [0, 1]])

        # object to test for non-cyclic distributions
        self.fm1 = DistributionMatrix(test_sheet.shape,
                                      axis_range=(0.0, 1.0),
                                      cyclic=False)
        self.fm1.update(self.a1, 0.5)

        # object to for cyclic distributions
        self.fm2 = DistributionMatrix(test_sheet.shape,
                                      axis_range=(0.0, 1.0),
                                      cyclic=True)
        self.fm2.update(self.a1, 0.5)
Example #22
0
    def test_coordinate_position(self):
        """
        these tests duplicate some of the earlier ones,
        except these use a matrix with non-integer
        (right-left) and (top-bottom). This is an important
        test case for the definition of density; without it,
        the tests above could be passed by a variety of
        sheet2matrix, bounds2shape functions, etc.

        CEBALERT: transfer the box to TestBox3Coordinates and have
        these tests run in the framework.
        """
        l, b, r, t = (-0.8, -0.8, 0.8, 0.8)
        # mimics that a sheet recalculates its density)
        density = int(16 * (r - l)) / float(r - l)

        bounds = BoundingBox(points=((l, b), (r, t)))

        ct = SheetCoordinateSystem(bounds, density, density)

        self.assertEqual(ct.sheet2matrixidx(0.8, 0.8), (0, 24 + 1))
        self.assertEqual(ct.sheet2matrixidx(0.0, 0.0), (12, 12))
        self.assertEqual(ct.sheet2matrixidx(-0.8, -0.8), (24 + 1, 0))
        self.assertEqual(ct.matrixidx2sheet(24, 0),
                         (((r - l) / int(density * (r - l)) / 2.0) + l,
                          (t - b) / int(density * (t - b)) / 2.0 + b))
        self.assertEqual(ct.matrixidx2sheet(0, 0),
                         (((r - l) / int(density * (r - l)) / 2.0) + l,
                          (t - b) / int(density * (t - b)) *
                          (int(density * (t - b)) - 0.5) + b))

        x, y = ct.matrixidx2sheet(0, 0)
        self.assertTrue(bounds.contains(x, y))
        self.assertEqual((0, 0), ct.sheet2matrixidx(x, y))

        x, y = ct.matrixidx2sheet(25, 25)
        self.assertFalse(bounds.contains(x, y))
        self.assertNotEqual((24, 24), ct.sheet2matrixidx(x, y))

        x, y = ct.matrixidx2sheet(0, 24)
        self.assertTrue(bounds.contains(x, y))
        self.assertEqual((0, 24), ct.sheet2matrixidx(x, y))

        x, y = ct.matrixidx2sheet(24, 0)
        self.assertTrue(bounds.contains(x, y))
        self.assertEqual((24, 0), ct.sheet2matrixidx(x, y))
Example #23
0
    def test_stretch_to_fit(self):
        """
        Test that both image dimensions are made to fit 1.0.
        """
        ### 8 units represent 1.0 in sheet coordinates.
        image_array = array([[
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
        ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 34.,
                                 68.,
                                 102.,
                                 136.,
                                 255.,
                                 0.,
                                 0.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 34.,
                                 68.,
                                 102.,
                                 136.,
                                 255.,
                                 0.,
                                 0.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 34.,
                                 68.,
                                 102.,
                                 136.,
                                 255.,
                                 255.,
                                 0.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 34.,
                                 68.,
                                 102.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 34.,
                                 68.,
                                 102.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ]])

        image = FileImage(filename=resolve_path('tests/testimage.pgm'),
                          xdensity=8,
                          ydensity=8,
                          output_fns=[],
                          bounds=BoundingBox(radius=1.0))

        ps = image.pattern_sampler
        ps.size_normalization = 'stretch_to_fit'
        ps.whole_pattern_output_fns = []

        assert_array_almost_equal(image_array, image())
Example #24
0
class ShiftingGeneratorSheet(SequenceGeneratorSheet):
    """
    A GeneratorSheet that takes an extra input on port 'Saccade'
    that specifies a saccade command as a tuple (amplitude,direction),
    indicating the relative size and direction of the saccade in
    degrees.  The parameter visual_angle_scale defines the
    relationship between degrees and sheet coordinates.  The parameter
    saccade bounds limits the region within which the saccades may occur.
    """

    visual_angle_scale = param.Number(default=90,
                                      doc="""
        The scale factor determining the visual angle subtended by this sheet, in
        degrees per unit of sheet.""")

    saccade_bounds = BoundingRegionParameter(default=BoundingBox(radius=1.0),
                                             doc="""
        The bounds for saccades.  Saccades are constrained such that the centroid of the
        sheet bounds remains within this region.""")

    generate_on_shift = param.Boolean(default=True,
                                      doc="""
       Whether to generate a new pattern when a shift occurs.""")

    fixation_jitter = param.Number(default=0,
                                   doc="""
       Standard deviation of Gaussian fixation jitter.""")
    fixation_jitter_period = param.Number(default=10,
                                          doc="""
       Period, in time units, indicating how often the eye jitters.
       """)

    dest_ports = ["Trigger", "Saccade"]
    src_ports = ['Activity', 'Position']

    def __init__(self, **params):
        super(ShiftingGeneratorSheet, self).__init__(**params)
        self.fixation_point = self.bounds.centroid()

    def start(self):
        super(ShiftingGeneratorSheet, self).start()
        if self.fixation_jitter_period > 0:
            now = self.simulation.time()
            refix_event = PeriodicEventSequence(
                now + self.simulation.convert_to_time_type(
                    self.fixation_jitter_period),
                self.simulation.convert_to_time_type(
                    self.fixation_jitter_period),
                [FunctionEvent(0, self.refixate)])
            self.simulation.enqueue_event(refix_event)

    def input_event(self, conn, data):
        if conn.dest_port == 'Saccade':
            # the data should be (amplitude,direction)
            amplitude, direction = data
            self.shift(amplitude, direction)

    def generate(self):
        super(ShiftingGeneratorSheet, self).generate()
        self.send_output(src_port='Position',
                         data=self.bounds.aarect().centroid())

    def shift(self, amplitude, direction, generate=None):
        """
        Shift the bounding box by the given amplitude and
        direction.

        Amplitude and direction are specified in degrees, and will be
        converted using the sheet's visual_angle_scale
        parameter. Negative directions are always downward, regardless
        of whether the amplitude is positive (rightword) or negative
        (leftward).  I.e. straight-down = -90, straight up = +90.

        The generate argument indicates whether or not to generate
        output after shifting.  If generate is None, then the value of
        the sheet's generate_on_shift parameter will be used.
        """

        # JPALERT:  Right now this method assumes that we're doing
        # colliculus-style saccades. i.e. amplitude and direction
        # relative to the current position.  Technically it would
        # not be hard to also support absolute or relative x,y
        # commands, and select what style to use with either with
        # a parameter, or with a different input port (e.g. 'xy
        # relative', 'xy absolute' etc.

        # JPHACKALERT: Currently there is no support for modeling the
        # fact that saccades actually take time, and larger amplitudes
        # take more time than small amplitudes.  No clue if we should
        # do that, or how, or what gets sent out while the saccade
        # "eye" is moving.

        assert not self._out_of_bounds()

        # convert the command to x/y translation
        radius = amplitude / self.visual_angle_scale

        # if the amplitude is negative, negate the direction (so up is still up)
        if radius < 0.0:
            direction *= -1

        self._translate(radius, direction)

        if self._out_of_bounds():
            self._find_saccade_in_bounds(radius, direction)

        self.fixation_point = self.bounds.centroid()

        if generate is None:
            generate = self.generate_on_shift

        if generate:
            self.generate()

    def refixate(self):
        """
        Move the bounds toward the fixation point.

        Moves the bounds toward the fixation point specified in
        self.fixation_point, potentially with noise as specified by
        the parameter self.fixation_jitter.
        """
        self.debug("Refixating.")

        if self.fixation_jitter > 0:
            jitter_vec = random.normal(0, self.fixation_jitter, (2, ))
        else:
            jitter_vec = zeros((2, ))

        fix = asarray(self.fixation_point)
        pos = asarray(self.bounds.centroid())
        refix_vec = (fix - pos) + jitter_vec
        self.bounds.translate(*refix_vec)

    def _translate(self, radius, angle):
        angle *= pi / 180
        xoff = radius * cos(angle)
        yoff = radius * sin(angle)

        self.verbose("Applying translation vector (%.2f,%.2f)" % (xoff, yoff))
        self.bounds.translate(xoff, yoff)

    def _out_of_bounds(self):
        """
        Return true if the centroid of the current bounds is outside the saccade bounds.
        """
        return not self.saccade_bounds.contains(
            *self.bounds.aarect().centroid())

    def _find_saccade_in_bounds(self, radius, theta):
        """
        Find a saccade in the given direction (theta) that lies within self.saccade_bounds.

        Assumes that the given saccade was already performed and
        landed out of bounds.
        """

        # JPHACKALERT: This method iterates to search for a saccade
        # that lies in bounds along the saccade vector. We should
        # really compute this algebraically. Doing so involves computing
        # the intersection of the saccade vector with the saccade
        # bounds.  Ideally, each type of BoundingRegion would know how
        # to compute its own intersection with a given line (should be
        # easy for boxes, circles, and ellipses, at least.)

        # Assume we're starting out of bounds, so start by shifting
        # back to the original position
        self._translate(-radius, theta)

        while not self._out_of_bounds():
            radius *= 0.5
            self._translate(radius, theta)

        radius = -radius
        while self._out_of_bounds():
            radius *= 0.5
            self._translate(radius, theta)
Example #25
0
    def test_position(self):
        """
        Test that a pattern is drawn correctly at different
        locations.
        """

        initial = array([[0,0,0,0],
                         [0,1,1,0],
                         [0,1,1,0],
                         [0,0,0,0]])

        r = Rectangle(bounds=BoundingBox(radius=2),xdensity=1,
                      ydensity=1,aspect_ratio=1,size=2,smoothing=0.0)
        assert_array_equal(r(),initial)

        ### x offset
        x_offset = array([[0,0,0,0],
                          [0,0,1,1],
                          [0,0,1,1],
                          [0,0,0,0]])

        assert_array_equal(r(x=1),x_offset)

        ### y offset
        y_offset = rot90(x_offset)
        assert_array_equal(r(y=1),y_offset)

        ### x and y offset
        target = array([[0,0,0,0,0,0,0,0,0,0],
                        [0,0,0,0,0,0,0,0,0,0],
                        [0,0,0,0,0,0,0,0,0,0],
                        [0,0,0,0,0,0,0,0,0,0],
                        [0,0,0,0,0,0,0,0,0,0],
                        [0,0,0,0,0,0,0,0,0,0],
                        [1,1,0,0,0,0,0,0,0,0],
                        [1,1,0,0,0,0,0,0,0,0],
                        [1,1,0,0,0,0,0,0,0,0],
                        [1,1,0,0,0,0,0,0,0,0]])

        width  = 0.2
        height = 0.4

        r = Rectangle(bounds=BoundingBox(radius=0.5),
                      xdensity=10,ydensity=10,smoothing=0.0,
                      aspect_ratio=width/height,size=height)

        assert_array_equal(r(x=-0.4,y=-0.3),target)

        ### x and y offset with bounds offset by the same
        target = array([[0,0,0,0,0,0,0,0,0,0],
                        [0,0,0,0,0,0,0,0,0,0],
                        [0,0,0,0,0,0,0,0,0,0],
                        [0,0,0,0,1,1,0,0,0,0],
                        [0,0,0,0,1,1,0,0,0,0],
                        [0,0,0,0,1,1,0,0,0,0],
                        [0,0,0,0,1,1,0,0,0,0],
                        [0,0,0,0,0,0,0,0,0,0],
                        [0,0,0,0,0,0,0,0,0,0],
                        [0,0,0,0,0,0,0,0,0,0]])

        width  = 0.2
        height = 0.4

        bounds = BoundingBox(points=((-0.9,-0.8),(0.1,0.2)))
        r = Rectangle(bounds=bounds,xdensity=10,ydensity=10,smoothing=0.0,
                      aspect_ratio=width/height,size=height)
        
        assert_array_equal(r(x=-0.4,y=-0.3),target)
Example #26
0
    def setUp(self):

        ### Simple case: we only pass a dictionary to Plot()
        ### that does not belong to a Sheet:
        views = {}

        time = 0
        metadata = AttrDict(timestamp=time)

        ### SheetView1:
        ### Find a way to assign randomly the matrix.
        self.matrix1 = zeros((10, 10), Float) + RandomArray.random((10, 10))
        self.bounds1 = BoundingBox(points=((-0.5, -0.5), (0.5, 0.5)))
        sv = SheetView(self.matrix1, self.bounds1, metadata=metadata)
        self.sheet_view1 = NdMapping((None, sv),
                                     src_name='TestInputParam',
                                     precedence=0.1,
                                     row_precedence=0.1,
                                     cyclic_range=None,
                                     timestamp=time)
        self.key1 = 'sv1'
        views[self.key1] = self.sheet_view1

        ### SheetView2:
        ### Find a way to assign randomly the matrix.
        self.matrix2 = zeros((10, 10), Float) + 0.3
        self.bounds2 = BoundingBox(points=((-0.5, -0.5), (0.5, 0.5)))
        sv = SheetView(self.matrix2, self.bounds2, metadata=metadata)
        self.sheet_view2 = NdMapping((None, sv),
                                     src_name='TestInputParam',
                                     precedence=0.2,
                                     row_precedence=0.2,
                                     cyclic_range=None,
                                     timestamp=time)
        self.key2 = ('sv2', 0, 10)
        views[self.key2] = self.sheet_view2

        ### SheetView3:
        ### Find a way to assign randomly the matrix.
        self.matrix3 = zeros((10, 10), Float) + RandomArray.random((10, 10))
        self.bounds3 = BoundingBox(points=((-0.5, -0.5), (0.5, 0.5)))
        sv = SheetView(self.matrix3, self.bounds3, metadata=metadata)
        self.sheet_view3 = NdMapping((None, sv),
                                     src_name='TestInputParam',
                                     precedence=0.3,
                                     row_precedence=0.3,
                                     cyclic_range=None,
                                     timestamp=time)
        self.key3 = ('sv3', 0, 'hello', (10, 0))
        views[self.key3] = self.sheet_view3

        ### SheetView4: for testing clipping + different bounding box
        ### Find a way to assign randomly the matrix.
        self.matrix4 = zeros((10, 10), Float) + 1.6
        self.bounds4 = BoundingBox(points=((-0.7, -0.7), (0.7, 0.7)))
        sv = SheetView(self.matrix4, self.bounds4, metadata=metadata)
        self.sheet_view4 = NdMapping((None, sv),
                                     src_name='TestInputParam',
                                     precedence=0.4,
                                     row_precedence=0.4,
                                     cyclic_range=None,
                                     timestamp=time)
        self.key4 = 'sv4'
        views[self.key4] = self.sheet_view4

        self.view_dict = {'Strength': views, 'Hue': views, 'Confidence': views}

        ### JCALERT! for the moment we can only pass a triple when creating plot
        ### adding more sheetView to test when plot will be fixed for accepting
        ### as much as you want.

        # plot0: empty plot + no sheetviewdict passed: error or empty plot?
        ### JCALERT! It has to be fixed what to do in this case in plot..
        ### disabled test for the moment.
        #self.plot0 = Plot((None,None,None),None,name='plot0')
        ### CATCH EXCEPTION

        plot_channels1 = {'Strength': None, 'Hue': None, 'Confidence': None}
        # plot1: empty plot
        self.plot1 = make_template_plot(plot_channels1,
                                        self.view_dict,
                                        density=10.0,
                                        name='plot1')

        plot_channels2 = {
            'Strength': self.key1,
            'Hue': None,
            'Confidence': None
        }
        # plot2: sheetView 1, no normalize, no clipping
        self.plot2 = make_template_plot(plot_channels2,
                                        self.view_dict,
                                        density=10.0,
                                        name='plot2')

        plot_channels3 = {
            'Strength': self.key1,
            'Hue': self.key2,
            'Confidence': None
        }
        # plot3: sheetView 1+2, no normalize, no clipping
        self.plot3 = make_template_plot(plot_channels3,
                                        self.view_dict,
                                        density=10.0,
                                        name='plot3')

        plot_channels4 = {
            'Strength': self.key1,
            'Hue': self.key2,
            'Confidence': self.key3
        }
        # plot4: sheetView 1+2+3, no normalize , no clipping
        self.plot4 = make_template_plot(plot_channels4,
                                        self.view_dict,
                                        density=10.0,
                                        name='plot4')

        plot_channels5 = {
            'Strength': self.key1,
            'Hue': None,
            'Confidence': self.key3
        }
        # plot5: sheetView 1+3, no normalize, no clipping
        self.plot5 = make_template_plot(plot_channels5,
                                        self.view_dict,
                                        density=10.0,
                                        name='plot5')

        plot_channels6 = {
            'Strength': None,
            'Hue': self.key2,
            'Confidence': self.key3
        }
        # plot6: sheetView 2+3, no normalize , no clipping
        self.plot6 = make_template_plot(plot_channels6,
                                        self.view_dict,
                                        density=10.0,
                                        name='plot6')

        plot_channels7 = {
            'Strength': self.key4,
            'Hue': self.key2,
            'Confidence': self.key3
        }
        # plot7: sheetView 1+2+3, no normalize , clipping
        self.plot7 = make_template_plot(plot_channels7,
                                        self.view_dict,
                                        density=10.0,
                                        name='plot7')

        plot_channels8 = {
            'Strength': self.key1,
            'Hue': self.key2,
            'Confidence': self.key3
        }
        # plot8: sheetView 1+2+3, normalize , no clipping
        self.plot8 = make_template_plot(plot_channels8,
                                        self.view_dict,
                                        density=10.0,
                                        normalize=True,
                                        name='plot8')

        ### JCALERT! FOR THE MOMENT I TAKE THE DEFAULT FOR NORMALIZE.
        ### WE WILL SEE IF IT REMAINS IN PLOT FIRST.

        ### also makes a sheet to test realease_sheetviews

        self.sheet = Sheet()
        self.sheet.views.maps[self.key1] = self.sheet_view1
        self.sheet.views.maps[self.key2] = self.sheet_view2
        self.sheet.views.maps[self.key3] = self.sheet_view3
        self.sheet.views.maps[self.key4] = self.sheet_view4

        plot_channels9 = {
            'Strength': self.key1,
            'Hue': self.key2,
            'Confidence': self.key3
        }
        self.plot9 = make_template_plot(plot_channels9,
                                        self.sheet.views.maps,
                                        density=10.0,
                                        name='plot9')
Example #27
0
    def test_slice2bounds(self):

        # test that if you ask to slice the matrix with the sheet's BoundingBox, you
        # get back the whole matrix
        # (I chose to use a 7 density, I don't know why I like 7 so much, it is kind of mystical)

        sheet_bb = BoundingBox(points=((-0.5, -0.5), (0.5, 0.5)))
        ct = SheetCoordinateSystem(sheet_bb, 7)
        slice_ = (0, 7, 0, 7)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        true_bounds_lbrt = (-0.5, -0.5, 0.5, 0.5)
        for a, b in zip(bounds.lbrt(), true_bounds_lbrt):
            self.assertAlmostEqual(a, b)

        # for the following tests, the values have been all computed
        # by hand and then tested (by JC). The boundingbox and density
        # tested have been chosen randomly, then drawn to get the slice
        # from it.

        # Test for 10 density
        ct = SheetCoordinateSystem(sheet_bb, 10)
        slice_ = (0, 9, 1, 5)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        true_bounds_lbrt = (-0.4, -0.4, 0, 0.5)
        for a, b in zip(bounds.lbrt(), true_bounds_lbrt):
            self.assertAlmostEqual(a, b)

        slice_ = (2, 3, 7, 10)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        true_bounds_lbrt = (0.2, 0.2, 0.5, 0.3)
        for a, b in zip(bounds.lbrt(), true_bounds_lbrt):
            self.assertAlmostEqual(a, b)

        # Test for 7 density
        ct = SheetCoordinateSystem(sheet_bb, 7)
        slice_ = (3, 7, 2, 5)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        true_bounds_lbrt = (-0.5 + 2.0 / 7.0, -0.5, -0.5 + 5.0 / 7.0,
                            0.5 - 3.0 / 7.0)
        for a, b in zip(bounds.lbrt(), true_bounds_lbrt):
            self.assertAlmostEqual(a, b)

        slice_ = (2, 6, 0, 1)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        true_bounds_lbrt = (-0.5, 0.5 - 6.0 / 7.0, -0.5 + 1.0 / 7.0,
                            0.5 - 2.0 / 7.0)
        for a, b in zip(bounds.lbrt(), true_bounds_lbrt):
            self.assertAlmostEqual(a, b)

        # Test for 25 density
        ct = SheetCoordinateSystem(sheet_bb, 25)
        slice_ = (0, 25, 4, 10)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        true_bounds_lbrt = (-0.5 + 4.0 / 25.0, -0.5, -0.5 + 10.0 / 25.0, 0.5)
        for a, b in zip(bounds.lbrt(), true_bounds_lbrt):
            self.assertAlmostEqual(a, b)

        slice_ = (7, 18, 3, 11)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        true_bounds_lbrt = (-0.5 + 3.0 / 25.0, 0.5 - 18.0 / 25.0,
                            -0.5 + 11.0 / 25.0, 0.5 - 7.0 / 25.0)
        for a, b in zip(bounds.lbrt(), true_bounds_lbrt):
            self.assertAlmostEqual(a, b)
Example #28
0
    def test_slice2bounds_bounds2slice(self):

        bb = BoundingBox(points=((-0.5, -0.5), (0.5, 0.5)))
        ct = SheetCoordinateSystem(bb, 10)

        slice_ = (0, 3, 7, 8)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        test_slice = Slice(bounds, ct)

        for a, b in zip(slice_, test_slice):
            self.assertEqual(a, b)

        slice_ = (4, 7, 8, 10)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        test_slice = Slice(bounds, ct)

        for a, b in zip(slice_, test_slice):
            self.assertEqual(a, b)

        slice_ = (2, 3, 4, 8)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        test_slice = Slice(bounds, ct)

        for a, b in zip(slice_, test_slice):
            self.assertEqual(a, b)

        slice_ = (0, 3, 9, 10)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        test_slice = Slice(bounds, ct)

        for a, b in zip(slice_, test_slice):
            self.assertEqual(a, b)

        bb = BoundingBox(points=((-0.75, -0.5), (0.75, 0.5)))
        ct = SheetCoordinateSystem(bb, 20, 20)

        slice_ = (9, 14, 27, 29)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        test_slice = Slice(bounds, ct)

        for a, b in zip(slice_, test_slice):
            self.assertEqual(a, b)

        slice_ = (0, 6, 0, 7)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        test_slice = Slice(bounds, ct)

        for a, b in zip(slice_, test_slice):
            self.assertEqual(a, b)

        slice_ = (6, 10, 11, 29)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        test_slice = Slice(bounds, ct)

        for a, b in zip(slice_, test_slice):
            self.assertEqual(a, b)

        bb = BoundingBox(points=((-0.5, -0.5), (0.5, 0.5)))
        ct = SheetCoordinateSystem(bb, 7)

        slice_ = (4, 7, 2, 3)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        test_slice = Slice(bounds, ct)

        for a, b in zip(slice_, test_slice):
            self.assertEqual(a, b)

        slice_ = (0, 7, 0, 7)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_, ct))
        test_slice = Slice(bounds, ct)

        for a, b in zip(slice_, test_slice):
            self.assertEqual(a, b)
Example #29
0
    def __call__(self, iterator, input_activity, output_activity, learning_rate, **params):
        cfs = iterator.proj.cfs.tolist() # CEBALERT: convert to use flatcfs
        rows,cols = output_activity.shape

        # This learning function does not need to scale the learning
        # rate like some do, so it does not use constant_sum_connection_rate()
        single_connection_learning_rate = learning_rate
        
        ### JABALERT: The learning_radius is normally set by
        ### the learn() function of CFSOM, so it doesn't matter
        ### much that the value accepted here is in matrix and 
        ### not sheet coordinates.  It's confusing that anything
        ### would accept matrix coordinates, but the learning_fn
        ### doesn't have access to the sheet, so it can't easily
        ### convert from sheet coords.
        radius = self.learning_radius
        crop_radius = max(1.25,radius*self.crop_radius_multiplier)
        
        # find out the matrix coordinates of the winner
        #
        # NOTE: when there are multiple projections, it would be
        # slightly more efficient to calculate the winner coordinates
        # within the Sheet, e.g. by moving winner_coords() to CFSOM
        # and passing in the results here.  However, finding the
        # coordinates does not take much time, and requiring the
        # winner to be passed in would make it harder to mix and match
        # Projections and learning rules with different Sheets.
        wr,wc = array_argmax(output_activity)
        
        # Optimization: Calculate the bounding box around the winner
        # in which weights will be changed, to avoid considering those
        # units below.
        cmin = int(max(wc-crop_radius,0))
        cmax = int(min(wc+crop_radius+1,cols)) # at least 1 between cmin and cmax
        rmin = int(max(wr-crop_radius,0))
        rmax = int(min(wr+crop_radius+1,rows))

        # generate the neighborhood kernel matrix so that the values
        # can be read off easily using matrix coordinates.
        nk_generator = self.neighborhood_kernel_generator
        radius_int = int(ceil(crop_radius))
        rbound = radius_int + 0.5
        bb = BoundingBox(points=((-rbound,-rbound), (rbound,rbound)))

        # Print parameters designed to match fm2d's output
        #print "%d rad= %d std= %f alpha= %f" % (topo.sim._time, radius_int, radius, single_connection_learning_rate)

        neighborhood_matrix = nk_generator(bounds=bb,xdensity=1,ydensity=1,
                                           size=2*radius)

        for r in range(rmin,rmax):
            for c in range(cmin,cmax):
                cwc = c - wc 
                rwr = r - wr 
                lattice_dist = L2norm((cwc,rwr))
                if lattice_dist <= crop_radius:
                    cf = cfs[r][c]
                    rate = single_connection_learning_rate * neighborhood_matrix[rwr+radius_int,cwc+radius_int]
                    X = cf.get_input_matrix(input_activity)
                    cf.weights += rate * (X - cf.weights)

                    # CEBHACKALERT: see ConnectionField.__init__()
                    cf.weights *= cf.mask
Example #30
0
class TestCoordinateTransforms(unittest.TestCase):
    """
    Tests for sheet.

    Subclassed for use; the subclasses have a setUp method to create
    the particular coordinates to use each time.
    """
    def makeBox(self):
        self.box = BoundingBox(points=((self.left, self.bottom), (self.right,
                                                                  self.top)))

        self.ct = SheetCoordinateSystem(self.box, self.density, self.density)

        # float bounds for matrix coordinates: these
        # values are actually outside the matrix
        self.rbound = self.density * (self.top - self.bottom)
        self.cbound = self.density * (self.right - self.left)

        #self.cbound = int(self.density*(self.right-self.left)) / float((self.right-self.left))
        #self.rbound = int(self.density*(self.top-self.bottom)) / float((self.top-self.bottom))

        # CEBALERT: this is supposed to be a small distance
        D = 0.00001

        # Sheet values around the edge of the BoundingBox
        self.just_in_right_x = self.right - D
        self.just_in_bottom_y = self.bottom + D
        self.just_out_top_y = self.top + D
        self.just_out_left_x = self.left - D

        # Matrix values around the edge of the matrix
        self.just_out_right_idx = self.rbound + D
        self.just_out_bottom_idx = self.cbound + D
        self.just_out_top_idx = 0.0 - D
        self.just_out_left_idx = 0.0 - D

    ### sheet2matrix() tests
    #
    def test_sheet2matrix_center(self):
        """
        Check that the center of the Sheet corresponds to the center
        of the matrix.
        """
        x_center = self.left + (self.right - self.left) / 2.0
        y_center = self.bottom + (self.top - self.bottom) / 2.0
        row, col = self.ct.sheet2matrix(x_center, y_center)
        self.assertEqual((row, col), (self.rbound / 2.0, self.cbound / 2.0))

    def test_sheet2matrix_left_top(self):
        """
        Check that the top-left of the Sheet is [0,0] in matrix
        coordinates.
        """
        row, col = self.ct.sheet2matrix(self.left, self.top)
        self.assertEqual((row, col), (0, 0))

    def test_sheet2matrix_right_bottom(self):
        """
        Check that the bottom-right of the Sheet is [rbound,cbound] in matrix
        coordinates.
        """
        row, col = self.ct.sheet2matrix(self.right, self.bottom)
        self.assertEqual((row, col), (self.rbound, self.cbound))

    def test_sheet2matrix_matrix2sheet(self):
        """
        Check that matrix2sheet() is the inverse of sheet2matrix().
        """
        # top-right corner
        row, col = self.ct.sheet2matrix(self.right, self.top)
        x_right, y_top = self.ct.matrix2sheet(row, col)
        self.assertEqual((x_right, y_top), (self.right, self.top))

        # bottom-left corner
        row, col = self.ct.sheet2matrix(self.left, self.bottom)
        x_left, y_bottom = self.ct.matrix2sheet(row, col)
        self.assertEqual((x_left, y_bottom), (self.left, self.bottom))

    def test_matrix2sheet_sheet2matrix(self):
        """
        Check that sheet2matrix() is the inverse of matrix2sheet().
        """
        # top-right corner
        x, y = self.ct.matrix2sheet(float(0), float(self.last_col))
        top_row, right_col = self.ct.sheet2matrix(x, y)
        self.assertEqual((top_row, right_col),
                         (float(0), float(self.last_col)))

        # bottom-left corner
        x, y = self.ct.matrix2sheet(float(self.last_row), float(0))
        bottom_row, left_col = self.ct.sheet2matrix(x, y)
        self.assertEqual((bottom_row, left_col),
                         (float(self.last_row), float(0)))

    ### sheet2matrixidx() tests
    #
    def test_sheet2matrixidx_left_top(self):
        """
        Test a point just inside the top-left corner of the BoundingBox, and
        one just outside.
        """
        # inside
        r, c = 0, 0
        x, y = self.left, self.top
        self.assertEqual(self.ct.sheet2matrixidx(x, y), (r, c))

        # outside
        r, c = -1, -1
        x, y = self.just_out_left_x, self.just_out_top_y
        self.assertEqual(self.ct.sheet2matrixidx(x, y), (r, c))

    def test_sheet2matrixidx_left_bottom(self):
        """
        Test a point just inside the left-bottom corner of the BoundingBox, and
        one just outside.
        """
        # inside
        r, c = self.last_row, 0
        x, y = self.left, self.just_in_bottom_y
        self.assertEqual(self.ct.sheet2matrixidx(x, y), (r, c))

        # outside
        r, c = self.last_row + 1, -1
        x, y = self.just_out_left_x, self.bottom
        self.assertEqual(self.ct.sheet2matrixidx(x, y), (r, c))

    def test_sheet2matrixidx_right_top(self):
        """
        Test a point just inside the top-right corner of the BoundingBox, and
        one just outside.
        """
        # inside
        r, c = 0, self.last_col
        x, y = self.just_in_right_x, self.top
        self.assertEqual(self.ct.sheet2matrixidx(x, y), (r, c))

        # outside
        r, c = -1, self.last_col + 1
        x, y = self.right, self.just_out_top_y
        self.assertEqual(self.ct.sheet2matrixidx(x, y), (r, c))

    def test_sheet2matrixidx_right_bottom(self):
        """
        Test a point just inside the bottom-right corner of the BoundingBox,
        and the corner itself - which should not be inside.
        """
        # inside
        r, c = self.last_row, self.last_col
        x, y = self.just_in_right_x, self.just_in_bottom_y
        self.assertEqual(self.ct.sheet2matrixidx(x, y), (r, c))

        # not inside
        r, c = self.last_row + 1, self.last_col + 1
        x, y = self.right, self.bottom
        self.assertEqual(self.ct.sheet2matrixidx(x, y), (r, c))

    ### matrix2sheet() tests
    #
    def test_matrix2sheet_left_top(self):
        """
        Check that Sheet's (0,0) is the top-left of the matrix.

        Check that just outside the top-left in matrix coordinates
        comes back to Sheet coordinates that are outside the
        BoundingBox.
        """
        x, y = self.ct.matrix2sheet(0, 0)
        self.assertEqual((x, y), (self.left, self.top))

        x, y = self.ct.matrix2sheet(self.just_out_left_idx,
                                    self.just_out_top_idx)
        self.assertFalse(self.box.contains(x, y))

    def test_matrix2sheet_right_bottom(self):
        """
        Check that Sheet's (right,bottom) is the bottom-right in
        matrix coordinates i.e. [rbound,cbound]

        Check that just outside the bottom-right in matrix coordinates
        comes back to Sheet coordinates that are outside the
        BoundingBox.
        """
        x, y = self.ct.matrix2sheet(self.rbound, self.cbound)
        self.assertEqual((x, y), (self.right, self.bottom))

        x, y = self.ct.matrix2sheet(self.just_out_right_idx,
                                    self.just_out_bottom_idx)
        self.assertFalse(self.box.contains(x, y))

    def test_matrix2sheet_center(self):
        """
        Check that the center in Sheet coordinates corresponds to
        the center in continuous matrix coordinates.
        """
        x_center = self.left + (self.right - self.left) / 2.0
        y_center = self.bottom + (self.top - self.bottom) / 2.0
        center_float_row = self.rbound / 2.0
        center_float_col = self.cbound / 2.0
        x, y = self.ct.matrix2sheet(center_float_row, center_float_col)
        self.assertEqual((x, y), (x_center, y_center))

    ### matrixidx2sheet() tests
    #
    def test_matrixidx2sheet_left_top(self):
        """
        The top-left matrix cell [0,0] should be given back in Sheet
        coordinates at the center of that cell.

        The cell [-1,-1] outside this corner should come back out of
        the BoundingBox
        """
        # inside
        r, c = 0, 0
        x, y = self.left + self.half_unit, self.top - self.half_unit

        test_x, test_y = self.ct.matrixidx2sheet(r, c)
        self.assertEqual((test_x, test_y), (x, y))
        self.assertTrue(self.box.contains(test_x, test_y))

        # outside
        r, c = -1, -1
        test_x, test_y = self.ct.matrixidx2sheet(r, c)
        self.assertFalse(self.box.contains(test_x, test_y))

    def test_matrixidx2sheet_left_bottom(self):
        """
        The bottom-left matrix cell [0,rbound] should be given back
        in Sheet coordinates at the center of that cell.

        The cell [last_row+1,-1] outside this corner should come back out of
        the BoundingBox.
        """
        # inside
        r, c = self.last_row, 0
        x, y = self.left + self.half_unit, self.bottom + self.half_unit
        self.assertEqual(self.ct.matrixidx2sheet(r, c), (x, y))

        # outside
        r, c = self.last_row + 1, -1
        test_x, test_y = self.ct.matrixidx2sheet(r, c)
        self.assertFalse(self.box.contains(test_x, test_y))

    def test_matrixidx2sheet_right_top(self):
        """
        The top-right matrix cell [cbound,0] should be given back
        in Sheet coordinates at the center of that cell.

        The cell [-1,last_col+1] outside this corner should come back out of
        the BoundingBox.
        """
        # inside
        r, c = 0, self.last_col
        x, y = self.right - self.half_unit, self.top - self.half_unit
        self.assertEqual(self.ct.matrixidx2sheet(r, c), (x, y))

        # outside
        r, c = -1, self.last_col + 1
        test_x, test_y = self.ct.matrixidx2sheet(r, c)
        self.assertFalse(self.box.contains(test_x, test_y))

    def test_matrixidx2sheet_right_bottom(self):
        """
        The bottom-right matrix cell [cbound,rbound] should be given back
        in Sheet coordinates at the center of that cell.

        The cell [last_row+1,last_col+1] outside this corner should come back out of
        the BoundingBox.
        """
        r, c = self.last_row, self.last_col
        x, y = self.right - self.half_unit, self.bottom + self.half_unit
        self.assertEqual(self.ct.matrixidx2sheet(r, c), (x, y))

        # outside
        r, c = self.last_row + 1, self.last_col + 1
        test_x, test_y = self.ct.matrixidx2sheet(r, c)
        self.assertFalse(self.box.contains(test_x, test_y))

    def test_matrixidx2sheet_center(self):
        """
        The row and col *index* of the center unit in the matrix should come
        back as the Sheet coordinates of the center of that center unit.
        """
        r, c = self.center_unit_idx
        x_center = self.left + (self.right - self.left) / 2.0
        y_center = self.bottom + (self.top - self.bottom) / 2.0
        x, y = x_center + self.half_unit, y_center - self.half_unit
        self.assertEqual(self.ct.matrixidx2sheet(r, c), (x, y))

    def test_matrixidx2sheet_sheet2matrixidx(self):
        """
        Check that sheet2matrixidx() is the inverse of matrix2sheetidx().
        """
        # top-right corner
        x, y = self.ct.matrixidx2sheet(float(0), float(self.last_col))
        top_row, right_col = self.ct.sheet2matrixidx(x, y)
        self.assertEqual((top_row, right_col),
                         (float(0), float(self.last_col)))

        # bottom-left corner
        x, y = self.ct.matrixidx2sheet(float(self.last_row), float(0))
        bottom_row, left_col = self.ct.sheet2matrixidx(x, y)
        self.assertEqual((bottom_row, left_col),
                         (float(self.last_row), float(0)))
Example #31
0
    def test_slice2bounds(self):

        # test that if you ask to slice the matrix with the sheet's BoundingBox, you
        # get back the whole matrix 
        # (I chose to use a 7 density, I don't know why I like 7 so much, it is kind of mystical)
        
        sheet_bb = BoundingBox(points=((-0.5,-0.5),(0.5,0.5)))
        ct = SheetCoordinateSystem(sheet_bb,7)
        slice_ = (0,7,0,7)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_,ct))
        true_bounds_lbrt = (-0.5,-0.5,0.5,0.5)
        for a,b in zip(bounds.lbrt(),true_bounds_lbrt):
            self.assertAlmostEqual(a,b)

        # for the following tests, the values have been all computed
        # by hand and then tested (by JC). The boundingbox and density
        # tested have been chosen randomly, then drawn to get the slice
        # from it.
        
        # Test for 10 density
        ct = SheetCoordinateSystem(sheet_bb,10)
        slice_ = (0,9,1,5)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_,ct))
        true_bounds_lbrt = (-0.4,-0.4,0,0.5)
        for a,b in zip(bounds.lbrt(),true_bounds_lbrt):
            self.assertAlmostEqual(a,b)

        slice_ = (2,3,7,10)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_,ct))
        true_bounds_lbrt = (0.2,0.2,0.5,0.3)
        for a,b in zip(bounds.lbrt(),true_bounds_lbrt):
            self.assertAlmostEqual(a,b)
        
        # Test for 7 density
        ct = SheetCoordinateSystem(sheet_bb,7)
        slice_ = (3,7,2,5)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_,ct))
        true_bounds_lbrt = (-0.5+2.0/7.0,-0.5,-0.5+5.0/7.0,0.5-3.0/7.0)
        for a,b in zip(bounds.lbrt(),true_bounds_lbrt):
            self.assertAlmostEqual(a,b)

        slice_ = (2,6,0,1)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_,ct))
        true_bounds_lbrt = (-0.5,0.5-6.0/7.0,-0.5+1.0/7.0,0.5-2.0/7.0)
        for a,b in zip(bounds.lbrt(),true_bounds_lbrt):
            self.assertAlmostEqual(a,b)

        # Test for 25 density
        ct = SheetCoordinateSystem(sheet_bb,25)
        slice_ = (0,25,4,10)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_,ct))
        true_bounds_lbrt = (-0.5+4.0/25.0,-0.5,-0.5+10.0/25.0,0.5)
        for a,b in zip(bounds.lbrt(),true_bounds_lbrt):
            self.assertAlmostEqual(a,b)
        

        slice_ = (7,18,3,11)
        bounds = BoundingBox(points=Slice._slicespec2boundsspec(slice_,ct))
        true_bounds_lbrt = (-0.5+3.0/25.0,0.5-18.0/25.0,-0.5+11.0/25.0,0.5-7.0/25.0)
        for a,b in zip(bounds.lbrt(),true_bounds_lbrt):
            self.assertAlmostEqual(a,b)
Example #32
0
    def test_fit_longest(self):
        """
        Check that the longer image dimension is made to fit the default
        dimension of 1.0, while the other is scaled the same.
        """
        ### Twice the default BoundingBox dimensions, image size of 2.0.
        ### In this case, 8 units represent 1.0 in sheet coordinates.
        image_array = array([[
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
        ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 0.,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 0.,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                             ],
                             [
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                             ],
                             [
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ]], Float)

        image = FileImage(filename=resolve_path('tests/testimage.pgm'),
                          xdensity=8,
                          ydensity=8,
                          size=2.0,
                          output_fns=[],
                          bounds=BoundingBox(radius=1.0))

        ps = image.pattern_sampler
        ps.size_normalization = 'fit_longest'
        ps.whole_pattern_output_fns = []

        assert_array_almost_equal(image_array, image())
Example #33
0
class TestCoordinateTransforms(unittest.TestCase):
    """
    Tests for sheet.

    Subclassed for use; the subclasses have a setUp method to create
    the particular coordinates to use each time.
    """    
    def makeBox(self):
        self.box = BoundingBox(points=((self.left,self.bottom),
                                       (self.right,self.top)))

        self.ct = SheetCoordinateSystem(self.box,self.density,self.density)

        # float bounds for matrix coordinates: these
        # values are actually outside the matrix
        self.rbound = self.density*(self.top-self.bottom)
        self.cbound = self.density*(self.right-self.left)

        #self.cbound = int(self.density*(self.right-self.left)) / float((self.right-self.left))
        #self.rbound = int(self.density*(self.top-self.bottom)) / float((self.top-self.bottom))


        # CEBALERT: this is supposed to be a small distance
        D = 0.00001

        # Sheet values around the edge of the BoundingBox
        self.just_in_right_x = self.right - D
        self.just_in_bottom_y = self.bottom + D
        self.just_out_top_y = self.top + D
        self.just_out_left_x = self.left - D

        # Matrix values around the edge of the matrix
        self.just_out_right_idx = self.rbound + D
        self.just_out_bottom_idx = self.cbound + D
        self.just_out_top_idx = 0.0 - D
        self.just_out_left_idx = 0.0 - D


        
    ### sheet2matrix() tests
    #
    def test_sheet2matrix_center(self):
        """
        Check that the center of the Sheet corresponds to the center
        of the matrix.
        """
        x_center = self.left+(self.right-self.left)/2.0
        y_center = self.bottom+(self.top-self.bottom)/2.0
        row, col = self.ct.sheet2matrix(x_center,y_center)
        self.assertEqual((row,col),(self.rbound/2.0,self.cbound/2.0))


    def test_sheet2matrix_left_top(self):
        """
        Check that the top-left of the Sheet is [0,0] in matrix
        coordinates.
        """
        row, col = self.ct.sheet2matrix(self.left,self.top)
        self.assertEqual((row,col),(0,0))


    def test_sheet2matrix_right_bottom(self):
        """
        Check that the bottom-right of the Sheet is [rbound,cbound] in matrix
        coordinates.
        """
        row, col = self.ct.sheet2matrix(self.right,self.bottom)
        self.assertEqual((row,col),(self.rbound,self.cbound))

        
    def test_sheet2matrix_matrix2sheet(self):
        """
        Check that matrix2sheet() is the inverse of sheet2matrix().
        """
        # top-right corner
        row, col = self.ct.sheet2matrix(self.right,self.top)
        x_right, y_top = self.ct.matrix2sheet(row,col)
        self.assertEqual((x_right,y_top),(self.right,self.top)) 

        # bottom-left corner
        row, col = self.ct.sheet2matrix(self.left,self.bottom)
        x_left, y_bottom = self.ct.matrix2sheet(row,col)
        self.assertEqual((x_left,y_bottom),(self.left,self.bottom)) 


    def test_matrix2sheet_sheet2matrix(self):
        """
        Check that sheet2matrix() is the inverse of matrix2sheet().
        """
        # top-right corner
        x,y = self.ct.matrix2sheet(float(0),float(self.last_col))
        top_row,right_col = self.ct.sheet2matrix(x,y)
        self.assertEqual((top_row,right_col),(float(0),float(self.last_col))) 

        # bottom-left corner
        x,y = self.ct.matrix2sheet(float(self.last_row),float(0))
        bottom_row,left_col = self.ct.sheet2matrix(x,y)
        self.assertEqual((bottom_row,left_col),(float(self.last_row),float(0)))

        
    ### sheet2matrixidx() tests
    #    
    def test_sheet2matrixidx_left_top(self):
        """
        Test a point just inside the top-left corner of the BoundingBox, and
        one just outside.
        """
        # inside
        r,c = 0,0
        x,y = self.left,self.top
        self.assertEqual(self.ct.sheet2matrixidx(x,y), (r,c))

        # outside
        r,c = -1,-1
        x,y = self.just_out_left_x,self.just_out_top_y
        self.assertEqual(self.ct.sheet2matrixidx(x,y), (r,c))


    def test_sheet2matrixidx_left_bottom(self):
        """
        Test a point just inside the left-bottom corner of the BoundingBox, and
        one just outside.
        """
        # inside
        r,c = self.last_row, 0
        x,y = self.left, self.just_in_bottom_y
        self.assertEqual(self.ct.sheet2matrixidx(x,y),(r,c))

        # outside
        r,c = self.last_row+1, -1
        x,y = self.just_out_left_x, self.bottom
        self.assertEqual(self.ct.sheet2matrixidx(x,y),(r,c))


    def test_sheet2matrixidx_right_top(self):
        """
        Test a point just inside the top-right corner of the BoundingBox, and
        one just outside.
        """
        # inside
        r,c = 0,self.last_col
        x,y = self.just_in_right_x,self.top
        self.assertEqual(self.ct.sheet2matrixidx(x,y),(r,c))

        # outside
        r,c = -1,self.last_col+1
        x,y = self.right,self.just_out_top_y
        self.assertEqual(self.ct.sheet2matrixidx(x,y),(r,c))


    def test_sheet2matrixidx_right_bottom(self):
        """
        Test a point just inside the bottom-right corner of the BoundingBox,
        and the corner itself - which should not be inside.
        """
        # inside 
        r,c = self.last_row,self.last_col
        x,y = self.just_in_right_x,self.just_in_bottom_y
        self.assertEqual(self.ct.sheet2matrixidx(x,y),(r,c))

        # not inside
        r,c = self.last_row+1,self.last_col+1
        x,y = self.right,self.bottom
        self.assertEqual(self.ct.sheet2matrixidx(x,y),(r,c))


    ### matrix2sheet() tests
    #
    def test_matrix2sheet_left_top(self):
        """
        Check that Sheet's (0,0) is the top-left of the matrix.

        Check that just outside the top-left in matrix coordinates
        comes back to Sheet coordinates that are outside the
        BoundingBox.
        """
        x,y = self.ct.matrix2sheet(0,0)
        self.assertEqual((x,y), (self.left,self.top))

        x,y = self.ct.matrix2sheet(self.just_out_left_idx,self.just_out_top_idx)
        self.assertFalse(self.box.contains(x,y))
    

    def test_matrix2sheet_right_bottom(self):
        """
        Check that Sheet's (right,bottom) is the bottom-right in
        matrix coordinates i.e. [rbound,cbound]

        Check that just outside the bottom-right in matrix coordinates
        comes back to Sheet coordinates that are outside the
        BoundingBox.
        """
        x,y = self.ct.matrix2sheet(self.rbound,self.cbound)
        self.assertEqual((x,y), (self.right,self.bottom))

        x,y = self.ct.matrix2sheet(self.just_out_right_idx,self.just_out_bottom_idx)
        self.assertFalse(self.box.contains(x,y))


    def test_matrix2sheet_center(self):
        """
        Check that the center in Sheet coordinates corresponds to
        the center in continuous matrix coordinates.
        """
        x_center = self.left+(self.right-self.left)/2.0
        y_center = self.bottom+(self.top-self.bottom)/2.0
        center_float_row = self.rbound/2.0
        center_float_col = self.cbound/2.0
        x,y = self.ct.matrix2sheet(center_float_row,center_float_col)
        self.assertEqual((x,y),(x_center,y_center))



    ### matrixidx2sheet() tests
    #
    def test_matrixidx2sheet_left_top(self):
        """
        The top-left matrix cell [0,0] should be given back in Sheet
        coordinates at the center of that cell.

        The cell [-1,-1] outside this corner should come back out of
        the BoundingBox
        """
        # inside
        r,c = 0,0
        x,y = self.left+self.half_unit,self.top-self.half_unit

        test_x, test_y = self.ct.matrixidx2sheet(r,c)
        self.assertEqual((test_x,test_y), (x,y))
        self.assertTrue(self.box.contains(test_x,test_y))

        # outside
        r,c = -1,-1
        test_x, test_y = self.ct.matrixidx2sheet(r,c)
        self.assertFalse(self.box.contains(test_x,test_y))
        
        
    def test_matrixidx2sheet_left_bottom(self):
        """
        The bottom-left matrix cell [0,rbound] should be given back
        in Sheet coordinates at the center of that cell.

        The cell [last_row+1,-1] outside this corner should come back out of
        the BoundingBox.
        """
        # inside
        r,c = self.last_row,0
        x,y = self.left+self.half_unit,self.bottom+self.half_unit
        self.assertEqual(self.ct.matrixidx2sheet(r,c), (x,y))

        # outside
        r,c = self.last_row+1,-1
        test_x, test_y = self.ct.matrixidx2sheet(r,c)
        self.assertFalse(self.box.contains(test_x,test_y))

        
    def test_matrixidx2sheet_right_top(self):
        """
        The top-right matrix cell [cbound,0] should be given back
        in Sheet coordinates at the center of that cell.

        The cell [-1,last_col+1] outside this corner should come back out of
        the BoundingBox.
        """
        # inside
        r,c = 0,self.last_col
        x,y = self.right-self.half_unit,self.top-self.half_unit
        self.assertEqual(self.ct.matrixidx2sheet(r,c), (x,y))

        # outside
        r,c = -1,self.last_col+1
        test_x, test_y = self.ct.matrixidx2sheet(r,c)
        self.assertFalse(self.box.contains(test_x,test_y))

        
    def test_matrixidx2sheet_right_bottom(self):
        """
        The bottom-right matrix cell [cbound,rbound] should be given back
        in Sheet coordinates at the center of that cell.

        The cell [last_row+1,last_col+1] outside this corner should come back out of
        the BoundingBox.
        """
        r,c = self.last_row,self.last_col
        x,y = self.right-self.half_unit,self.bottom+self.half_unit
        self.assertEqual(self.ct.matrixidx2sheet(r,c), (x,y))

        # outside
        r,c = self.last_row+1,self.last_col+1
        test_x, test_y = self.ct.matrixidx2sheet(r,c)
        self.assertFalse(self.box.contains(test_x,test_y))


    def test_matrixidx2sheet_center(self):
        """
        The row and col *index* of the center unit in the matrix should come
        back as the Sheet coordinates of the center of that center unit.
        """
        r,c = self.center_unit_idx
        x_center = self.left+(self.right-self.left)/2.0
        y_center = self.bottom+(self.top-self.bottom)/2.0
        x,y = x_center+self.half_unit, y_center-self.half_unit
        self.assertEqual(self.ct.matrixidx2sheet(r,c), (x,y))    

    def test_matrixidx2sheet_sheet2matrixidx(self):
        """
        Check that sheet2matrixidx() is the inverse of matrix2sheetidx().
        """
        # top-right corner
        x,y = self.ct.matrixidx2sheet(float(0),float(self.last_col))
        top_row,right_col = self.ct.sheet2matrixidx(x,y)
        self.assertEqual((top_row,right_col),(float(0),float(self.last_col))) 

        # bottom-left corner
        x,y = self.ct.matrixidx2sheet(float(self.last_row),float(0))
        bottom_row,left_col = self.ct.sheet2matrixidx(x,y)
        self.assertEqual((bottom_row,left_col),(float(self.last_row),float(0)))