def get_mapped_array_volume_view(self, entity_gid, mapped_array_gid, x_plane, y_plane, z_plane,
                                     mapped_array_slice=None, **kwargs):

        with h5.h5_file_for_gid(entity_gid) as entity_h5:
            data_shape = entity_h5.array_data.shape
            x_plane, y_plane, z_plane = preprocess_space_parameters(x_plane, y_plane, z_plane, data_shape[0],
                                                                    data_shape[1], data_shape[2])
            slice_x, slice_y, slice_z = entity_h5.get_volume_slice(x_plane, y_plane, z_plane)
            connectivity_gid = entity_h5.connectivity.load()

        with h5.h5_file_for_gid(mapped_array_gid) as mapped_array_h5:
            if mapped_array_slice:
                matrix_slice = parse_slice(mapped_array_slice)
                measure = mapped_array_h5.array_data[matrix_slice]
            else:
                measure = mapped_array_h5.array_data[:]

        connectivity_index = self.load_entity_by_gid(connectivity_gid)
        if measure.shape != (connectivity_index.number_of_regions,):
            raise ValueError('cannot project measure on the space')

        result_x = measure[slice_x]
        result_y = measure[slice_y]
        result_z = measure[slice_z]
        # Voxels outside the brain are -1. The indexing above is incorrect for those voxels as it
        # associates the values of the last region measure[-1] to them.
        # Here we replace those values with an out of scale value.
        result_x[slice_x == -1] = measure.min() - 1
        result_y[slice_y == -1] = measure.min() - 1
        result_z[slice_z == -1] = measure.min() - 1

        return [[result_x.tolist()],
                [result_y.tolist()],
                [result_z.tolist()]]
Example #2
0
    def compute_data_for_gradient_view(self, local_connectivity_gid,
                                       selected_triangle):
        """
        When the user loads an existent local connectivity and he picks a vertex from the used surface, this
        method computes the data needed for drawing a gradient view corresponding to that vertex.

        Returns a json which contains the data needed for drawing a gradient view for the selected vertex.
        """
        triangle_index = int(selected_triangle)
        lconn_h5 = h5.h5_file_for_gid(local_connectivity_gid)

        surface_h5 = h5.h5_file_for_gid(lconn_h5.surface.load())
        assert isinstance(surface_h5, SurfaceH5)
        vertex_index = int(surface_h5.triangles[triangle_index][0])

        assert isinstance(lconn_h5, LocalConnectivityH5)
        lconn_matrix = lconn_h5.matrix.load()
        picked_data = list(lconn_matrix[vertex_index].toarray().squeeze())
        lconn_h5.close()

        result = []
        number_of_split_slices = surface_h5.number_of_split_slices.load()
        if number_of_split_slices <= 1:
            result.append(picked_data)
        else:
            for slice_number in range(number_of_split_slices):
                start_idx, end_idx = surface_h5.get_slice_vertex_boundaries(
                    slice_number)
                result.append(picked_data[start_idx:end_idx])

        surface_h5.close()
        result = {'data': json.dumps(result)}
        return result
Example #3
0
    def read_data_page_split(self,
                             time_series_gid,
                             from_idx,
                             to_idx,
                             step=None,
                             specific_slices=None):
        with h5.h5_file_for_gid(time_series_gid) as time_series_h5:
            assert isinstance(time_series_h5, TimeSeriesH5)
            basic_result = time_series_h5.read_data_page(
                from_idx, to_idx, step, specific_slices)

            if not isinstance(time_series_h5, TimeSeriesSurfaceH5):
                return basic_result.tolist()
            surface_gid = time_series_h5.surface.load()

        result = []
        with h5.h5_file_for_gid(surface_gid) as surface_h5:
            assert isinstance(surface_h5, SurfaceH5)
            number_of_split_slices = surface_h5.number_of_split_slices.load()
            if number_of_split_slices <= 1:
                result.append(basic_result.tolist())
            else:
                for slice_number in range(surface_h5.number_of_split_slices):
                    start_idx, end_idx = surface_h5.get_slice_vertex_boundaries(
                        slice_number)
                    result.append(basic_result[:, start_idx:end_idx].tolist())

        return result
