Ejemplo n.º 1
0
    def compute_parameters(input_data, colors=None, rays=None):
        """
        Having as inputs a Connectivity matrix(required) and two arrays that 
        represent the rays and colors of the nodes from the matrix(optional) 
        this method will build the required parameter dictionary that will be 
        sent to the HTML/JS 3D representation of the connectivity matrix.
        """
        if colors is not None:
            color_list = colors.array_data.tolist()
            color_list = ABCDisplayer.get_one_dimensional_list(
                color_list, input_data.number_of_regions,
                "Invalid input size for Sphere Colors")
            color_list = numpy.nan_to_num(
                numpy.array(color_list, dtype=numpy.float64)).tolist()
        else:
            color_list = [1.0] * input_data.number_of_regions

        if rays is not None:
            rays_list = rays.array_data.tolist()
            rays_list = ABCDisplayer.get_one_dimensional_list(
                rays_list, input_data.number_of_regions,
                "Invalid input size for Sphere Sizes")
            rays_list = numpy.nan_to_num(
                numpy.array(rays_list, dtype=numpy.float64)).tolist()
        else:
            rays_list = [1.0] * input_data.number_of_regions

        params = dict(raysArray=json.dumps(rays_list),
                      rayMin=min(rays_list),
                      rayMax=max(rays_list),
                      colorsArray=json.dumps(color_list),
                      colorMin=min(color_list),
                      colorMax=max(color_list))
        return params, {}
Ejemplo n.º 2
0
def prepare_mapped_sensors_as_measure_points_params(project_id, sensors, eeg_cap=None):
    """
    Compute sensors positions by mapping them to the ``eeg_cap`` surface
    If ``eeg_cap`` is not specified the mapping will use a default EEGCal DataType in current project.
    If no default EEGCap is found, return sensors as they are (not projected)

    :returns: dictionary to be used in Viewers for rendering measure_points
    :rtype: dict
    """

    if eeg_cap is None:
        eeg_cap = dao.try_load_last_entity_of_type(project_id, EEGCap)

    if eeg_cap:
        datatype_kwargs = json.dumps({'surface_to_map': eeg_cap.gid})
        sensor_locations = ABCDisplayer.paths2url(sensors, 'sensors_to_surface') + '/' + datatype_kwargs
        sensor_no = sensors.number_of_sensors
        sensor_labels = ABCDisplayer.paths2url(sensors, 'labels')

        return {'urlMeasurePoints': sensor_locations,
                'urlMeasurePointsLabels': sensor_labels,
                'noOfMeasurePoints': sensor_no,
                'minMeasure': 0,
                'maxMeasure': sensor_no,
                'urlMeasure': ''}

    return prepare_sensors_as_measure_points_params(sensors)
Ejemplo n.º 3
0
def prepare_mapped_sensors_as_measure_points_params(project_id,
                                                    sensors,
                                                    eeg_cap=None):
    """
    Compute sensors positions by mapping them to the ``eeg_cap`` surface
    If ``eeg_cap`` is not specified the mapping will use a default EEGCal DataType in current project.
    If no default EEGCap is found, return sensors as they are (not projected)

    :returns: dictionary to be used in Viewers for rendering measure_points
    :rtype: dict
    """

    if eeg_cap is None:
        eeg_cap = dao.get_values_of_datatype(project_id, EEGCap,
                                             page_size=1)[0]
        if eeg_cap:
            eeg_cap = ABCDisplayer.load_entity_by_gid(eeg_cap[-1][2])

    if eeg_cap:
        datatype_kwargs = json.dumps({'surface_to_map': eeg_cap.gid})
        sensor_locations = ABCDisplayer.paths2url(
            sensors, 'sensors_to_surface') + '/' + datatype_kwargs
        sensor_no = sensors.number_of_sensors
        sensor_labels = ABCDisplayer.paths2url(sensors, 'labels')

        return {
            'urlMeasurePoints': sensor_locations,
            'urlMeasurePointsLabels': sensor_labels,
            'noOfMeasurePoints': sensor_no,
            'minMeasure': 0,
            'maxMeasure': sensor_no,
            'urlMeasure': ''
        }

    return prepare_sensors_as_measure_points_params(sensors)
