Exemple #1
0
    def _update_proj_cog(self, p, proj):
        """Measure the CoG of the specified projection and register corresponding SheetViews."""

        sheet = proj.dest
        rows, cols = sheet.activity.shape
        xcog = np.zeros((rows, cols), np.float64)
        ycog = np.zeros((rows, cols), np.float64)

        for r in xrange(rows):
            for c in xrange(cols):
                cf = proj.cfs[r, c]
                r1, r2, c1, c2 = cf.input_sheet_slice
                row_centroid, col_centroid = centroid(cf.weights)
                xcentroid, ycentroid = proj.src.matrix2sheet(
                    r1 + row_centroid + 0.5, c1 + col_centroid + 0.5)

                xcog[r][c] = xcentroid
                ycog[r][c] = ycentroid

        metadata = AttrDict(precedence=sheet.precedence,
                            row_precedence=sheet.row_precedence,
                            src_name=sheet.name)

        timestamp = topo.sim.time()
        lbrt = sheet.bounds.lbrt()
        xsv = Image(xcog,
                    sheet.bounds,
                    label=proj.name,
                    group='X CoG',
                    vdims=[Dimension('X CoG', range=(lbrt[0], lbrt[2]))])
        ysv = Image(ycog,
                    sheet.bounds,
                    label=proj.name,
                    group='Y CoG',
                    vdims=[Dimension('Y CoG', range=(lbrt[1], lbrt[3]))])

        lines = []
        hlines, vlines = xsv.data.shape
        for hind in range(hlines)[::p.stride]:
            lines.append(np.vstack([xsv.data[hind, :].T, ysv.data[hind, :]]).T)
        for vind in range(vlines)[::p.stride]:
            lines.append(np.vstack([xsv.data[:, vind].T, ysv.data[:, vind]]).T)
        cogmesh = Contours(lines,
                           extents=sheet.bounds.lbrt(),
                           label=proj.name,
                           group='Center of Gravity')

        xcog_map = HoloMap((timestamp, xsv), kdims=[features.Time])
        xcog_map.metadata = metadata
        ycog_map = HoloMap((timestamp, ysv), kdims=[features.Time])
        ycog_map.metadata = metadata

        contour_map = HoloMap((timestamp, cogmesh), kdims=[features.Time])
        contour_map.metadata = metadata

        return {'XCoG': xcog_map, 'YCoG': ycog_map, 'CoG': contour_map}
Exemple #2
0
    def _update_proj_cog(self, p, proj):
        """Measure the CoG of the specified projection and register corresponding SheetViews."""

        sheet = proj.dest
        rows, cols = sheet.activity.shape
        xcog = np.zeros((rows, cols), np.float64)
        ycog = np.zeros((rows, cols), np.float64)

        for r in xrange(rows):
            for c in xrange(cols):
                cf = proj.cfs[r, c]
                r1, r2, c1, c2 = cf.input_sheet_slice
                row_centroid, col_centroid = centroid(cf.weights)
                xcentroid, ycentroid = proj.src.matrix2sheet(
                    r1 + row_centroid + 0.5,
                    c1 + col_centroid + 0.5)

                xcog[r][c] = xcentroid
                ycog[r][c] = ycentroid

        metadata = AttrDict(precedence=sheet.precedence,
                            row_precedence=sheet.row_precedence,
                            src_name=sheet.name)

        timestamp = topo.sim.time()
        lbrt = sheet.bounds.lbrt()
        xsv = Image(xcog, sheet.bounds, label=proj.name, group='X CoG',
                    value_dimensions=[Dimension('X CoG', range=(lbrt[0], lbrt[2]))])
        ysv = Image(ycog, sheet.bounds, label=proj.name, group='Y CoG',
                    value_dimensions=[Dimension('Y CoG', range=(lbrt[1], lbrt[3]))])

        lines = []
        hlines, vlines = xsv.data.shape
        for hind in range(hlines)[::p.stride]:
            lines.append(np.vstack([xsv.data[hind,:].T, ysv.data[hind,:]]).T)
        for vind in range(vlines)[::p.stride]:
            lines.append(np.vstack([xsv.data[:,vind].T, ysv.data[:,vind]]).T)
        cogmesh = Contours(lines, extents=sheet.bounds.lbrt(), label=proj.name,
                           group='Center of Gravity')

        xcog_map = HoloMap((timestamp, xsv), key_dimensions=[features.Time])
        xcog_map.metadata = metadata
        ycog_map = HoloMap((timestamp, ysv), key_dimensions=[features.Time])
        ycog_map.metadata = metadata

        contour_map = HoloMap((timestamp, cogmesh), key_dimensions=[features.Time])
        contour_map.metadata = metadata

        return {'XCoG': xcog_map, 'YCoG': ycog_map, 'CoG': contour_map}