Example #4
0
    def generate_region_boundaries(self, surface_gid, region_mapping_gid):
        """
        Return the full region boundaries, including: vertices, normals and lines indices.
        """
        boundary_vertices = []
        boundary_lines = []
        boundary_normals = []

        with h5.h5_file_for_gid(region_mapping_gid) as rm_h5:
            array_data = rm_h5.array_data[:]

        with h5.h5_file_for_gid(surface_gid) as surface_h5:
            for slice_idx in range(surface_h5.get_number_of_split_slices()):
                # Generate the boundaries sliced for the off case where we might overflow the buffer capacity
                slice_triangles = surface_h5.get_triangles_slice(slice_idx)
                slice_vertices = surface_h5.get_vertices_slice(slice_idx)
                slice_normals = surface_h5.get_vertex_normals_slice(slice_idx)
                first_index_in_slice = surface_h5.split_slices.load()[str(
                    slice_idx)][KEY_VERTICES][KEY_START]
                # These will keep track of the vertices / triangles / normals for this slice that have
                # been processed and were found as a part of the boundary
                processed_vertices = []
                processed_triangles = []
                processed_normals = []
                for triangle in slice_triangles:
                    triangle += first_index_in_slice
                    # Check if there are two points from a triangles that are in separate regions
                    # then send this to further processing that will generate the corresponding
                    # region separation lines depending on the 3rd point from the triangle
                    rt0, rt1, rt2 = array_data[triangle]
                    if rt0 - rt1:
                        reg_idx1, reg_idx2, dangling_idx = 0, 1, 2
                    elif rt1 - rt2:
                        reg_idx1, reg_idx2, dangling_idx = 1, 2, 0
                    elif rt2 - rt0:
                        reg_idx1, reg_idx2, dangling_idx = 2, 0, 1
                    else:
                        continue

                    lines_vert, lines_ind, lines_norm = self._process_triangle(
                        triangle, reg_idx1, reg_idx2, dangling_idx,
                        first_index_in_slice, array_data, slice_vertices,
                        slice_normals)
                    ind_offset = len(processed_vertices) / 3
                    processed_vertices.extend(lines_vert)
                    processed_normals.extend(lines_norm)
                    processed_triangles.extend(
                        [ind + ind_offset for ind in lines_ind])
                boundary_vertices.append(processed_vertices)
                boundary_lines.append(processed_triangles)
                boundary_normals.append(processed_normals)
            return numpy.array(
                [boundary_vertices, boundary_lines,
                 boundary_normals]).tolist()
Example #5
0
    def extract_source_labels(self, datatype_matrix):
        # type: (DataTypeMatrix) -> list
        if hasattr(datatype_matrix, "fk_connectivity_gid"):
            with h5.h5_file_for_gid(datatype_matrix.fk_connectivity_gid) as conn_h5:
                labels = list(conn_h5.region_labels.load())
            return labels

        if hasattr(datatype_matrix, "fk_source_gid"):
            with h5.h5_file_for_gid(datatype_matrix.fk_source_gid) as source_h5:
                labels = self.get_space_labels(source_h5)
            return labels

        return None
Example #6
0
    def launch(self, view_model):
        # type: (PCAModel) -> dict
        """Construct data for visualization and launch it."""
        with h5.h5_file_for_gid(view_model.pca) as ts_h5:
            source_gid = ts_h5.source.load()

        with h5.h5_file_for_gid(source_gid) as source_h5:
            labels_data = self.get_space_labels(source_h5)

        fractions_update_url = URLGenerator.build_h5_url(view_model.pca, 'read_fractions_data')
        weights_update_url = URLGenerator.build_h5_url(view_model.pca, 'read_weights_data')
        return self.build_display_result("pca/view", dict(labels_data=json.dumps(labels_data),
                                                          fractions_update_url=fractions_update_url,
                                                          weights_update_url=weights_update_url))