Ejemplo n.º 4
0
    def compute_parameters(input_data, colors=None, rays=None):
        """
        Having as inputs a Connectivity matrix(required) and two arrays that 
        represent the rays and colors of the nodes from the matrix(optional) 
        this method will build the required parameter dictionary that will be 
        sent to the HTML/JS 3D representation of the connectivity matrix.
        """
        if colors is not None:
            color_list = colors.array_data.tolist()
            color_list = ABCDisplayer.get_one_dimensional_list(color_list, input_data.number_of_regions,
                                                               "Invalid input size for Sphere Colors")
            color_list = numpy.nan_to_num(numpy.array(color_list, dtype=numpy.float64)).tolist()
        else:
            color_list = [1.0] * input_data.number_of_regions

        if rays is not None:
            rays_list = rays.array_data.tolist()
            rays_list = ABCDisplayer.get_one_dimensional_list(rays_list, input_data.number_of_regions,
                                                              "Invalid input size for Sphere Sizes")
            rays_list = numpy.nan_to_num(numpy.array(rays_list, dtype=numpy.float64)).tolist()
        else:
            rays_list = [1.0] * input_data.number_of_regions

        params = dict(raysArray=json.dumps(rays_list), rayMin=min(rays_list), rayMax=max(rays_list),
                      colorsArray=json.dumps(color_list), colorMin=min(color_list), colorMax=max(color_list))
        return params, {}
Ejemplo n.º 5
0
 def get_sensor_measure_points(sensors):
     """
         Returns urls from where to fetch the measure points and their labels
     """
     measure_points = ABCDisplayer.paths2url(sensors, 'locations')
     measure_points_no = sensors.number_of_sensors
     measure_points_labels = ABCDisplayer.paths2url(sensors, 'labels')
     return measure_points, measure_points_labels, measure_points_no
Ejemplo n.º 6
0
 def retrieve_measure_points(self, time_series):
     """
     To be overwritten method, for retrieving the measurement points (region centers, EEG sensors).
     """
     if isinstance(time_series, TimeSeriesSurface):
         return [], [], 0
     measure_points = ABCDisplayer.paths2url(time_series.connectivity, 'centres')
     measure_points_labels = ABCDisplayer.paths2url(time_series.connectivity, 'region_labels')
     measure_points_no = time_series.connectivity.number_of_regions
     return measure_points, measure_points_labels, measure_points_no
Ejemplo n.º 7
0
def prepare_sensors_as_measure_points_params(sensors):
    """
    Returns urls from where to fetch the measure points and their labels
    """
    sensor_locations = ABCDisplayer.paths2url(sensors, 'locations')
    sensor_no = sensors.number_of_sensors
    sensor_labels = ABCDisplayer.paths2url(sensors, 'labels')

    return {'urlMeasurePoints': sensor_locations,
            'urlMeasurePointsLabels': sensor_labels,
            'noOfMeasurePoints': sensor_no,
            'minMeasure': 0,
            'maxMeasure': sensor_no,
            'urlMeasure': ''}
Ejemplo n.º 8
0
def prepare_sensors_as_measure_points_params(sensors):
    """
    Returns urls from where to fetch the measure points and their labels
    """
    sensor_locations = ABCDisplayer.paths2url(sensors, 'locations')
    sensor_no = sensors.number_of_sensors
    sensor_labels = ABCDisplayer.paths2url(sensors, 'labels')

    return {
        'urlMeasurePoints': sensor_locations,
        'urlMeasurePointsLabels': sensor_labels,
        'noOfMeasurePoints': sensor_no,
        'minMeasure': 0,
        'maxMeasure': sensor_no,
        'urlMeasure': ''
    }
    def compute_params(self,
                       region_mapping_volume=None,
                       measure=None,
                       data_slice=''):

        region_mapping_volume = self._ensure_region_mapping(
            region_mapping_volume)

        volume = region_mapping_volume.volume
        volume_shape = region_mapping_volume.read_data_shape()
        volume_shape = (1, ) + volume_shape

        if measure is None:
            params = self._compute_region_volume_map_params(
                region_mapping_volume)
        else:
            params = self._compute_measure_params(region_mapping_volume,
                                                  measure, data_slice)

        url_voxel_region = ABCDisplayer.paths2url(region_mapping_volume,
                                                  "get_voxel_region",
                                                  parameter="")

        params.update(volumeShape=json.dumps(volume_shape),
                      volumeOrigin=json.dumps(volume.origin.tolist()),
                      voxelUnit=volume.voxel_unit,
                      voxelSize=json.dumps(volume.voxel_size.tolist()),
                      urlVoxelRegion=url_voxel_region)
        return params
