def test_dimension_values_datetime_xcoords(self):
     start = np.datetime64(dt.datetime.today())
     end = start+np.timedelta64(1, 's')
     xs = date_range(start, end, 10)
     image = Image((xs, self.ys, self.array))
     self.assertEqual(image.dimension_values(0, expanded=False),
                      date_range(start, end, 10))
def update_sheet_activity(sheet_name, force=False):
    """
    Update the '_activity_buffer' ViewMap for a given sheet by name.

    If force is False and the existing Activity Image isn't stale,
    the existing view is returned.
    """
    name = 'ActivityBuffer'
    sheet = topo.sim.objects(Sheet)[sheet_name]
    view = sheet.views.Maps.get(name, False)
    time = topo.sim.time()
    metadata = AttrDict(precedence=sheet.precedence,
                        row_precedence=sheet.row_precedence,
                        src_name=sheet.name, shape=sheet.activity.shape,
                        timestamp=time)
    if not view:
        im = Image(np.array(sheet.activity), sheet.bounds)
        im.metadata=metadata
        view = HoloMap((time, im), key_dimensions=[Time])
        view.metadata = metadata
        sheet.views.Maps[name] = view
    else:
        if force or view.range('Time')[1] < time:
            im = Image(np.array(sheet.activity), sheet.bounds)
            im.metadata=metadata
            view[time] = im
    return view
Beispiel #3
0
    def test_custom_magic_to_default_inheritance(self):
        """
        Checks customs inheritance backs off to default tree correctly
        simulating the %%opts cell magic.
        """
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("Custom magic inheritance test requires matplotlib")
        options = self.initialize_option_tree()
        options.Image.A.B = Options('style', alpha=0.2)

        obj = Image(np.random.rand(10, 10), group='A', label='B')

        # Before customizing...
        expected_obj =  {'alpha': 0.2, 'cmap': 'hot', 'interpolation': 'nearest'}
        obj_lookup = Store.lookup_options('matplotlib', obj, 'style')
        self.assertEqual(obj_lookup.kwargs, expected_obj)

        custom_tree = {0: OptionTree(groups=['plot', 'style', 'norm'],
                                     style={'Image' : dict(clims=(0, 0.5))})}
        Store._custom_options['matplotlib'] = custom_tree
        obj.id = 0 # Manually set the id to point to the tree above

        # Customize this particular object
        expected_custom_obj =  dict(clims=(0,0.5), **expected_obj)
        custom_obj_lookup = Store.lookup_options('matplotlib', obj, 'style')
        self.assertEqual(custom_obj_lookup.kwargs, expected_custom_obj)
Beispiel #4
0
 def test_plot_options_one_object(self):
     im = Image(np.random.rand(10,10))
     imopts = opts.Image(interpolation='nearest', cmap='jet')
     styled_im = im.options(imopts)
     self.assertEqual(self.lookup_options(im, 'plot').options, {})
     self.assertEqual(self.lookup_options(styled_im, 'style').options,
                      dict(cmap='jet', interpolation='nearest'))
Beispiel #5
0
    def view_depth_map(self, mode='both'):
        """
        Visualize the depth map using holoviews, including
        distribution histograms.

        Mode may be one of 'discrete', 'raw' or 'both':

        * The 'discrete' mode presents the depth map used by
          TemporalScatter, showing the latency at which
          TemporalScatter will propagate the input i.e. discrete,
          positive latencies in milliseconds.

        * The 'raw' mode shows the continuous distribution before
          discretization. This is typically a zero-mean, zero-centered
          distribution i.e a continuous, zero-centered latency
          distribution.

        * Both presents both of the above types together (default).
        """
        views = []
        if mode in ['raw', 'both']:
            views.append(Image(self.raw_depth_map, group='Pattern',
                               label='Raw Depth map').hist())

        if mode in ['discrete', 'both']:
            scaled_map = (self.depth_map * self.timestep)
            discrete_sv = Image(scaled_map, group='Pattern',
                                label='Depth map')
            views.append(discrete_sv.hist(num_bins=self.depth,
                                          bin_range=(0, self.span)))

        return views[0] if len(views)==1 else views[0]+views[1]
Beispiel #6
0
 def test_regrid_mean_xarray_transposed(self):
     img = Image((range(10), range(5), np.arange(10) * np.arange(5)[np.newaxis].T),
                 datatype=['xarray'])
     img.data = img.data.transpose()
     regridded = regrid(img, width=2, height=2, dynamic=False)
     expected = Image(([2., 7.], [0.75, 3.25], [[1, 5], [6, 22]]))
     self.assertEqual(regridded, expected)
Beispiel #7
0
    def test_opts_method_with_utility(self):
        im = Image(np.random.rand(10,10))
        imopts = opts.Image(cmap='Blues')
        styled_im = im.opts(imopts)

        assert styled_im is im
        self.assertEqual(self.lookup_options(im, 'style').options,
                         {'cmap': 'Blues', 'interpolation': 'nearest'})
Beispiel #8
0
 def test_plot_options_object_list(self):
     im = Image(np.random.rand(10,10))
     imopts1 = opts.Image(interpolation='nearest')
     imopts2 = opts.Image(cmap='summer')
     styled_im = im.options([imopts1,imopts2])
     self.assertEqual(self.lookup_options(im, 'plot').options, {})
     self.assertEqual(self.lookup_options(styled_im, 'style').options,
                      dict(cmap='summer', interpolation='nearest'))
Beispiel #9
0
    def __getitem__(self, coords):
        metadata = AttrDict(precedence=self.precedence,
                            row_precedence=self.row_precedence,
                            timestamp=self.simulation.time())

        image = Image(self.activity.copy(), self.bounds,
                   label=self.name, group='Activity')[coords]
        image.metadata=metadata
        return image
Beispiel #10
0
    def test_simple_clone_disabled(self):
        im = Image(np.random.rand(10,10))
        styled_im = im.opts(interpolation='nearest', cmap='jet', clone=False)

        self.assertEqual(self.lookup_options(im, 'plot').options, {})
        self.assertEqual(self.lookup_options(styled_im, 'plot').options, {})

        assert styled_im is im
        self.assertEqual(self.lookup_options(im, 'style').options,
                         {'cmap': 'jet', 'interpolation': 'nearest'})