Example #7
0
    def launch(self, view_model):
        # type: (ConnectivityViewerModel) -> dict
        """
        Given the input connectivity data and the surface data, 
        build the HTML response to be displayed.
        """
        connectivity, colors, rays = self._load_input_data(view_model)

        global_params, global_pages = self._compute_connectivity_global_params(connectivity)
        if view_model.surface_data is not None:
            with h5.h5_file_for_gid(view_model.surface_data) as surface_h5:
                url_vertices, url_normals, _, url_triangles, _ = SurfaceURLGenerator.get_urls_for_rendering(surface_h5)
        else:
            url_vertices, url_normals, url_triangles = [], [], []

        global_params["urlVertices"] = json.dumps(url_vertices)
        global_params["urlTriangles"] = json.dumps(url_triangles)
        global_params["urlNormals"] = json.dumps(url_normals)
        global_params['isSingleMode'] = False

        result_params, result_pages = Connectivity2DViewer().compute_parameters(connectivity, colors, rays,
                                                                                view_model.step)
        result_params.update(global_params)
        result_pages.update(global_pages)
        _params, _pages = Connectivity3DViewer().compute_parameters(connectivity, colors, rays)
        result_params.update(_params)
        result_pages.update(_pages)

        return self.build_display_result("connectivity/main_connectivity", result_params, result_pages)
Example #8
0
    def launch(self, view_model):
        # type: (PearsonCorrelationCoefficientVisualizerModel) -> dict
        """Construct data for visualization and launch it."""

        with h5.h5_file_for_gid(view_model.datatype) as datatype_h5:
            matrix_shape = datatype_h5.array_data.shape[0:2]
            ts_gid = datatype_h5.source.load()

        ts_index = self.load_entity_by_gid(ts_gid)
        state_list = ts_index.get_labels_for_dimension(1)
        mode_list = list(range(ts_index.data_length_4d))

        with h5.h5_file_for_index(ts_index) as ts_h5:
            labels = self.get_space_labels(ts_h5)

        if not labels:
            labels = None
        pars = dict(matrix_labels=json.dumps(labels),
                    matrix_shape=json.dumps(matrix_shape),
                    viewer_title='Pearson Edge Bundle',
                    url_base=URLGenerator.build_h5_url(view_model.datatype.hex, 'get_correlation_data', flatten="True",
                                                       parameter=''),
                    state_variable=0,
                    mode=mode_list[0],
                    state_list=state_list,
                    mode_list=mode_list,
                    pearson_min=CorrelationCoefficients.PEARSON_MIN,
                    pearson_max=CorrelationCoefficients.PEARSON_MAX,
                    thresh=0.5
                    )

        return self.build_display_result("pearson_edge_bundle/view", pars)