Ejemplo n.º 10
0
    def launch(self, datatype):
        """Construct data for visualization and launch it."""

        matrix_shape = datatype.array_data.shape[0:2]
        parent_ts = datatype.source
        parent_ts = self.load_entity_by_gid(parent_ts.gid)
        labels = parent_ts.get_space_labels()
        state_list = parent_ts.labels_dimensions.get(
            parent_ts.labels_ordering[1], [])
        mode_list = range(parent_ts._length_4d)
        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=ABCDisplayer.paths2url(datatype,
                                                    "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)
Ejemplo n.º 11
0
    def compute_params(self, region_mapping_volume=None, measure=None, data_slice='', background=None):

        region_mapping_volume = self._ensure_region_mapping(region_mapping_volume)

        volume = region_mapping_volume.volume
        volume_shape = region_mapping_volume.read_data_shape()
        volume_shape = (1, ) + volume_shape

        if measure is None:
            params = self._compute_region_volume_map_params(region_mapping_volume)
        else:
            params = self._compute_measure_params(region_mapping_volume, measure, data_slice)

        url_voxel_region = ABCDisplayer.paths2url(region_mapping_volume, "get_voxel_region", parameter="")

        params.update(volumeShape=json.dumps(volume_shape),
                      volumeOrigin=json.dumps(volume.origin.tolist()),
                      voxelUnit=volume.voxel_unit,
                      voxelSize=json.dumps(volume.voxel_size.tolist()),
                      urlVoxelRegion=url_voxel_region)

        if background is None:
            background = dao.try_load_last_entity_of_type(self.current_project_id, StructuralMRI)

        params.update(self._compute_background(background))
        return params
Ejemplo n.º 12
0
    def launch(self, view_model):
        # type: (TopographicViewerModel) -> dict

        connectivities_idx = []
        measures_ht = []
        for measure in [view_model.data_0, view_model.data_1, view_model.data_2]:
            if measure is not None:
                measure_index = self.load_entity_by_gid(measure)
                measures_ht.append(h5.load_from_index(measure_index))
                conn_index = self.load_entity_by_gid(measure_index.fk_connectivity_gid)
                connectivities_idx.append(conn_index)

        with h5.h5_file_for_index(connectivities_idx[0]) as conn_h5:
            centres = conn_h5.centres.load()
        sensor_locations = TopographyCalculations.normalize_sensors(centres)
        sensor_number = len(sensor_locations)

        arrays = []
        titles = []
        min_vals = []
        max_vals = []
        data_array = []
        data_arrays = []
        for i, measure in enumerate(measures_ht):
            if connectivities_idx[i].number_of_regions != sensor_number:
                raise Exception("Use the same connectivity!!!")
            arrays.append(measure.array_data.tolist())
            titles.append(measure.title)
            min_vals.append(measure.array_data.min())
            max_vals.append(measure.array_data.max())

        color_bar_min = min(min_vals)
        color_bar_max = max(max_vals)

        for i, array_data in enumerate(arrays):
            try:
                data_array = TopographyCalculations.compute_topography_data(array_data, sensor_locations)

                # We always access the first element because only one connectivity can be used at one time
                first_label = h5.load_from_index(connectivities_idx[0]).hemispheres[0]
                if first_label:
                    data_array = numpy.rot90(data_array, k=1, axes=(0, 1))
                else:
                    data_array = numpy.rot90(data_array, k=-1, axes=(0, 1))
                if numpy.any(numpy.isnan(array_data)):
                    titles[i] = titles[i] + " - Topography contains nan"
                if not numpy.any(array_data):
                    titles[i] = titles[i] + " - Topography data is all zeros"
                data_arrays.append(ABCDisplayer.dump_with_precision(data_array.flat))
            except KeyError as err:
                self.log.exception(err)
                raise LaunchException("The measure points location is not compatible with this viewer ", err)

        params = dict(matrix_datas=data_arrays,
                      matrix_shape=json.dumps(data_array.squeeze().shape),
                      titles=titles,
                      vmin=color_bar_min,
                      vmax=color_bar_max)
        return self.build_display_result("topographic/view", params,
                                         pages={"controlPage": "topographic/controls"})
Ejemplo n.º 13
0
    def launch(self, background=None):
        volume = background.volume
        volume_shape = background.read_data_shape()
        volume_shape = (1, ) + volume_shape

        min_value, max_value = background.get_min_max_values()
        url_volume_data = ABCDisplayer.paths2url(background,
                                                 'get_volume_view',
                                                 parameter='')

        params = dict(title="MRI Volume visualizer",
                      minValue=min_value,
                      maxValue=max_value,
                      urlVolumeData=url_volume_data,
                      volumeShape=json.dumps(volume_shape),
                      volumeOrigin=json.dumps(volume.origin.tolist()),
                      voxelUnit=volume.voxel_unit,
                      voxelSize=json.dumps(volume.voxel_size.tolist()),
                      urlVoxelRegion='',
                      minBackgroundValue=min_value,
                      maxBackgroundValue=max_value,
                      urlBackgroundVolumeData='')

        return self.build_display_result(
            "time_series_volume/staticView",
            params,
            pages=dict(controlPage="time_series_volume/controls"))
Ejemplo n.º 14
0
    def launch(self, **kwargs):
        self.log.debug("Plot started...")
        input_data = kwargs['input_data']
        shape = list(input_data.read_data_shape())
        state_list = input_data.source.labels_dimensions.get(input_data.source.labels_ordering[1], [])
        mode_list = range(shape[3])
        available_scales = ["Linear", "Logarithmic"]

        params = dict(matrix_shape=json.dumps([shape[0], shape[2]]),
                      plotName=input_data.source.type,
                      url_base=ABCDisplayer.paths2url(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(input_data.frequency[slice(shape[0])].tolist()),
                      xmin=input_data.freq_step,
                      xmax=input_data.max_freq)
        return self.build_display_result("fourier_spectrum/view", params)
Ejemplo n.º 15
0
    def get_metric_matrix(self, datatype_group, selected_metric=None):
        self.model = PseIsoModel.from_db(datatype_group.fk_operation_group)
        if selected_metric is None:
            selected_metric = self.model.metrics.keys()[0]

        data_matrix = self.model.apriori_data[selected_metric]
        data_matrix = numpy.rot90(data_matrix)
        data_matrix = numpy.flipud(data_matrix)
        matrix_data = ABCDisplayer.dump_with_precision(data_matrix.flat)
        matrix_guids = self.model.datatypes_gids
        matrix_guids = numpy.rot90(matrix_guids)
        matrix_shape = json.dumps(data_matrix.squeeze().shape)
        x_min = self.model.apriori_x[0]
        x_max = self.model.apriori_x[self.model.apriori_x.size - 1]
        y_min = self.model.apriori_y[0]
        y_max = self.model.apriori_y[self.model.apriori_y.size - 1]
        vmin = data_matrix.min()
        vmax = data_matrix.max()
        return dict(matrix_data=matrix_data,
                    matrix_guids=json.dumps(matrix_guids.flatten().tolist()),
                    matrix_shape=matrix_shape,
                    color_metric=selected_metric,
                    x_min=x_min,
                    x_max=x_max,
                    y_min=y_min,
                    y_max=y_max,
                    vmin=vmin,
                    vmax=vmax)
Ejemplo n.º 16
0
    def get_metric_matrix(self, datatype_group_gid, selected_metric=None):
        pse_iso = PSEIsoGroupModel(datatype_group_gid)

        if selected_metric is None:
            selected_metric = list(pse_iso.get_available_metric_keys())[0]

        data_matrix = pse_iso.apriori_data[selected_metric]
        data_matrix = numpy.rot90(data_matrix)
        data_matrix = numpy.flipud(data_matrix)
        vmin = numpy.nanmin(data_matrix)
        vmax = numpy.nanmax(data_matrix)
        # TODO: We replace NaN values here. To be addressed by task TVB-2660.
        data_matrix[numpy.isnan(data_matrix)] = vmin - 1
        matrix_data = ABCDisplayer.dump_with_precision(data_matrix.flat)
        matrix_guids = pse_iso.datatypes_gids
        matrix_guids = numpy.rot90(matrix_guids)
        matrix_shape = json.dumps(data_matrix.squeeze().shape)
        x_min = pse_iso.apriori_x[0]
        x_max = pse_iso.apriori_x[-1]
        y_min = pse_iso.apriori_y[0]
        y_max = pse_iso.apriori_y[-1]
        return dict(matrix_data=matrix_data,
                    matrix_guids=json.dumps(matrix_guids.flatten().tolist()),
                    matrix_shape=matrix_shape,
                    color_metric=selected_metric,
                    xAxisName=pse_iso.get_range1_key(),
                    yAxisName=pse_iso.get_range2_key(),
                    available_metrics=pse_iso.get_available_metric_keys(),
                    x_min=x_min,
                    x_max=x_max,
                    y_min=y_min,
                    y_max=y_max,
                    vmin=vmin,
                    vmax=vmax)
Ejemplo n.º 17
0
    def get_metric_matrix(self, datatype_group, selected_metric=None):
        self.model = PseIsoModel.from_db(datatype_group.fk_operation_group)
        if selected_metric is None:
            selected_metric = list(self.model.metrics)[0]

        data_matrix = self.model.apriori_data[selected_metric]
        data_matrix = numpy.rot90(data_matrix)
        data_matrix = numpy.flipud(data_matrix)
        matrix_data = ABCDisplayer.dump_with_precision(data_matrix.flat)
        matrix_guids = self.model.datatypes_gids
        matrix_guids = numpy.rot90(matrix_guids)
        matrix_shape = json.dumps(data_matrix.squeeze().shape)
        x_min = self.model.apriori_x[0]
        x_max = self.model.apriori_x[self.model.apriori_x.size - 1]
        y_min = self.model.apriori_y[0]
        y_max = self.model.apriori_y[self.model.apriori_y.size - 1]
        vmin = data_matrix.min()
        vmax = data_matrix.max()
        return dict(matrix_data=matrix_data,
                    matrix_guids=json.dumps(matrix_guids.flatten().tolist()),
                    matrix_shape=matrix_shape,
                    color_metric=selected_metric,
                    x_min=x_min,
                    x_max=x_max,
                    y_min=y_min,
                    y_max=y_max,
                    vmin=vmin,
                    vmax=vmax)
Ejemplo n.º 18
0
    def compute_raw_matrix_params(matrix):
        """
        Serializes matrix data, shape and stride metadata to json
        """
        matrix_data = ABCDisplayer.dump_with_precision(matrix.flat)
        matrix_shape = json.dumps(matrix.shape)

        return dict(matrix_data=matrix_data, matrix_shape=matrix_shape)
Ejemplo n.º 19
0
    def retrieve_measure_points_prams(self, time_series):
        """
        To be overwritten method, for retrieving the measurement points (region centers, EEG sensors).
        """
        if self.connectivity is None:
            self.measure_points_no = 0
            return {'urlMeasurePoints': [],
                    'urlMeasurePointsLabels': [],
                    'noOfMeasurePoints': 0}

        measure_points = ABCDisplayer.paths2url(self.connectivity, 'centres')
        measure_points_labels = ABCDisplayer.paths2url(self.connectivity, 'region_labels')
        self.measure_points_no = self.connectivity.number_of_regions

        return {'urlMeasurePoints': measure_points,
                'urlMeasurePointsLabels': measure_points_labels,
                'noOfMeasurePoints': self.measure_points_no}
    def launch(self, connectivity):
        """Construct data for visualization and launch it."""

        pars = {"labels": json.dumps(connectivity.region_labels.tolist()),
                "url_base": ABCDisplayer.paths2url(connectivity, attribute_name="weights", flatten="True")
                }

        return self.build_display_result("connectivity_edge_bundle/view", pars)
Ejemplo n.º 21
0
 def _compute_background(background):
     if background is not None:
         min_value, max_value = background.get_min_max_values()
         url_volume_data = ABCDisplayer.paths2url(background, 'get_volume_view', parameter='')
     else:
         min_value, max_value = 0, 0
         url_volume_data = None
     return dict( minBackgroundValue=min_value, maxBackgroundValue=max_value,
                  urlBackgroundVolumeData = url_volume_data )
Ejemplo n.º 22
0
    def compute_raw_matrix_params(matrix):
        """
        Serializes matrix data, shape and stride metadata to json
        """
        matrix_data = ABCDisplayer.dump_with_precision(matrix.flat)
        matrix_shape = json.dumps(matrix.shape)

        return dict(matrix_data=matrix_data,
                    matrix_shape=matrix_shape)
    def launch(self, datatype):
        """Construct data for visualization and launch it."""

        # get data from coher datatype, convert to json
        frequency = ABCDisplayer.dump_with_precision(datatype.get_data('frequency').flat)
        array_data = datatype.get_data('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)
Ejemplo n.º 24
0
    def get_shell_surface_urls(shell_surface=None, project_id=0):

        if shell_surface is None:
            shell_surface = dao.get_values_of_datatype(project_id, FaceSurface)[0]

            if not shell_surface:
                raise Exception('No face object found in database.')

            shell_surface = ABCDisplayer.load_entity_by_gid(shell_surface[0][2])

        face_vertices, face_normals, _, face_triangles = shell_surface.get_urls_for_rendering()
        return json.dumps([face_vertices, face_normals, face_triangles])
Ejemplo n.º 25
0
    def compute_sensor_surfacemapped_measure_points(project_id, sensors, eeg_cap=None):
        """
        Compute sensors positions by mapping them to the ``eeg_cap`` surface
        If ``eeg_cap`` is not specified the mapping will use a default.
        It returns a url from where to fetch the positions
        If no default is available it returns None
        :returns: measure points, measure points labels, measure points number
        :rtype: tuple
        """

        if eeg_cap is None:
            eeg_cap = dao.get_values_of_datatype(project_id, EEGCap)[0]
            if eeg_cap:
                eeg_cap = ABCDisplayer.load_entity_by_gid(eeg_cap[-1][2])

        if eeg_cap:
            datatype_kwargs = json.dumps({'surface_to_map': eeg_cap.gid})
            measure_points = ABCDisplayer.paths2url(sensors, 'sensors_to_surface') + '/' + datatype_kwargs
            measure_points_no = sensors.number_of_sensors
            measure_points_labels = ABCDisplayer.paths2url(sensors, 'labels')
            return measure_points, measure_points_labels, measure_points_no
Ejemplo n.º 26
0
    def launch(self, view_model):
        # type: (WaveletSpectrogramVisualizerModel) -> dict

        input_index = self.load_entity_by_gid(view_model.input_data.hex)
        with h5.h5_file_for_index(input_index) as input_h5:
            shape = input_h5.array_data.shape
            input_sample_period = input_h5.sample_period.load()
            input_frequencies = input_h5.frequencies.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)

        ts_index = self.load_entity_by_gid(input_index.fk_source_gid)
        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"})
Ejemplo n.º 27
0
    def launch(self, connectivity):
        """Construct data for visualization and launch it."""

        pars = {
            "labels":
            json.dumps(connectivity.region_labels.tolist()),
            "url_base":
            ABCDisplayer.paths2url(connectivity,
                                   attribute_name="weights",
                                   flatten="True")
        }

        return self.build_display_result("connectivity_edge_bundle/view", pars)
Ejemplo n.º 28
0
    def launch(self, datatype):
        """Construct data for visualization and launch it."""

        # get data from coher datatype, convert to json
        frequency = ABCDisplayer.dump_with_precision(
            datatype.get_data('frequency').flat)
        array_data = datatype.get_data('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)
Ejemplo n.º 29
0
    def launch(self, datatype):
        """Construct data for visualization and launch it."""

        datatype_h5_class, datatype_h5_path = self._load_h5_of_gid(datatype.gid)
        with datatype_h5_class(datatype_h5_path) as datatype_h5:
            # get data from coher 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)
Ejemplo n.º 30
0
    def launch(self, data_0, data_1=None, data_2=None):

        connectivity = data_0.connectivity
        sensor_locations = TopographyCalculations.normalize_sensors(
            connectivity.centres)
        sensor_number = len(sensor_locations)

        arrays = []
        titles = []
        min_vals = []
        max_vals = []
        data_array = []
        data_arrays = []
        for measure in [data_0, data_1, data_2]:
            if measure is not None:
                if len(measure.connectivity.centres) != sensor_number:
                    raise Exception("Use the same connectivity!!!")
                arrays.append(measure.array_data.tolist())
                titles.append(measure.title)
                min_vals.append(measure.array_data.min())
                max_vals.append(measure.array_data.max())

        color_bar_min = min(min_vals)
        color_bar_max = max(max_vals)

        for i, array_data in enumerate(arrays):
            try:
                data_array = TopographyCalculations.compute_topography_data(
                    array_data, sensor_locations)
                if numpy.any(numpy.isnan(array_data)):
                    titles[i] = titles[i] + " - Topography contains nan"
                if not numpy.any(array_data):
                    titles[i] = titles[i] + " - Topography data is all zeros"
                data_arrays.append(
                    ABCDisplayer.dump_with_precision(data_array.flat))
            except KeyError as err:
                self.log.exception(err)
                raise LaunchException(
                    "The measure points location is not compatible with this viewer ",
                    err)

        params = dict(matrix_datas=data_arrays,
                      matrix_shape=json.dumps(data_array.squeeze().shape),
                      titles=titles,
                      vmin=color_bar_min,
                      vmax=color_bar_max)
        return self.build_display_result(
            "topographic/view",
            params,
            pages={"controlPage": "topographic/controls"})
Ejemplo n.º 31
0
def prepare_shell_surface_urls(project_id, shell_surface=None):

    if shell_surface is None:
        shell_surface = dao.get_values_of_datatype(project_id,
                                                   FaceSurface,
                                                   page_size=1)[0]

        if not shell_surface:
            raise Exception('No Face object found in current project.')

        shell_surface = ABCDisplayer.load_entity_by_gid(shell_surface[0][2])

    face_vertices, face_normals, _, face_triangles = shell_surface.get_urls_for_rendering(
    )
    return json.dumps([face_vertices, face_normals, face_triangles])
Ejemplo n.º 32
0
    def launch(self, view_model):
        # type: (CrossCoherenceVisualizerModel) -> dict
        """Construct data for visualization and launch it."""

        coherence_gid = view_model.datatype
        coherence_index = self.load_entity_by_gid(coherence_gid)
        with h5.h5_file_for_index(coherence_index) 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)
Ejemplo n.º 33
0
    def _compute_measure_params(self, region_mapping_volume, measure, data_slice):
        # prepare the url that will project the measure onto the region volume map
        metadata = measure.get_metadata('array_data')
        min_value, max_value = metadata[measure.METADATA_ARRAY_MIN], metadata[measure.METADATA_ARRAY_MAX]
        measure_shape = measure.get_data_shape('array_data')
        if not data_slice:
            data_slice = self.get_default_slice(measure_shape, region_mapping_volume.connectivity.number_of_regions)
            data_slice = slice_str(data_slice)
        datatype_kwargs = json.dumps({'mapped_array': measure.gid})
        url_volume_data = ABCDisplayer.paths2url(region_mapping_volume, "get_mapped_array_volume_view")
        url_volume_data += '/' + datatype_kwargs + '?mapped_array_slice=' + data_slice + ';'

        return dict(  minValue=min_value, maxValue=max_value,
                      urlVolumeData=url_volume_data,
                      measureShape=slice_str(measure_shape),
                      measureSlice=data_slice)
Ejemplo n.º 34
0
 def _prepare_colors(self, colors, expected_size, step=None):
     """
     From the input array, all values smaller than step will get a different color
     """
     if colors is None:
         return [self.DEFAULT_COLOR] * expected_size, None
     colors = numpy.nan_to_num(numpy.array(colors.array_data, dtype=numpy.float64)).tolist()
     colors = ABCDisplayer.get_one_dimensional_list(colors, expected_size, "Invalid size for colors array!")
     result = []
     if step is None:
         step = (max(colors) + min(colors)) / 2
     for val in colors:
         if val < step:
             result.append(self.OTHER_COLOR)
         else:
             result.append(self.DEFAULT_COLOR)
     return result, step
    def launch(self, input_data, **kwargs):
        """
        Draw interactive display.
        """
        self.log.debug("Plot started...")

        params = dict(plotName=input_data.source.type,
                      xAxisName="Frequency [kHz]",
                      yAxisName="CohSpec",
                      available_xScale=["Linear", "Logarithmic"],
                      available_spectrum=json.dumps(input_data.spectrum_types),
                      spectrum_list=input_data.spectrum_types,
                      xscale="Linear",
                      spectrum=input_data.spectrum_types[0],
                      url_base=ABCDisplayer.paths2url(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)
Ejemplo n.º 36
0
    def launch(self, data_0, data_1=None, data_2=None):

        connectivity = data_0.connectivity
        sensor_locations = TopographyCalculations.normalize_sensors(connectivity.centres)
        sensor_number = len(sensor_locations)

        arrays = []
        titles = []
        min_vals = []
        max_vals = []
        data_array = []
        data_arrays = []
        for measure in [data_0, data_1, data_2]:
            if measure is not None:
                if len(measure.connectivity.centres) != sensor_number:
                    raise Exception("Use the same connectivity!!!")
                arrays.append(measure.array_data.tolist())
                titles.append(measure.title)
                min_vals.append(measure.array_data.min())
                max_vals.append(measure.array_data.max())

        color_bar_min = min(min_vals)
        color_bar_max = max(max_vals)

        for i, array_data in enumerate(arrays):
            try:
                data_array = TopographyCalculations.compute_topography_data(array_data, sensor_locations)
                if numpy.any(numpy.isnan(array_data)):
                    titles[i] = titles[i] + " - Topography contains nan"
                if not numpy.any(array_data):
                    titles[i] = titles[i] + " - Topography data is all zeros"
                data_arrays.append(ABCDisplayer.dump_with_precision(data_array.flat))
            except KeyError as err:
                self.log.exception(err)
                raise LaunchException("The measure points location is not compatible with this viewer ", err)

        params = dict(matrix_datas=data_arrays,
                      matrix_shape=json.dumps(data_array.squeeze().shape),
                      titles=titles,
                      vmin=color_bar_min,
                      vmax=color_bar_max)
        return self.build_display_result("topographic/view", params,
                                         pages={"controlPage": "topographic/controls"})
Ejemplo n.º 37
0
    def launch(self, input_data, **kwarg):
        shape = input_data.read_data_shape()
        start_time = input_data.source.start_time
        wavelet_sample_period = input_data.source.sample_period * \
                                max((1, int(input_data.sample_period / input_data.source.sample_period)))
        end_time = input_data.source.start_time + (wavelet_sample_period *
                                                   shape[1])
        if len(input_data.frequencies):
            freq_lo = input_data.frequencies[0]
            freq_hi = input_data.frequencies[-1]
        else:
            freq_lo = 0
            freq_hi = 1
        slices = (slice(shape[0]), slice(shape[1]), slice(0, 1, None),
                  slice(0, shape[3], None), slice(0, 1, None))

        data_matrix = input_data.get_data('power', slices)
        data_matrix = data_matrix.sum(axis=3)

        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: " + input_data.source.type,
            xAxisName="Time (%s)" % str(input_data.source.sample_period_unit),
            yAxisName="Frequency (%s)" % str("kHz"),
            title=self._ui_name,
            matrix_data=matrix_data,
            matrix_shape=matrix_shape,
            start_time=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"})
    def launch(self, input_data, **kwarg):
        shape = input_data.read_data_shape()
        start_time = input_data.source.start_time
        wavelet_sample_period = input_data.source.sample_period * \
                                max((1, int(input_data.sample_period / input_data.source.sample_period)))
        end_time = input_data.source.start_time + (wavelet_sample_period * shape[1])
        if len(input_data.frequencies):
            freq_lo = input_data.frequencies[0]
            freq_hi = input_data.frequencies[-1]
        else:
            freq_lo = 0
            freq_hi = 1
        slices = (slice(shape[0]),
                  slice(shape[1]),
                  slice(0, 1, None),
                  slice(0, shape[3], None),
                  slice(0, 1, None))

        data_matrix = input_data.get_data('power', slices)
        data_matrix = data_matrix.sum(axis=3)

        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: " + input_data.source.type,
                      xAxisName="Time (%s)" % str(input_data.source.sample_period_unit),
                      yAxisName="Frequency (%s)" % str("kHz"),
                      title=self._ui_name,
                      matrix_data=matrix_data,
                      matrix_shape=matrix_shape,
                      start_time=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"})
    def launch(self, background=None):
        volume = background.volume
        volume_shape = background.read_data_shape()
        volume_shape = (1,) + volume_shape

        min_value, max_value = background.get_min_max_values()
        url_volume_data = ABCDisplayer.paths2url(background, 'get_volume_view', parameter='')

        params = dict(title="MRI Volume visualizer",
                      minValue=min_value, maxValue=max_value,
                      urlVolumeData=url_volume_data,
                      volumeShape=json.dumps(volume_shape),
                      volumeOrigin=json.dumps(volume.origin.tolist()),
                      voxelUnit=volume.voxel_unit,
                      voxelSize=json.dumps(volume.voxel_size.tolist()),
                      urlVoxelRegion='',
                      minBackgroundValue=min_value, maxBackgroundValue=max_value,
                      urlBackgroundVolumeData='')

        return self.build_display_result("time_series_volume/staticView", params,
                                         pages=dict(controlPage="time_series_volume/controls"))
    def compute_params(self, region_mapping_volume=None, measure=None, data_slice=''):

        region_mapping_volume = self._ensure_region_mapping(region_mapping_volume)

        volume = region_mapping_volume.volume
        volume_shape = region_mapping_volume.read_data_shape()
        volume_shape = (1, ) + volume_shape

        if measure is None:
            params = self._compute_region_volume_map_params(region_mapping_volume)
        else:
            params = self._compute_measure_params(region_mapping_volume, measure, data_slice)

        url_voxel_region = ABCDisplayer.paths2url(region_mapping_volume, "get_voxel_region", parameter="")

        params.update(volumeShape=json.dumps(volume_shape),
                      volumeOrigin=json.dumps(volume.origin.tolist()),
                      voxelUnit=volume.voxel_unit,
                      voxelSize=json.dumps(volume.voxel_size.tolist()),
                      urlVoxelRegion=url_voxel_region)
        return params
Ejemplo n.º 41
0
 def _normalize_rays(self, rays, expected_size):
     """
     Make sure all rays are in the interval [self.MIN_RAY, self.MAX_RAY]
     """
     if rays is None:
         value = (self.MAX_RAY + self.MIN_RAY) / 2
         return [value] * expected_size, 0.0, 0.0
     rays = rays.array_data.tolist()
     rays = ABCDisplayer.get_one_dimensional_list(rays, expected_size, "Invalid size for rays array.")
     min_x = min(rays)
     max_x = max(rays)
     if min_x >= self.MIN_RAY and max_x <= self.MAX_RAY:
         # No need to normalize
         return rays, min_x, max_x
     result = []
     diff = max_x - min_x
     if min_x == max_x:
         diff = self.MAX_RAY - self.MIN_RAY
     for ray in rays:
         result.append(self.MIN_RAY + self.MAX_RAY * (ray - min_x) / diff)
     result = numpy.nan_to_num(numpy.array(result, dtype=numpy.float64)).tolist()
     return result, min(rays), max(rays)
    def launch(self, input_data, **kwargs):
        """
        Draw interactive display.
        """
        self.log.debug("Plot started...")

        params = dict(
            plotName=input_data.source.type,
            xAxisName="Frequency [kHz]",
            yAxisName="CohSpec",
            available_xScale=["Linear", "Logarithmic"],
            available_spectrum=json.dumps(input_data.spectrum_types),
            spectrum_list=input_data.spectrum_types,
            xscale="Linear",
            spectrum=input_data.spectrum_types[0],
            url_base=ABCDisplayer.paths2url(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)
Ejemplo n.º 43
0
 def __init__(self):
     ABCDisplayer.__init__(self)
Ejemplo n.º 44
0
 def __init__(self):
     ABCDisplayer.__init__(self)
     self.interp_models = {}
     self.nan_indices = {}
 def __init__(self):
     ABCDisplayer.__init__(self)
Ejemplo n.º 46
0
 def __init__(self):
     ABCDisplayer.__init__(self)
     self.interp_models = {}
     self.nan_indices = {}