Beispiel #11
0
    def _collate_results(self, p):
        results = Layout()

        timestamp = self.metadata.timestamp
        axis_name = p.x_axis.capitalize()
        axis_feature = [f for f in self.features if f.name.lower() == p.x_axis][0]
        if axis_feature.cyclic:
            axis_feature.values.append(axis_feature.range[1])
        curve_label = ''.join([p.measurement_prefix, axis_name, 'Tuning'])
        dimensions = [features.Time, features.Duration] + [f for f in self.outer] + [axis_feature]
        pattern_dimensions = self.outer + self.inner
        pattern_dim_label = '_'.join(f.name.capitalize() for f in pattern_dimensions)

        for label in self.measurement_product:
            # Deconstruct label into source name and feature_values
            name = label[0]
            f_vals = label[1:]

            # Get data and metadata from the DistributionMatrix objects
            dist_matrix = self._featureresponses[name][f_vals][p.x_axis]
            curve_responses = dist_matrix.distribution_matrix

            output_metadata = self.metadata.outputs[name]
            rows, cols = output_metadata['shape']

            # Create top level NdMapping indexing over time, duration, the outer
            # feature dimensions and the x_axis dimension
            if (curve_label, name) not in results:
                vmap = HoloMap(kdims=dimensions,
                               group=curve_label, label=name)
                vmap.metadata = AttrDict(**output_metadata)
                results.set_path((curve_label, name), vmap)

            metadata = AttrDict(timestamp=timestamp, **output_metadata)

            # Populate the ViewMap with measurements for each x value
            for x in curve_responses[0, 0]._data.iterkeys():
                y_axis_values = np.zeros(output_metadata['shape'], activity_dtype)
                for i in range(rows):
                    for j in range(cols):
                        y_axis_values[i, j] = curve_responses[i, j].get_value(x)
                key = (timestamp,)+f_vals+(x,)
                im = Image(y_axis_values, bounds=output_metadata['bounds'],
                           label=name, group=' '.join([curve_label, 'Response']),
                           vdims=['Response'])
                im.metadata = metadata.copy()
                results[(curve_label, name)][key] = im
                if axis_feature.cyclic and x == axis_feature.range[0]:
                    symmetric_key = (timestamp,)+f_vals+(axis_feature.range[1],)
                    results[(curve_label, name)][symmetric_key] = im
            if p.store_responses:
                info = (p.pattern_generator.__class__.__name__, pattern_dim_label, 'Response')
                results.set_path(('%s_%s_%s' % info, name), self._responses[name])

        return results
 def test_sample_coords(self):
     arr = np.arange(10)*np.arange(5)[np.newaxis].T
     xs = np.linspace(0.12, 0.81, 10)
     ys = np.linspace(0.12, 0.391, 5)
     img = Image((xs, ys, arr), kdims=['x', 'y'], vdims=['z'], datatype=[self.datatype])
     sampled = img.sample([(0.15, 0.15), (0.15, 0.4), (0.8, 0.4), (0.8, 0.15)])
     self.assertIsInstance(sampled, Table)
     yidx = [0, 4, 4, 0]
     xidx = [0, 0, 9, 9]
     table = Table((xs[xidx], ys[yidx], arr[yidx, xidx]), kdims=['x', 'y'], vdims=['z'])
     self.assertEqual(sampled, table)
Beispiel #13
0
 def test_sheetview_release(self):
     s = Sheet()
     s.activity = np.array([[1, 2], [3, 4]])
     # Call s.sheet_view(..) with a parameter
     im2 = Image(s.activity, bounds=s.bounds)
     im2.metadata = dict(src_name=s.name)
     self.assertEqual(len(s.views.Maps.keys()), 0)
     s.views.Maps["Activity"] = im2
     self.assertEqual(len(s.views.Maps.keys()), 1)
     s.release_sheet_view("Activity")
     self.assertEqual(len([v for v in s.views.Maps.values() if v is not None]), 0)
Beispiel #14
0
    def test_simple_opts_clone_enabled(self):
        im = Image(np.random.rand(10,10))
        styled_im = im.opts(interpolation='nearest', cmap='jet', clone=True)

        self.assertEqual(self.lookup_options(im, 'plot').options, {})
        self.assertEqual(self.lookup_options(styled_im, 'plot').options, {})

        assert styled_im is not im
        im_lookup = self.lookup_options(im, 'style').options
        self.assertEqual(im_lookup['cmap'] == 'jet', False)
        styled_im_lookup =  self.lookup_options(styled_im, 'style').options
        self.assertEqual(styled_im_lookup['cmap'] == 'jet', True)
Beispiel #15
0
 def test_mpl_bokeh_mpl_via_builders_opts_method(self):
     img = Image(np.random.rand(10,10))
     mpl_opts = opts.Image(cmap='Blues', backend='matplotlib')
     bokeh_opts = opts.Image(cmap='Purple', backend='bokeh')
     self.assertEqual(mpl_opts.kwargs['backend'], 'matplotlib')
     self.assertEqual(bokeh_opts.kwargs['backend'], 'bokeh')
     img.opts(mpl_opts, bokeh_opts)
     mpl_lookup = Store.lookup_options('matplotlib', img, 'style').options
     self.assertEqual(mpl_lookup['cmap'], 'Blues')
     bokeh_lookup = Store.lookup_options('bokeh', img, 'style').options
     self.assertEqual(bokeh_lookup['cmap'], 'Purple')
     self.assert_output_options_group_empty(img)
 def test_canonical_vdim(self):
     x = np.array([ 0.  ,  0.75,  1.5 ])
     y = np.array([ 1.5 ,  0.75,  0.  ])
     z = np.array([[ 0.06925999,  0.05800389,  0.05620127],
                   [ 0.06240918,  0.05800931,  0.04969735],
                   [ 0.05376789,  0.04669417,  0.03880118]])
     dataset = Image((x, y, z), kdims=['x', 'y'], vdims=['z'])
     canonical = np.array([[ 0.05376789,  0.04669417,  0.03880118],
                           [ 0.06240918,  0.05800931,  0.04969735],
                           [ 0.06925999,  0.05800389,  0.05620127]])
     self.assertEqual(dataset.dimension_values('z', flat=False),
                      canonical)
Beispiel #17
0
    def _collate_results(self, p):
        """
        Collate responses into the results dictionary containing a
        ProjectionGrid for each measurement source.
        """
        results = Layout()

        timestamp = self.metadata.timestamp
        dimensions = [features.Time, features.Duration]
        pattern_dimensions = self.outer + self.inner
        pattern_dim_label = '_'.join(f.name.capitalize() for f in pattern_dimensions)

        grids, responses = {}, {}
        for labels in self.measurement_product:
            in_label, out_label, duration = labels
            input_metadata = self.metadata.inputs[in_label]
            output_metadata = self.metadata.outputs[out_label]
            rows, cols, scs = self._compute_roi(p, output_metadata)
            time_key = (timestamp, duration)

            grid_key = (in_label, out_label)
            if grid_key not in grids:
                if p.store_responses:
                    responses[in_label] = self._responses[in_label]
                    responses[out_label] = self._responses[out_label]
                grids[grid_key] = GridSpace(group='RFs', label=out_label)
            view = grids[grid_key]
            rc_response = self._featureresponses[in_label][out_label][duration]
            for i, ii in enumerate(rows):
                for j, jj in enumerate(cols):
                    coord = scs.matrixidx2sheet(ii, jj)
                    im = Image(rc_response[i, j], bounds=input_metadata['bounds'],
                               label=out_label, group='Receptive Field',
                               vdims=['Weight'])
                    im.metadata = AttrDict(timestamp=timestamp)

                    if coord in view:
                        view[coord][time_key] = im
                    else:
                        view[coord] = HoloMap((time_key, im), kdims=dimensions,
                                              label=out_label, group='Receptive Field')
                    view[coord].metadata = AttrDict(**input_metadata)
        for (in_label, out_label), view in grids.items():
            results.set_path(('%s_Reverse_Correlation' % in_label, out_label), view)
            if p.store_responses:
                info = (p.pattern_generator.__class__.__name__,
                        pattern_dim_label, 'Response')
                results.set_path(('%s_%s_%s' % info, in_label),
                                 responses[in_label])
                results.set_path(('%s_%s_%s' % info, out_label),
                                 responses[out_label])
        return results