Example #9
0
    def display_surface(surface_gid, region_mapping_gid=None):
        """
        Generates the HTML for displaying the surface with the given ID.
        """
        surface_h5 = h5.h5_file_for_gid(surface_gid)
        if surface_h5 is None:
            raise MissingDataException(
                SpatioTemporalController.MSG_MISSING_SURFACE + "!!")
        common.add2session(PARAM_SURFACE, surface_gid)

        url_vertices_pick, url_normals_pick, url_triangles_pick = SurfaceURLGenerator.get_urls_for_pick_rendering(
            surface_h5)
        url_vertices, url_normals, _, url_triangles, _ = SurfaceURLGenerator.get_urls_for_rendering(
            surface_h5, region_mapping_gid)
        surface_h5.close()

        return {
            'urlVerticesPick': json.dumps(url_vertices_pick),
            'urlTrianglesPick': json.dumps(url_triangles_pick),
            'urlNormalsPick': json.dumps(url_normals_pick),
            'urlVertices': json.dumps(url_vertices),
            'urlTriangles': json.dumps(url_triangles),
            'urlNormals': json.dumps(url_normals),
            'brainCenter': json.dumps(surface_h5.center())
        }
    def get_view_region(self,
                        ts_h5,
                        volume_rm_h5,
                        from_idx,
                        to_idx,
                        x,
                        y,
                        z,
                        var=0,
                        mode=0):
        idx_slices = slice(x, x + 1), slice(y, y + 1), slice(z, z + 1)

        idx = int(volume_rm_h5.array_data[idx_slices])

        time_length = ts_h5.data.shape[0]
        var, mode = int(var), int(mode)
        voxel_slices = prepare_time_slice(time_length), slice(
            var, var + 1), slice(idx, idx + 1), slice(mode, mode + 1)

        connectivity_gid = volume_rm_h5.connectivity.load()
        with h5.h5_file_for_gid(connectivity_gid) as connectivity_h5:
            label = connectivity_h5.region_labels.load()[idx]

        background, back_min, back_max = None, None, None
        if idx < 0:
            back_min, back_max = ts_h5.get_min_max_values()
            background = numpy.ones(
                (time_length, 1)) * ts_h5.out_of_range(back_min)
            label = 'background'

        result = postprocess_voxel_ts(ts_h5, voxel_slices, background,
                                      back_min, back_max, label)
        return result
    def get_volume_view(self, entity_gid, **kwargs):
        with h5.h5_file_for_gid(entity_gid) as ts_region_h5:
            if isinstance(ts_region_h5, TimeSeriesRegionH5):
                return self.prepare_view_region(ts_region_h5, **kwargs)

            volume_view = ts_region_h5.get_volume_view(**kwargs)
        return volume_view
    def prepare_view_region(self,
                            ts_h5,
                            x_plane,
                            y_plane,
                            z_plane,
                            from_idx=None,
                            to_idx=None,
                            var=0,
                            mode=0):
        region_mapping_volume_gid = ts_h5.region_mapping_volume.load()

        if region_mapping_volume_gid is None:
            raise Exception(
                "Invalid method called for TS without Volume Mapping!")

        with h5.h5_file_for_gid(region_mapping_volume_gid) as volume_rm_h5:
            volume_rm_shape = volume_rm_h5.array_data.shape

            # Work with space inside Volume:
            x_plane, y_plane, z_plane = preprocess_space_parameters(
                x_plane, y_plane, z_plane, volume_rm_shape[0],
                volume_rm_shape[1], volume_rm_shape[2])
            region = self.get_view_region(ts_h5, volume_rm_h5, from_idx,
                                          to_idx, x_plane, y_plane, z_plane,
                                          var, mode)

        return region
    def launch(self, view_model):
        # type: (ImaginaryCoherenceDisplayModel) -> dict
        """
        Draw interactive display.
        """
        self.log.debug("Plot started...")

        with h5.h5_file_for_gid(view_model.input_data) as input_data_h5:
            source_gid = input_data_h5.source.load()
            source_index = self.load_entity_by_gid(source_gid)

            params = dict(
                plotName=source_index.type,
                xAxisName="Frequency [kHz]",
                yAxisName="CohSpec",
                available_xScale=["Linear", "Logarithmic"],
                available_spectrum=json.dumps(input_data_h5.spectrum_types),
                spectrum_list=input_data_h5.spectrum_types,
                xscale="Linear",
                spectrum=input_data_h5.spectrum_types[0],
                url_base=URLGenerator.build_h5_url(view_model.input_data,
                                                   'get_spectrum_data',
                                                   parameter=""),
                # TODO investigate the static xmin and xmax values
                xmin=0.02,
                xmax=0.8)

        return self.build_display_result("complex_coherence/view", params)
    def get_required_memory_size(self, view_model):
        # type: (ImaginaryCoherenceDisplayModel) -> numpy.ndarray
        """
        Return the required memory to run this algorithm.
        """
        with h5.h5_file_for_gid(view_model.input_data) as input_data_h5:
            required_memory = numpy.prod(input_data_h5.read_data_shape()) * 8

        return required_memory