Exemple #3
0
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
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
Exemple #5
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
Exemple #6
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
    def _collate_results(self, responses, label):
        time = self.metadata.timestamp
        dims = [f.Time, f.Duration]

        response_label = label + ' Response'
        results = Layout()
        for label, response in responses.items():
            name, duration = label
            path = (response_label.replace(' ', ''), name)
            label = ' '.join([name, response_label])
            metadata = self.metadata['outputs'][name]
            if path not in results:
                vmap = HoloMap(key_dimensions=dims)
                vmap.metadata = AttrDict(**metadata)
                results.set_path(path, vmap)

            im = Image(response, metadata['bounds'], label=label, group='Activity')
            im.metadata=AttrDict(timestamp=time)
            results[path][(time, duration)] = im
        return results
Exemple #8
0
    def view(self, sheet_x, sheet_y, timestamp=None, situated=False, **kwargs):
        """
        Return a single connection field Image, for the unit
        located nearest to sheet coordinate (sheet_x,sheet_y).
        """
        if timestamp is None:
            timestamp = self.src.simulation.time()
        time_dim = Dimension("Time", type=param.Dynamic.time_fn.time_type)
        (r, c) = self.dest.sheet2matrixidx(sheet_x, sheet_y)
        cf = self.cfs[r, c]
        r1, r2, c1, c2 = cf.input_sheet_slice
        situated_shape = self.src.activity.shape
        situated_bounds = self.src.bounds
        roi_bounds = cf.get_bounds(self.src)
        if situated:
            matrix_data = np.zeros(situated_shape, dtype=np.float64)
            matrix_data[r1:r2, c1:c2] = cf.weights.copy()
            bounds = situated_bounds
        else:
            matrix_data = cf.weights.copy()
            bounds = roi_bounds

        sv = CFView(matrix_data,
                    bounds,
                    situated_bounds=situated_bounds,
                    input_sheet_slice=(r1, r2, c1, c2),
                    roi_bounds=roi_bounds,
                    label=self.name,
                    group='CF Weight')
        sv.metadata = AttrDict(timestamp=timestamp)

        viewmap = HoloMap((timestamp, sv), kdims=[time_dim])
        viewmap.metadata = AttrDict(coords=(sheet_x, sheet_y),
                                    dest_name=self.dest.name,
                                    precedence=self.src.precedence,
                                    proj_name=self.name,
                                    src_name=self.src.name,
                                    row_precedence=self.src.row_precedence,
                                    timestamp=timestamp,
                                    **kwargs)
        return viewmap
Exemple #9
0
    def view(self, sheet_x, sheet_y, timestamp=None, situated=False, **kwargs):
        """
        Return a single connection field Image, for the unit
        located nearest to sheet coordinate (sheet_x,sheet_y).
        """
        if timestamp is None:
            timestamp = self.src.simulation.time()
        time_dim = Dimension("Time", type=param.Dynamic.time_fn.time_type)
        (r, c) = self.dest.sheet2matrixidx(sheet_x, sheet_y)
        cf = self.cfs[r, c]
        r1, r2, c1, c2 = cf.input_sheet_slice
        situated_shape = self.src.activity.shape
        situated_bounds = self.src.bounds
        roi_bounds = cf.get_bounds(self.src)
        if situated:
            matrix_data = np.zeros(situated_shape, dtype=np.float64)
            matrix_data[r1:r2, c1:c2] = cf.weights.copy()
            bounds = situated_bounds
        else:
            matrix_data = cf.weights.copy()
            bounds = roi_bounds

        sv = CFView(matrix_data, bounds, situated_bounds=situated_bounds,
                    input_sheet_slice=(r1, r2, c1, c2), roi_bounds=roi_bounds,
                    label=self.name, group='CF Weight')
        sv.metadata=AttrDict(timestamp=timestamp)

        viewmap = HoloMap((timestamp, sv), kdims=[time_dim])
        viewmap.metadata = AttrDict(coords=(sheet_x, sheet_y),
                                    dest_name=self.dest.name,
                                    precedence=self.src.precedence,
                                    proj_name=self.name,
                                    src_name=self.src.name,
                                    row_precedence=self.src.row_precedence,
                                    timestamp=timestamp, **kwargs)
        return viewmap
Exemple #10
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