Beispiel #18
0
 def projection_view(self, timestamp=None):
     """Returns the activity in a single projection"""
     if timestamp is None:
         timestamp = self.src.simulation.time()
     im = Image(self.activity.copy(), self.dest.bounds,
                label=self.name, group='Activity')
     im.metadata=AttrDict(proj_src_name=self.src.name,
                          precedence=self.src.precedence,
                          proj_name=self.name,
                          row_precedence=self.src.row_precedence,
                          src_name=self.dest.name,
                          timestamp=timestamp)
     return im
Beispiel #19
0
 def test_opts_clear(self):
     im = Image(np.random.rand(10,10))
     styled_im = im.opts(style=dict(cmap='jet', interpolation='nearest',
                                    option1='A', option2='B'), clone=False)
     self.assertEqual(self.lookup_options(im, 'style').options,
                      {'cmap': 'jet', 'interpolation': 'nearest',
                       'option1':'A', 'option2':'B'})
     assert styled_im is im
     cleared = im.opts.clear()
     assert cleared is im
     cleared_options = self.lookup_options(cleared, 'style').options
     self.assertEqual(not any(k in ['option1', 'option2']
                              for k in cleared_options.keys()), True)
    def __getitem__(self, coords):
        metadata = AttrDict(precedence=self.precedence,
                            row_precedence=self.row_precedence,
                            timestamp=self.simulation.time())

        if self._channel_data:
            arr = np.dstack(self._channel_data)
        else:
            arr = self.activity.copy()

        im = Image(arr, self.bounds,
                   label=self.name+' Activity', group='Activity')[coords]
        im.metadata=metadata
        return im
Beispiel #21
0
def update_rgb_activities():
    """
    Make available Red, Green, and Blue activity matrices for all appropriate sheets.
    """
    for sheet in topo.sim.objects(Sheet).values():
        metadata = AttrDict(src_name=sheet.name, precedence=sheet.precedence,
                            row_precedence=sheet.row_precedence,
                            timestamp=topo.sim.time())
        for c in ['Red','Green','Blue']:
            # should this ensure all of r,g,b are present?
            if hasattr(sheet,'activity_%s'%c.lower()):
                activity_copy = getattr(sheet,'activity_%s'%c.lower()).copy()
                new_view = Image(activity_copy, bounds=sheet.bounds)
                new_view.metadata=metadata
                sheet.views.Maps['%sActivity'%c]=new_view
Beispiel #22
0
    def test_custom_opts_to_default_inheritance(self):
        """
        Checks customs inheritance backs off to default tree correctly
        using .opts.
        """
        options = self.initialize_option_tree()
        options.Image.A.B = Options('style', alpha=0.2)

        obj = Image(np.random.rand(10, 10), group='A', label='B')
        expected_obj =  {'alpha': 0.2, 'cmap': 'hot', 'interpolation': 'nearest'}
        obj_lookup = Store.lookup_options('matplotlib', obj, 'style')
        self.assertEqual(obj_lookup.kwargs, expected_obj)

        # Customize this particular object
        custom_obj = obj.opts(style=dict(clims=(0, 0.5)))
        expected_custom_obj =  dict(clims=(0,0.5), **expected_obj)
        custom_obj_lookup = Store.lookup_options('matplotlib', custom_obj, 'style')
        self.assertEqual(custom_obj_lookup.kwargs, expected_custom_obj)
Beispiel #23
0
 def test_regrid_max(self):
     img = Image((range(10), range(5), np.arange(10) * np.arange(5)[np.newaxis].T))
     regridded = regrid(img, aggregator='max', width=2, height=2, dynamic=False)
     expected = Image(([2., 7.], [0.75, 3.25], [[8, 18], [16, 36]]))
     self.assertEqual(regridded, expected)
Beispiel #24
0
 def test_image_gradient(self):
     img = Image(np.array([[0, 1, 0], [3, 4, 5.], [6, 7, 8]]))
     op_img = gradient(img)
     self.assertEqual(op_img, img.clone(np.array([[3.162278, 3.162278], [3.162278, 3.162278]]), group='Gradient'))
Beispiel #25
0
 def test_image_transform(self):
     img = Image(np.random.rand(10, 10))
     op_img = transform(img, operator=lambda x: x*2)
     self.assertEqual(op_img, img.clone(img.data*2, group='Transform'))
Beispiel #26
0
 def test_regrid_disabled_expand(self):
     img = Image(([0.5, 1.5], [0.5, 1.5], [[0., 1.], [2., 3.]]))
     regridded = regrid(img, width=2, height=2, x_range=(-2, 4), y_range=(-2, 4), expand=False,
                        dynamic=False)
     self.assertEqual(regridded, img)
Beispiel #27
0
 def test_rasterize_image_string_aggregator(self):
     img = Image((range(10), range(5), np.arange(10) * np.arange(5)[np.newaxis].T))
     regridded = regrid(img, width=2, height=2, dynamic=False, aggregator='mean')
     expected = Image(([2., 7.], [0.75, 3.25], [[1, 5], [6, 22]]))
     self.assertEqual(regridded, expected)
 def init_data(self):
     self.image = Image(np.flipud(self.array), bounds=(-10, 0, 10, 10))
Beispiel #29
0
 def test_image_threshold(self):
     img = Image(np.array([[0, 1, 0], [3, 4, 5.]]))
     op_img = threshold(img)
     self.assertEqual(
         op_img,
         img.clone(np.array([[0, 1, 0], [1, 1, 1]]), group='Threshold'))
Beispiel #30
0
 def test_operation_holomap(self):
     hmap = HoloMap({1: Image(np.random.rand(10, 10))})
     op_hmap = operation(hmap, op=lambda x, k: x.clone(x.data * 2))
     self.assertEqual(
         op_hmap.last, hmap.last.clone(hmap.last.data * 2,
                                       group='Operation'))