Example #15
0
    def get_space_labels(self, ts_h5):
        """
        :return: An array of strings with the connectivity node labels.
        """
        if type(ts_h5) is TimeSeriesRegionH5:
            connectivity_gid = ts_h5.connectivity.load()
            if connectivity_gid is None:
                return []

            with h5.h5_file_for_gid(connectivity_gid) as conn_h5:
                return list(conn_h5.region_labels.load())

        if isinstance(ts_h5, TimeSeriesSensorsH5):
            sensors_gid = ts_h5.sensors.load()
            if sensors_gid is None:
                return []
            with h5.h5_file_for_gid(sensors_gid) as sensors_h5:
                return list(sensors_h5.labels.load())

        return ts_h5.get_space_labels()
Example #16
0
    def launch(self, view_model):
        params = dict(title="Local Connectivity Visualizer",
                      extended_view=False,
                      isOneToOneMapping=False,
                      hasRegionMap=False)

        local_conn_h5 = h5.h5_file_for_gid(view_model.local_conn)
        with local_conn_h5:
            surface_gid = local_conn_h5.surface.load()
            min_value, max_value = local_conn_h5.get_min_max_values()

        with h5.h5_file_for_gid(surface_gid) as surface_h5:
            params.update(self._compute_surface_params(surface_h5))

        params['local_connectivity_gid'] = view_model.local_conn.hex
        params['minValue'] = min_value
        params['maxValue'] = max_value
        return self.build_display_result(
            "local_connectivity/view",
            params,
            pages={"controlPage": "local_connectivity/controls"})
Example #17
0
    def launch(self, view_model):
        # type: (WaveletSpectrogramVisualizerModel) -> dict

        with h5.h5_file_for_gid(view_model.input_data) as input_h5:
            shape = input_h5.array_data.shape
            input_sample_period = input_h5.sample_period.load()
            input_frequencies = input_h5.frequencies.load()
            ts_index = self.load_entity_by_gid(input_h5.source.load())

            slices = (slice(shape[0]), slice(shape[1]), slice(0, 1, None),
                      slice(0, shape[3], None), slice(0, 1, None))
            data_matrix = input_h5.power[slices]
            data_matrix = data_matrix.sum(axis=3)

        assert isinstance(ts_index, TimeSeriesIndex)

        wavelet_sample_period = ts_index.sample_period * max(
            (1, int(input_sample_period / ts_index.sample_period)))
        end_time = ts_index.start_time + (wavelet_sample_period * shape[1])

        if len(input_frequencies):
            freq_lo = input_frequencies[0]
            freq_hi = input_frequencies[-1]
        else:
            freq_lo = 0
            freq_hi = 1

        scale_range_start = max(1, int(0.25 * shape[1]))
        scale_range_end = max(1, int(0.75 * shape[1]))
        scale_min = data_matrix[:, scale_range_start:scale_range_end, :].min()
        scale_max = data_matrix[:, scale_range_start:scale_range_end, :].max()
        matrix_data = ABCDisplayer.dump_with_precision(data_matrix.flat)
        matrix_shape = json.dumps(data_matrix.squeeze().shape)

        params = dict(canvasName="Wavelet Spectrogram for: " + ts_index.title,
                      xAxisName="Time (%s)" % str(ts_index.sample_period_unit),
                      yAxisName="Frequency (%s)" % str("kHz"),
                      title=self._ui_name,
                      matrix_data=matrix_data,
                      matrix_shape=matrix_shape,
                      start_time=ts_index.start_time,
                      end_time=end_time,
                      freq_lo=freq_lo,
                      freq_hi=freq_hi,
                      vmin=scale_min,
                      vmax=scale_max)

        return self.build_display_result(
            "wavelet/wavelet_view",
            params,
            pages={"controlPage": "wavelet/controls"})
Example #18
0
    def get_voxel_region(self, region_mapping_volume_gid, x_plane, y_plane, z_plane):
        with h5.h5_file_for_gid(region_mapping_volume_gid) as entity_h5:
            data_shape = entity_h5.array_data.shape
            x_plane, y_plane, z_plane = preprocess_space_parameters(x_plane, y_plane, z_plane, data_shape[0],
                                                                    data_shape[1], data_shape[2])
            slices = slice(x_plane, x_plane + 1), slice(y_plane, y_plane + 1), slice(z_plane, z_plane + 1)
            voxel = entity_h5.array_data[slices][0, 0, 0]
            connectivity_gid = entity_h5.connectivity.load()

        if voxel != -1:
            conn = self.load_traited_by_gid(connectivity_gid)
            return conn.region_labels[int(voxel)]
        else:
            return 'background'
Example #19
0
    def _base_before_launch(self, data_file, region_volume_gid):
        if data_file is None:
            raise LaunchException("Please select a file to import!")

        if region_volume_gid is not None:
            rvm_h5 = h5.h5_file_for_gid(region_volume_gid)
            self._attempt_to_cache_regionmap(rvm_h5)
            self.region_volume_shape = rvm_h5.read_data_shape()
            self.region_volume_h5 = rvm_h5

        datatype = Tracts()
        dummy_rvm = RegionVolumeMapping()
        dummy_rvm.gid = region_volume_gid
        datatype.region_volume_map = dummy_rvm
        return datatype
Example #20
0
    def launch(self, view_model):
        # type: (CrossCoherenceVisualizerModel) -> dict
        """Construct data for visualization and launch it."""

        with h5.h5_file_for_gid(view_model.datatype) as datatype_h5:
            # get data from coherence datatype h5, convert to json
            frequency = ABCDisplayer.dump_with_precision(
                datatype_h5.frequency.load().flat)
            array_data = datatype_h5.array_data[:]

        params = self.compute_raw_matrix_params(array_data)
        params.update(frequency=frequency)
        params.update(matrix_strides=json.dumps(
            [x / array_data.itemsize for x in array_data.strides]))
        return self.build_display_result("cross_coherence/view", params)
Example #21
0
    def _read_from_h5(self, entity_gid, method_name, datatype_kwargs='null', **kwargs):
        self.logger.debug("Starting to read HDF5: " + entity_gid + "/" + method_name + "/" + str(kwargs))

        datatype_kwargs = json.loads(datatype_kwargs)
        if datatype_kwargs:
            for key, value in six.iteritems(datatype_kwargs):
                kwargs[key] = load_entity_by_gid(value)

        with h5.h5_file_for_gid(entity_gid) as entity_h5:
            result = getattr(entity_h5, method_name)
            if kwargs:
                result = result(**kwargs)
            else:
                result = result()

        return result
Example #22
0
    def get_voxel_time_series(self, entity_gid, **kwargs):
        """
        Retrieve for a given voxel (x,y,z) the entire timeline.

        :param x: int coordinate
        :param y: int coordinate
        :param z: int coordinate

        :return: A complex dictionary with information about current voxel.
                The main part will be a vector with all the values over time from the x,y,z coordinates.
        """

        with h5.h5_file_for_gid(entity_gid) as ts_h5:
            if isinstance(ts_h5, TimeSeriesRegionH5):
                return self.prepare_view_region(ts_h5, **kwargs)

            data = ts_h5.get_voxel_time_series(**kwargs)
        return data