Beispiel #31
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 = np.zeros((10, 10), dtype=np.float) + np.random.random(
            (10, 10))
        self.bounds1 = BoundingBox(points=((-0.5, -0.5), (0.5, 0.5)))
        im = Image(self.matrix1, self.bounds1)
        im.metadata = metadata
        self.sheet_view1 = NdMapping((None, im))
        self.sheet_view1.metadata = AttrDict(src_name='TestInputParam',
                                             precedence=0.1,
                                             row_precedence=0.1,
                                             cyclic_range=None,
                                             timestamp=time)
        self.key1 = 'IM1'
        views[self.key1] = self.sheet_view1

        ### SheetView2:
        ### Find a way to assign randomly the matrix.
        self.matrix2 = np.zeros((10, 10), dtype=np.float) + 0.3
        self.bounds2 = BoundingBox(points=((-0.5, -0.5), (0.5, 0.5)))
        im = Image(self.matrix2, self.bounds2)
        im.metadata = metadata
        self.sheet_view2 = NdMapping((None, im))
        self.sheet_view2.metadata = AttrDict(src_name='TestInputParam',
                                             precedence=0.2,
                                             row_precedence=0.2,
                                             cyclic_range=None,
                                             timestamp=time)
        self.key2 = 'IM2'
        views[self.key2] = self.sheet_view2

        ### SheetView3:
        ### Find a way to assign randomly the matrix.
        self.matrix3 = np.zeros((10, 10), dtype=np.float) + np.random.random(
            (10, 10))
        self.bounds3 = BoundingBox(points=((-0.5, -0.5), (0.5, 0.5)))
        im = Image(self.matrix3, self.bounds3)
        im.metadata = metadata
        self.sheet_view3 = NdMapping((None, im))
        self.sheet_view3.metadata = AttrDict(src_name='TestInputParam',
                                             precedence=0.3,
                                             row_precedence=0.3,
                                             cyclic_range=None,
                                             timestamp=time)
        self.key3 = 'IM3'
        views[self.key3] = self.sheet_view3

        ### SheetView4: for testing clipping + different bounding box
        ### Find a way to assign randomly the matrix.
        self.matrix4 = np.zeros((10, 10), dtype=np.float) + 1.6
        self.bounds4 = BoundingBox(points=((-0.7, -0.7), (0.7, 0.7)))
        im = Image(self.matrix4, self.bounds4)
        im.metadata = metadata
        self.sheet_view4 = NdMapping((None, im))
        self.sheet_view4.metadata = AttrDict(src_name='TestInputParam',
                                             precedence=0.4,
                                             row_precedence=0.4,
                                             cyclic_range=None,
                                             timestamp=time)
        self.key4 = 'IM4'
        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')