Example #23
0
    def launch(self, view_model):
        # type: (FourierSpectrumModel) -> dict

        self.log.debug("Plot started...")
        # these partial loads are dangerous for TS and FS instances, but efficient
        fourier_spectrum = FourierSpectrum()
        with h5.h5_file_for_gid(view_model.input_data) as input_h5:
            shape = list(input_h5.array_data.shape)
            fourier_spectrum.segment_length = input_h5.segment_length.load()
            fourier_spectrum.windowing_function = input_h5.windowing_function.load(
            )
            ts_index = self.load_entity_by_gid(input_h5.source.load())

        state_list = ts_index.get_labels_for_dimension(1)
        if len(state_list) == 0:
            state_list = list(range(shape[1]))
        fourier_spectrum.source = TimeSeries(
            sample_period=ts_index.sample_period)

        mode_list = list(range(shape[3]))
        available_scales = ["Linear", "Logarithmic"]

        params = dict(matrix_shape=json.dumps([shape[0], shape[2]]),
                      plotName=ts_index.title,
                      url_base=URLGenerator.build_h5_url(view_model.input_data,
                                                         "get_fourier_data",
                                                         parameter=""),
                      xAxisName="Frequency [kHz]",
                      yAxisName="Power",
                      available_scales=available_scales,
                      state_list=state_list,
                      mode_list=mode_list,
                      normalize_list=["no", "yes"],
                      normalize="no",
                      state_variable=state_list[0],
                      mode=mode_list[0],
                      xscale=available_scales[0],
                      yscale=available_scales[0],
                      x_values=json.dumps(fourier_spectrum.frequency[slice(
                          shape[0])].tolist()),
                      xmin=fourier_spectrum.freq_step,
                      xmax=fourier_spectrum.max_freq)
        return self.build_display_result("fourier_spectrum/view", params)
Example #24
0
    def get_grouped_space_labels(self, ts_h5):
        """
        :return: A structure of this form [('left', [(idx, lh_label)...]), ('right': [(idx, rh_label) ...])]
        """
        if isinstance(ts_h5, TimeSeriesSensorsH5):
            sensors_gid = ts_h5.sensors.load()
            with h5.h5_file_for_gid(sensors_gid) as sensors_h5:
                labels = sensors_h5.labels.load()
                # TODO uncomment this when the UI component will be able to scale for many groups
                # if isinstance(ts_h5, TimeSeriesSEEGH5):
                #     return SensorsInternal.group_sensors_to_electrodes(labels)
                return [('', list(enumerate(labels)))]

        if isinstance(ts_h5, TimeSeriesRegionH5):
            connectivity_gid = ts_h5.connectivity.load()
            conn = self.load_traited_by_gid(connectivity_gid)
            assert isinstance(conn, Connectivity)
            return conn.get_grouped_space_labels()

        return ts_h5.get_grouped_space_labels()
Example #25
0
    def prepare_stimuli_surface_from_view_model(self,
                                                view_model,
                                                load_full_surface=False):
        # type: (SurfaceStimulusCreatorModel, bool) -> StimuliSurface
        stimuli_surface = StimuliSurface()

        stimuli_surface.focal_points_triangles = view_model.focal_points_triangles
        stimuli_surface.spatial = view_model.spatial
        stimuli_surface.temporal = view_model.temporal

        if load_full_surface:
            stimuli_surface.surface = self.load_traited_by_gid(
                view_model.surface)
        else:
            stimuli_surface.surface = CorticalSurface()
            stimuli_surface.gid = view_model.surface
            # We need to load surface triangles on stimuli because focal_points_surface property needs to acces them
            with h5.h5_file_for_gid(view_model.surface) as surface_h5:
                stimuli_surface.surface.triangles = surface_h5.triangles.load()

        return stimuli_surface
Example #26
0
    def _params_meg_sensors(self,
                            meg_sensors,
                            projection_surface=None,
                            shell_surface=None):

        params = prepare_sensors_as_measure_points_params(meg_sensors)

        shell_surface = ensure_shell_surface(self.current_project_id,
                                             shell_surface)

        params.update({
            'shellObject':
            self.prepare_shell_surface_params(shell_surface,
                                              SurfaceURLGenerator),
            'urlVertices':
            '',
            'urlTriangles':
            '',
            'urlLines':
            '[]',
            'urlNormals':
            '',
            'boundaryURL':
            '',
            'urlRegionMap':
            ''
        })

        if projection_surface is not None:
            with h5.h5_file_for_gid(
                    projection_surface.gid) as projection_surface_h5:
                params.update(
                    self._compute_surface_params(projection_surface_h5))

        return self.build_display_result(
            "sensors/sensors_eeg",
            params,
            pages={"controlPage": "sensors/sensors_controls"})