savefig_III.png
test.mp4       # If the ffmpeg animation writer is enabled
frame.png
"""

import numpy as np
from holoviews import Image, Curve, HoloMap, Store

# Note that outside of Jupyter notebooks, you need to activate the
# appropriate renderer by importing it. Here we import the mpl backend.
from holoviews.plotting import mpl

# First lets create some example HoloViews objects to export

x, y = np.mgrid[-50:51, -50:51] * 0.1
image = Image(np.sin(x**2 + y**2))

coords = [(0.1 * i, np.sin(0.1 * i)) for i in range(100)]
curve = Curve(coords)

curves = {
    phase: Curve([(0.1 * i, np.sin(phase + 0.1 * i)) for i in range(100)])
    for phase in [0, np.pi / 2, np.pi, np.pi * 3 / 2]
}
waves = HoloMap(curves)

# Static layout
layout = image + curve

#==============================#
# Matplotlib renderer instance #
Beispiel #33
0
 def test_bounds_mismatch(self):
     with self.assertRaises(ValueError):
         Image((range(10), range(10), np.random.rand(10, 10)), bounds=0.5)
Beispiel #34
0
 def test_init_data_tuple_error(self):
     xs = np.arange(5)
     ys = np.arange(10)
     array = xs * ys[:, np.newaxis]
     with self.assertRaises(DataError):
         Image((ys, xs, array))
Beispiel #35
0
 def init_data(self):
     self.image = Image(np.flipud(self.array), bounds=(-10, 0, 10, 10))
Beispiel #36
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 = np.zeros((10,10),dtype=np.float) + np.random.random((10,10))
        self.bounds1 = BoundingBox(points=((-0.5,-0.5),(0.5,0.5)))
        im = Image(self.matrix1, self.bounds1)
        im.metadata=metadata
        self.sheet_view1 = NdMapping((None, im))
        self.sheet_view1.metadata = AttrDict(src_name='TestInputParam',
                                            precedence=0.1, row_precedence=0.1,
                                            cyclic_range=None, timestamp=time)
        self.key1 = 'IM1'
        views[self.key1] = self.sheet_view1

        ### SheetView2:
        ### Find a way to assign randomly the matrix.
        self.matrix2 = np.zeros((10,10),dtype=np.float) + 0.3
        self.bounds2 = BoundingBox(points=((-0.5,-0.5),(0.5,0.5)))
        im = Image(self.matrix2, self.bounds2)
        im.metadata=metadata
        self.sheet_view2 = NdMapping((None, im))
        self.sheet_view2.metadata = AttrDict(src_name='TestInputParam',
                                             precedence=0.2, row_precedence=0.2,
                                             cyclic_range=None, timestamp=time)
        self.key2 = 'IM2'
        views[self.key2] = self.sheet_view2

        ### SheetView3:
        ### Find a way to assign randomly the matrix.
        self.matrix3 = np.zeros((10,10),dtype=np.float) + np.random.random((10,10))
        self.bounds3 = BoundingBox(points=((-0.5,-0.5),(0.5,0.5)))
        im = Image(self.matrix3, self.bounds3)
        im.metadata=metadata
        self.sheet_view3 = NdMapping((None, im))
        self.sheet_view3.metadata = AttrDict(src_name='TestInputParam',
                                             precedence=0.3, row_precedence=0.3,
                                             cyclic_range=None, timestamp=time)
        self.key3 = 'IM3'
        views[self.key3] = self.sheet_view3

        ### SheetView4: for testing clipping + different bounding box
        ### Find a way to assign randomly the matrix.
        self.matrix4 = np.zeros((10,10),dtype=np.float) + 1.6
        self.bounds4 = BoundingBox(points=((-0.7,-0.7),(0.7,0.7)))
        im = Image(self.matrix4, self.bounds4)
        im.metadata=metadata
        self.sheet_view4 = NdMapping((None, im))
        self.sheet_view4.metadata = AttrDict(src_name='TestInputParam',
                                             precedence=0.4, row_precedence=0.4,
                                             cyclic_range=None, timestamp=time)
        self.key4 = 'IM4'
        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')
Beispiel #37
0
 def test_rasterize_quadmesh(self):
     qmesh = QuadMesh(([0, 1], [0, 1], np.array([[0, 1], [2, 3]])))
     img = rasterize(qmesh, width=3, height=3, dynamic=False, aggregator=ds.mean('z'))
     image = Image(np.array([[2, 3, 3], [2, 3, 3], [0, 1, 1]]),
                   bounds=(-.5, -.5, 1.5, 1.5))
     self.assertEqual(img, image)
Beispiel #38
0
 def test_operation_element(self):
     img = Image(np.random.rand(10, 10))
     op_img = operation(img, op=lambda x, k: x.clone(x.data * 2))
     self.assertEqual(op_img, img.clone(img.data * 2, group='Operation'))
Beispiel #39
0
 def test_select_value_dimension_rgb(self):
     self.assertEqual(
         self.rgb[..., 'R'],
         Image(np.flipud(self.rgb_array[:, :, 0]),
               bounds=self.rgb.bounds,
               vdims=[Dimension('R', range=(0, 1))]))
Beispiel #40
0
 def test_spikes_aggregate_spike_length(self):
     spikes = Spikes([1, 2, 3])
     agg = rasterize(spikes, width=5, dynamic=False, expand=False, spike_length=7)
     expected = Image(np.array([[1, 0, 1, 0, 1]]), vdims='count',
                      xdensity=2.5, ydensity=1, bounds=(1, 0, 3, 7.0))
     self.assertEqual(agg, expected)
class Image_ImageInterfaceTests(InterfaceTests):
    """
    Tests for ImageInterface
    """

    datatype = 'image'
    element = Image
    data_type = np.ndarray

    def init_grid_data(self):
        self.xs = np.linspace(-9, 9, 10)
        self.ys = np.linspace(0.5, 9.5, 10)
        self.array = np.arange(10) * np.arange(10)[:, np.newaxis]

    def init_data(self):
        self.image = Image(np.flipud(self.array), bounds=(-10, 0, 10, 10))

    def test_init_data_tuple(self):
        xs = np.arange(5)
        ys = np.arange(10)
        array = xs * ys[:, np.newaxis]
        Image((xs, ys, array))

    def test_init_data_tuple_error(self):
        xs = np.arange(5)
        ys = np.arange(10)
        array = xs * ys[:, np.newaxis]
        with self.assertRaises(DataError):
            Image((ys, xs, array))

    def test_bounds_mismatch(self):
        with self.assertRaises(ValueError):
            Image((range(10), range(10), np.random.rand(10, 10)), bounds=0.5)

    def test_init_data_datetime_xaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        xs = date_range(start, end, 10)
        Image((xs, self.ys, self.array))

    def test_init_data_datetime_yaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        ys = date_range(start, end, 10)
        Image((self.xs, ys, self.array))

    def test_init_bounds(self):
        self.assertEqual(self.image.bounds.lbrt(), (-10, 0, 10, 10))

    def test_init_bounds_datetime_xaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        xs = date_range(start, end, 10)
        bounds = (start, 0, end, 10)
        image = Image((xs, self.ys, self.array), bounds=bounds)
        self.assertEqual(image.bounds.lbrt(), bounds)

    def test_init_bounds_datetime_yaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        ys = date_range(start, end, 10)
        bounds = (-10, start, 10, end)
        image = Image((self.xs, ys, self.array))
        self.assertEqual(image.bounds.lbrt(), bounds)

    def test_init_densities(self):
        self.assertEqual(self.image.xdensity, 0.5)
        self.assertEqual(self.image.ydensity, 1)

    def test_init_densities_datetime_xaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        xs = date_range(start, end, 10)
        image = Image((xs, self.ys, self.array))
        self.assertEqual(image.xdensity, 1e-5)
        self.assertEqual(image.ydensity, 1)

    def test_init_densities_datetime_yaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        ys = date_range(start, end, 10)
        image = Image((self.xs, ys, self.array))
        self.assertEqual(image.xdensity, 0.5)
        self.assertEqual(image.ydensity, 1e-5)

    def test_dimension_values_xs(self):
        self.assertEqual(self.image.dimension_values(0, expanded=False),
                         np.linspace(-9, 9, 10))

    def test_dimension_values_ys(self):
        self.assertEqual(self.image.dimension_values(1, expanded=False),
                         np.linspace(0.5, 9.5, 10))

    def test_dimension_values_vdim(self):
        self.assertEqual(self.image.dimension_values(2, flat=False),
                         self.array)

    def test_index_single_coordinate(self):
        self.assertEqual(self.image[0.3, 5.1], 25)

    def test_slice_xaxis(self):
        sliced = self.image[0.3:5.2]
        self.assertEqual(sliced.bounds.lbrt(), (0, 0, 6, 10))
        self.assertEqual(sliced.xdensity, 0.5)
        self.assertEqual(sliced.ydensity, 1)
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[:, 5:8])

    def test_slice_datetime_xaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        bounds = (start, 0, end, 10)
        xs = date_range(start, end, 10)
        image = Image((xs, self.ys, self.array), bounds=bounds)
        sliced = image[start+np.timedelta64(530, 'ms'): start+np.timedelta64(770, 'ms')]
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[:, 5:8])

    def test_slice_yaxis(self):
        sliced = self.image[:, 1.2:5.2]
        self.assertEqual(sliced.bounds.lbrt(), (-10, 1., 10, 5))
        self.assertEqual(sliced.xdensity, 0.5)
        self.assertEqual(sliced.ydensity, 1)
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[1:5, :])

    def test_slice_datetime_yaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        ys = date_range(start, end, 10)
        image = Image((self.xs, ys, self.array))
        sliced = image[:, start+np.timedelta64(120, 'ms'): start+np.timedelta64(520, 'ms')]
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[1:5, :])

    def test_slice_both_axes(self):
        sliced = self.image[0.3:5.2, 1.2:5.2]
        self.assertEqual(sliced.bounds.lbrt(), (0, 1., 6, 5))
        self.assertEqual(sliced.xdensity, 0.5)
        self.assertEqual(sliced.ydensity, 1)
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[1:5, 5:8])

    def test_slice_x_index_y(self):
        sliced = self.image[0.3:5.2, 5.2]
        self.assertEqual(sliced.bounds.lbrt(), (0, 5.0, 6.0, 6.0))
        self.assertEqual(sliced.xdensity, 0.5)
        self.assertEqual(sliced.ydensity, 1)
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[5:6, 5:8])

    def test_index_x_slice_y(self):
        sliced = self.image[3.2, 1.2:5.2]
        self.assertEqual(sliced.bounds.lbrt(), (2.0, 1.0, 4.0, 5.0))
        self.assertEqual(sliced.xdensity, 0.5)
        self.assertEqual(sliced.ydensity, 1)
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[1:5, 6:7])

    def test_range_xdim(self):
        self.assertEqual(self.image.range(0), (-10, 10))

    def test_range_datetime_xdim(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        xs = date_range(start, end, 10)
        image = Image((xs, self.ys, self.array))
        self.assertEqual(image.range(0), (start, end))

    def test_range_ydim(self):
        self.assertEqual(self.image.range(1), (0, 10))

    def test_range_datetime_ydim(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        ys = date_range(start, end, 10)
        image = Image((self.xs, ys, self.array))
        self.assertEqual(image.range(1), (start, end))

    def test_range_vdim(self):
        self.assertEqual(self.image.range(2), (0, 81))

    def test_dimension_values_xcoords(self):
        self.assertEqual(self.image.dimension_values(0, expanded=False),
                         np.linspace(-9, 9, 10))

    def test_dimension_values_datetime_xcoords(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        xs = date_range(start, end, 10)
        image = Image((xs, self.ys, self.array))
        self.assertEqual(image.dimension_values(0, expanded=False),
                         date_range(start, end, 10))

    def test_dimension_values_ycoords(self):
        self.assertEqual(self.image.dimension_values(1, expanded=False),
                         np.linspace(0.5, 9.5, 10))

    def test_sample_xcoord(self):
        ys = np.linspace(0.5, 9.5, 10)
        zs = [0, 7, 14, 21, 28, 35, 42, 49, 56, 63]
        with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], self.image):
            self.assertEqual(self.image.sample(x=5),
                             Curve((ys, zs), kdims=['y'], vdims=['z']))

    def test_sample_ycoord(self):
        xs = np.linspace(-9, 9, 10)
        zs = [0, 4, 8, 12, 16, 20, 24, 28, 32, 36]
        with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], self.image):
            self.assertEqual(self.image.sample(y=5),
                             Curve((xs, zs), kdims=['x'], vdims=['z']))

    def test_sample_coords(self):
        arr = np.arange(10)*np.arange(5)[np.newaxis].T
        xs = np.linspace(0.12, 0.81, 10)
        ys = np.linspace(0.12, 0.391, 5)
        img = Image((xs, ys, arr), kdims=['x', 'y'], vdims=['z'], datatype=[self.datatype])
        sampled = img.sample([(0.15, 0.15), (0.15, 0.4), (0.8, 0.4), (0.8, 0.15)])
        self.assertIsInstance(sampled, Table)
        yidx = [0, 4, 4, 0]
        xidx = [0, 0, 9, 9]
        table = Table((xs[xidx], ys[yidx], arr[yidx, xidx]), kdims=['x', 'y'], vdims=['z'])
        self.assertEqual(sampled, table)

    def test_reduce_to_scalar(self):
        self.assertEqual(self.image.reduce(['x', 'y'], function=np.mean),
                         20.25)

    def test_reduce_x_dimension(self):
        ys = np.linspace(0.5, 9.5, 10)
        zs = [0., 4.5, 9., 13.5, 18., 22.5, 27., 31.5, 36., 40.5]
        with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], Image):
            self.assertEqual(self.image.reduce(x=np.mean),
                             Curve((ys, zs), kdims=['y'], vdims=['z']))

    def test_reduce_y_dimension(self):
        xs = np.linspace(-9, 9, 10)
        zs = [0., 4.5, 9., 13.5, 18., 22.5, 27., 31.5, 36., 40.5]
        with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], Image):
            self.assertEqual(self.image.reduce(y=np.mean),
                             Curve((xs, zs), kdims=['x'], vdims=['z']))

    def test_dataset_reindex_constant(self):
        with DatatypeContext([self.datatype, 'dictionary', 'dataframe', 'grid'], self.image):
            selected = Dataset(self.image.select(x=0))
            reindexed = selected.reindex(['y'])
        data = Dataset(selected.columns(['y', 'z']),
                       kdims=['y'], vdims=['z'])
        self.assertEqual(reindexed, data)

    def test_dataset_reindex_non_constant(self):
        with DatatypeContext([self.datatype, 'dictionary', 'dataframe', 'grid'], self.image):
            ds = Dataset(self.image)
            reindexed = ds.reindex(['y'])
        data = Dataset(ds.columns(['y', 'z']),
                       kdims=['y'], vdims=['z'])
        self.assertEqual(reindexed, data)

    def test_aggregate_with_spreadfn(self):
        with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], self.image):
            agg = self.image.aggregate('x', np.mean, np.std)
        xs = self.image.dimension_values('x', expanded=False)
        mean = self.array.mean(axis=0)
        std = self.array.std(axis=0)
        self.assertEqual(agg, Curve((xs, mean, std), kdims=['x'],
                                    vdims=['z', 'z_std']))
 def init_data(self):
     self.xs = np.linspace(-9, 9, 10)
     self.ys = np.linspace(0.5, 9.5, 10)
     self.array = np.arange(10) * np.arange(10)[:, np.newaxis]
     self.image = Image((self.xs, self.ys, self.array))
     self.image_inv = Image((self.xs[::-1], self.ys[::-1], self.array[::-1, ::-1]))
Beispiel #43
0
 def test_rasterize_quadmesh_string_aggregator(self):
     qmesh = QuadMesh(([0, 1], [0, 1], np.array([[0, 1], [2, 3]])))
     img = rasterize(qmesh, width=3, height=3, dynamic=False, aggregator='mean')
     image = Image(np.array([[2., 3., np.NaN], [0, 1, np.NaN], [np.NaN, np.NaN, np.NaN]]),
                   bounds=(-.5, -.5, 1.5, 1.5))
     self.assertEqual(img, image)
 def test_init_data_datetime_yaxis(self):
     start = np.datetime64(dt.datetime.today())
     end = start+np.timedelta64(1, 's')
     ys = date_range(start, end, 10)
     Image((self.xs, ys, self.array))
Beispiel #45
0
 def test_operation_element(self):
     img = Image(np.random.rand(10, 10))
     op_img = operation(img, op=lambda x, k: x.clone(x.data*2))
     self.assertEqual(op_img, img.clone(img.data*2, group='Operation'))
 def test_init_data_tuple(self):
     xs = np.arange(5)
     ys = np.arange(10)
     array = xs * ys[:, np.newaxis]
     Image((xs, ys, array))
Beispiel #47
0
 def test_image_threshold(self):
     img = Image(np.array([[0, 1, 0], [3, 4, 5.]]))
     op_img = threshold(img)
     self.assertEqual(op_img, img.clone(np.array([[0, 1, 0], [1, 1, 1]]), group='Threshold'))
 def test_init_bounds_datetime_yaxis(self):
     start = np.datetime64(dt.datetime.today())
     end = start+np.timedelta64(1, 's')
     ys = date_range(start, end, 10)
     image = Image((self.xs, ys, self.array))
     self.assertEqual(image.bounds.lbrt(), (-10, start, 10, end))
Beispiel #49
0
 def test_regrid_disabled_upsampling(self):
     img = Image(([0.5, 1.5], [0.5, 1.5], [[0, 1], [2, 3]]))
     regridded = regrid(img, width=3, height=3, dynamic=False, upsample=False)
     self.assertEqual(regridded, img)
 def test_range_datetime_xdim(self):
     start = np.datetime64(dt.datetime.today())
     end = start+np.timedelta64(1, 's')
     xs = date_range(start, end, 10)
     image = Image((xs, self.ys, self.array))
     self.assertEqual(image.range(0), (start, end))
Beispiel #51
0
 def test_image_casting(self):
     img = Image([], bounds=2)
     self.assertEqual(img, Image(img))
 def test_aggregate_points_target(self):
     points = Points([(0.2, 0.3), (0.4, 0.7), (0, 0.99)])
     expected = Image(([0.25, 0.75], [0.25, 0.75], [[1, 0], [2, 0]]),
                      vdims=['Count'])
     img = aggregate(points, dynamic=False, target=expected)
     self.assertEqual(img, expected)
Beispiel #53
0
 def test_image_string_signature(self):
     img = Image(np.array([[0, 1], [0, 1]]), ['a', 'b'], 'c')
     self.assertEqual(img.kdims, [Dimension('a'), Dimension('b')])
     self.assertEqual(img.vdims, [Dimension('c')])
 def test_regrid_mean(self):
     img = Image(
         (range(10), range(5), np.arange(10) * np.arange(5)[np.newaxis].T))
     regridded = regrid(img, width=2, height=2, dynamic=False)
     expected = Image(([2., 7.], [0.75, 3.25], [[1, 5], [6, 22]]))
     self.assertEqual(regridded, expected)
class ImageInterfaceTest(ComparisonTestCase):

    datatype = 'image'

    def setUp(self):
        self.eltype = Image
        self.restore_datatype = self.eltype.datatype
        self.eltype.datatype = [self.datatype]
        self.init_data()

    def init_data(self):
        self.array = np.arange(10) * np.arange(10)[:, np.newaxis]
        self.image = Image(np.flipud(self.array), bounds=(-10, 0, 10, 10))

    def tearDown(self):
        self.eltype.datatype = self.restore_datatype

    def test_init_data_tuple(self):
        xs = np.arange(5)
        ys = np.arange(10)
        array = xs * ys[:, np.newaxis]
        Image((xs, ys, array))

    def test_init_data_tuple_error(self):
        xs = np.arange(5)
        ys = np.arange(10)
        array = xs * ys[:, np.newaxis]
        with self.assertRaises(DataError):
            Image((ys, xs, array))

    def test_bounds_mismatch(self):
        with self.assertRaises(ValueError):
            Image((range(10), range(10), np.random.rand(10, 10)), bounds=0.5)

    def test_init_data_datetime_xaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        Image(np.flipud(self.array), bounds=(start, 0, end, 10))

    def test_init_data_datetime_yaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        Image(np.flipud(self.array), bounds=(-10, start, 10, end))

    def test_init_bounds(self):
        self.assertEqual(self.image.bounds.lbrt(), (-10, 0, 10, 10))

    def test_init_bounds_datetime_xaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        bounds = (start, 0, end, 10)
        image = Image(np.flipud(self.array), bounds=bounds)
        self.assertEqual(image.bounds.lbrt(), bounds)

    def test_init_bounds_datetime_yaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        bounds = (-10, start, 10, end)
        image = Image(np.flipud(self.array), bounds=bounds)
        self.assertEqual(image.bounds.lbrt(), bounds)

    def test_init_densities(self):
        self.assertEqual(self.image.xdensity, 0.5)
        self.assertEqual(self.image.ydensity, 1)

    def test_init_densities_datetime_xaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        bounds = (start, 0, end, 10)
        image = Image(np.flipud(self.array), bounds=bounds)
        self.assertEqual(image.xdensity, 1e-5)
        self.assertEqual(image.ydensity, 1)

    def test_init_densities_datetime_yaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        bounds = (-10, start, 10, end)
        image = Image(np.flipud(self.array), bounds=bounds)
        self.assertEqual(image.xdensity, 0.5)
        self.assertEqual(image.ydensity, 1e-5)

    def test_dimension_values_xs(self):
        self.assertEqual(self.image.dimension_values(0, expanded=False),
                         np.linspace(-9, 9, 10))

    def test_dimension_values_ys(self):
        self.assertEqual(self.image.dimension_values(1, expanded=False),
                         np.linspace(0.5, 9.5, 10))

    def test_dimension_values_vdim(self):
        self.assertEqual(self.image.dimension_values(2, flat=False),
                         self.array)

    def test_index_single_coordinate(self):
        self.assertEqual(self.image[0.3, 5.1], 25)

    def test_slice_xaxis(self):
        sliced = self.image[0.3:5.2]
        self.assertEqual(sliced.bounds.lbrt(), (0, 0, 6, 10))
        self.assertEqual(sliced.xdensity, 0.5)
        self.assertEqual(sliced.ydensity, 1)
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[:, 5:8])

    def test_slice_datetime_xaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        bounds = (start, 0, end, 10)
        image = Image(np.flipud(self.array), bounds=bounds)
        sliced = image[start+np.timedelta64(530, 'ms'): start+np.timedelta64(770, 'ms')]
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[:, 5:8])

    def test_slice_yaxis(self):
        sliced = self.image[:, 1.2:5.2]
        self.assertEqual(sliced.bounds.lbrt(), (-10, 1., 10, 5))
        self.assertEqual(sliced.xdensity, 0.5)
        self.assertEqual(sliced.ydensity, 1)
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[1:5, :])

    def test_slice_datetime_yaxis(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        bounds = (-10, start, 10, end)
        image = Image(np.flipud(self.array), bounds=bounds)
        sliced = image[:, start+np.timedelta64(120, 'ms'): start+np.timedelta64(520, 'ms')]
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[1:5, :])

    def test_slice_both_axes(self):
        sliced = self.image[0.3:5.2, 1.2:5.2]
        self.assertEqual(sliced.bounds.lbrt(), (0, 1., 6, 5))
        self.assertEqual(sliced.xdensity, 0.5)
        self.assertEqual(sliced.ydensity, 1)
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[1:5, 5:8])

    def test_slice_x_index_y(self):
        sliced = self.image[0.3:5.2, 5.2]
        self.assertEqual(sliced.bounds.lbrt(), (0, 5.0, 6.0, 6.0))
        self.assertEqual(sliced.xdensity, 0.5)
        self.assertEqual(sliced.ydensity, 1)
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[5:6, 5:8])

    def test_index_x_slice_y(self):
        sliced = self.image[3.2, 1.2:5.2]
        self.assertEqual(sliced.bounds.lbrt(), (2.0, 1.0, 4.0, 5.0))
        self.assertEqual(sliced.xdensity, 0.5)
        self.assertEqual(sliced.ydensity, 1)
        self.assertEqual(sliced.dimension_values(2, flat=False),
                         self.array[1:5, 6:7])

    def test_range_xdim(self):
        self.assertEqual(self.image.range(0), (-10, 10))

    def test_range_datetime_xdim(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        bounds = (start, 0, end, 10)
        image = Image(np.flipud(self.array), bounds=bounds)
        self.assertEqual(image.range(0), (start, end))

    def test_range_ydim(self):
        self.assertEqual(self.image.range(1), (0, 10))

    def test_range_datetime_ydim(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        bounds = (-10, start, 10, end)
        image = Image(np.flipud(self.array), bounds=bounds)
        self.assertEqual(image.range(1), (start, end))

    def test_range_vdim(self):
        self.assertEqual(self.image.range(2), (0, 81))

    def test_dimension_values_xcoords(self):
        self.assertEqual(self.image.dimension_values(0, expanded=False),
                         np.linspace(-9, 9, 10))

    def test_dimension_values_datetime_xcoords(self):
        start = np.datetime64(dt.datetime.today())
        end = start+np.timedelta64(1, 's')
        bounds = (start, 0, end, 10)
        image = Image(np.flipud(self.array), bounds=bounds)
        self.assertEqual(image.dimension_values(0, expanded=False),
                         date_range(start, end, 10))

    def test_dimension_values_ycoords(self):
        self.assertEqual(self.image.dimension_values(1, expanded=False),
                         np.linspace(0.5, 9.5, 10))

    def test_sample_xcoord(self):
        ys = np.linspace(0.5, 9.5, 10)
        zs = [0, 7, 14, 21, 28, 35, 42, 49, 56, 63]
        with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], self.image):
            self.assertEqual(self.image.sample(x=5),
                             Curve((ys, zs), kdims=['y'], vdims=['z']))

    def test_sample_ycoord(self):
        xs = np.linspace(-9, 9, 10)
        zs = [0, 4, 8, 12, 16, 20, 24, 28, 32, 36]
        with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], self.image):
            self.assertEqual(self.image.sample(y=5),
                             Curve((xs, zs), kdims=['x'], vdims=['z']))

    def test_sample_coords(self):
        arr = np.arange(10)*np.arange(5)[np.newaxis].T
        xs = np.linspace(0.12, 0.81, 10)
        ys = np.linspace(0.12, 0.391, 5)
        img = Image((xs, ys, arr), kdims=['x', 'y'], vdims=['z'], datatype=[self.datatype])
        sampled = img.sample([(0.15, 0.15), (0.15, 0.4), (0.8, 0.4), (0.8, 0.15)])
        self.assertIsInstance(sampled, Table)
        yidx = [0, 4, 4, 0]
        xidx = [0, 0, 9, 9]
        table = Table((xs[xidx], ys[yidx], arr[yidx, xidx]), kdims=['x', 'y'], vdims=['z'])
        self.assertEqual(sampled, table)

    def test_reduce_to_scalar(self):
        self.assertEqual(self.image.reduce(['x', 'y'], function=np.mean),
                         20.25)

    def test_reduce_x_dimension(self):
        ys = np.linspace(0.5, 9.5, 10)
        zs = [0., 4.5, 9., 13.5, 18., 22.5, 27., 31.5, 36., 40.5]
        with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], Image):
            self.assertEqual(self.image.reduce(x=np.mean),
                             Curve((ys, zs), kdims=['y'], vdims=['z']))

    def test_reduce_y_dimension(self):
        xs = np.linspace(-9, 9, 10)
        zs = [0., 4.5, 9., 13.5, 18., 22.5, 27., 31.5, 36., 40.5]
        with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], Image):
            self.assertEqual(self.image.reduce(y=np.mean),
                             Curve((xs, zs), kdims=['x'], vdims=['z']))

    def test_dataset_reindex_constant(self):
        with DatatypeContext([self.datatype, 'dictionary', 'dataframe', 'grid'], self.image):
            selected = Dataset(self.image.select(x=0))
            reindexed = selected.reindex(['y'])
        data = Dataset(selected.columns(['y', 'z']),
                       kdims=['y'], vdims=['z'])
        self.assertEqual(reindexed, data)

    def test_dataset_reindex_non_constant(self):
        with DatatypeContext([self.datatype, 'dictionary', 'dataframe', 'grid'], self.image):
            ds = Dataset(self.image)
            reindexed = ds.reindex(['y'])
        data = Dataset(ds.columns(['y', 'z']),
                       kdims=['y'], vdims=['z'])
        self.assertEqual(reindexed, data)

    def test_aggregate_with_spreadfn(self):
        with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], self.image):
            agg = self.image.aggregate('x', np.mean, np.std)
        xs = self.image.dimension_values('x', expanded=False)
        mean = self.array.mean(axis=0)
        std = self.array.std(axis=0)
        self.assertEqual(agg, Curve((xs, mean, std), kdims=['x'],
                                    vdims=['z', 'z_std']))
Beispiel #56
0
 def test_image_transform(self):
     img = Image(np.random.rand(10, 10))
     op_img = transform(img, operator=lambda x: x * 2)
     self.assertEqual(op_img, img.clone(img.data * 2, group='Transform'))
Beispiel #57
0
    def _collate_results(self, p):
        results = Layout()

        timestamp = self.metadata.timestamp

        # Generate dimension info dictionary from features
        dimensions = [features.Time, features.Duration] + self.outer
        pattern_dimensions = self.outer + self.inner
        pattern_dim_label = '_'.join(f.name.capitalize() for f in pattern_dimensions)

        for label in self.measurement_product:
            name = label[0] # Measurement source
            f_vals = label[1:] # Duration and outer feature values

            #Metadata
            inner_features = dict([(f.name, f) for f in self.inner])
            output_metadata = dict(self.metadata.outputs[name], inner_features=inner_features)

            # Iterate over inner features
            fr = self._featureresponses[name][f_vals]
            for fname, fdist in fr.items():
                feature = fname.capitalize()
                base_name = self.measurement_prefix + feature

                # Get information from the feature
                fp = [f for f in self.features if f.name.lower() == fname][0]
                pref_fn = fp.preference_fn if has_preference_fn(fp)\
                    else self.preference_fn
                if p.selectivity_multiplier is not None:
                    pref_fn.selectivity_scale = (pref_fn.selectivity_scale[0],
                                                 p.selectivity_multiplier)

                # Get maps and iterate over them
                response = fdist.apply_DSF(pref_fn)
                for k, maps in response.items():
                    for map_name, map_view in maps.items():
                        # Set labels and metadata
                        map_index = base_name + k + map_name.capitalize()
                        map_label = ' '.join([base_name, map_name.capitalize()])
                        cyclic = (map_name != 'selectivity' and fp.cyclic)
                        fprange = fp.range if cyclic else (None, None)
                        value_dimension = Dimension(map_label, cyclic=cyclic, range=fprange)
                        self._set_style(fp, map_name)

                        # Create views and stacks
                        im = Image(map_view, bounds=output_metadata['bounds'],
                                   label=name, group=map_label,
                                   vdims=[value_dimension])
                        im.metadata=AttrDict(timestamp=timestamp)
                        key = (timestamp,)+f_vals
                        if (map_label.replace(' ', ''), name) not in results:
                            vmap = HoloMap((key, im), kdims=dimensions,
                                           label=name, group=map_label)
                            vmap.metadata = AttrDict(**output_metadata)
                            results.set_path((map_index, name), vmap)
                        else:
                            results.path_items[(map_index, name)][key] = im
                if p.store_responses:
                    info = (p.pattern_generator.__class__.__name__, pattern_dim_label, 'Response')
                    results.set_path(('%s_%s_%s' % info, name), self._responses[name])

        return results
 def test_range_datetime_ydim(self):
     start = np.datetime64(dt.datetime.today())
     end = start+np.timedelta64(1, 's')
     bounds = (-10, start, 10, end)
     image = Image(np.flipud(self.array), bounds=bounds)
     self.assertEqual(image.range(1), (start, end))
 def init_data(self):
     self.array = np.arange(10) * np.arange(10)[:, np.newaxis]
     self.image = Image(np.flipud(self.array), bounds=(-10, 0, 10, 10))
Beispiel #60
0
 def test_spikes_aggregate_count_dask(self):
     spikes = Spikes([1, 2, 3], datatype=['dask'])
     agg = rasterize(spikes, width=5, dynamic=False, expand=False)
     expected = Image(np.array([[1, 0, 1, 0, 1]]), vdims='count',
                      xdensity=2.5, ydensity=1, bounds=(1, 0, 3, 0.5))
     self.assertEqual(agg, expected)