Example #27
0
    def _params_eeg_sensors(self,
                            eeg_sensors,
                            eeg_cap=None,
                            shell_surface=None):

        if eeg_cap is None:
            eeg_cap = ensure_shell_surface(
                self.current_project_id, eeg_cap,
                SurfaceTypesEnum.EEG_CAP_SURFACE.value)

        params = prepare_mapped_sensors_as_measure_points_params(
            eeg_sensors, eeg_cap, self.stored_adapter.id)

        shell_surface = ensure_shell_surface(self.current_project_id,
                                             shell_surface)

        params.update({
            'shellObject':
            self.prepare_shell_surface_params(shell_surface,
                                              SurfaceURLGenerator),
            'urlVertices':
            '',
            'urlTriangles':
            '',
            'urlLines':
            '[]',
            'urlNormals':
            ''
        })

        if eeg_cap is not None:
            with h5.h5_file_for_gid(eeg_cap.gid) as eeg_cap_h5:
                params.update(self._compute_surface_params(eeg_cap_h5))

        return self.build_display_result(
            "sensors/sensors_eeg",
            params,
            pages={"controlPage": "sensors/sensors_controls"})
Example #28
0
    def launch(self, view_model):
        # type: (ConnectivityAnnotationsViewModel) -> dict

        annotations_index = self.load_entity_by_gid(
            view_model.annotations_index)

        if view_model.connectivity_index is None:
            connectivity_index = self.load_entity_by_gid(
                annotations_index.fk_connectivity_gid)
        else:
            connectivity_index = self.load_entity_by_gid(
                view_model.connectivity_index)

        if view_model.region_mapping_index is None:
            region_map = dao.get_generic_entity(RegionMappingIndex,
                                                connectivity_index.gid,
                                                'fk_connectivity_gid')
            if len(region_map) < 1:
                raise LaunchException(
                    "Can not launch this viewer unless we have at least a RegionMapping for the current Connectivity!"
                )
            region_mapping_index = region_map[0]
        else:
            region_mapping_index = self.load_entity_by_gid(
                view_model.region_mapping_index)

        boundary_url = SurfaceURLGenerator.get_url_for_region_boundaries(
            region_mapping_index.fk_surface_gid, region_mapping_index.gid,
            self.stored_adapter.id)

        surface_h5 = h5.h5_file_for_gid(region_mapping_index.fk_surface_gid)
        assert isinstance(surface_h5, SurfaceH5)
        url_vertices_pick, url_normals_pick, url_triangles_pick = SurfaceURLGenerator.get_urls_for_pick_rendering(
            surface_h5)
        url_vertices, url_normals, _, url_triangles, url_region_map = SurfaceURLGenerator.get_urls_for_rendering(
            surface_h5, region_mapping_index.gid)

        params = dict(title="Connectivity Annotations Visualizer",
                      annotationsTreeUrl=URLGenerator.build_url(
                          self.stored_adapter.id, 'tree_json',
                          view_model.annotations_index),
                      urlTriangleToRegion=URLGenerator.build_url(
                          self.stored_adapter.id, "get_triangles_mapping",
                          region_mapping_index.gid),
                      urlActivationPatterns=URLGenerator.paths2url(
                          view_model.annotations_index,
                          "get_activation_patterns"),
                      minValue=0,
                      maxValue=connectivity_index.number_of_regions - 1,
                      urlColors=json.dumps(url_region_map),
                      urlVerticesPick=json.dumps(url_vertices_pick),
                      urlTrianglesPick=json.dumps(url_triangles_pick),
                      urlNormalsPick=json.dumps(url_normals_pick),
                      brainCenter=json.dumps(surface_h5.center()),
                      urlVertices=json.dumps(url_vertices),
                      urlTriangles=json.dumps(url_triangles),
                      urlNormals=json.dumps(url_normals),
                      urlRegionBoundaries=boundary_url)

        return self.build_display_result(
            "annotations/annotations_view",
            params,
            pages={"controlPage": "annotations/annotations_controls"})