Ejemplo n.º 1
0
    def UpdateGradient(self, gradient_type):
        self.gradient_color = GradientColor(gradient_type)
        # update color schema
        self.color_schema_dict["Density Map"] = GradientColorSchema(
            gradient_type)

        self.color_band = gradient_type
        self.grid_to_buffer()
        self.isResizing = True
        self.reInitBuffer = True

        return self.color_schema_dict["Density Map"]
Ejemplo n.º 2
0
    def __init__(self, parent, layer, data, **kwargs):
        PlottingCanvas.__init__(self, parent, data)

        try:
            self.layer_name = layer.name
            self.title = "Transition probility matrix (%s)" % self.layer_name
            self.x_label = "LISA transition states (1=HH,2=LH,3=LL,4=HL)"
            self.y_label = "LISA transition states"
            self.data = data
            n = len(self.data)
            self.enable_axis_labels = False
            self.enable_axis = True
            self.enable_axis_x = False
            self.enable_axis_y = False

            # a NxN matrix
            self.x_min = 1
            self.x_max = n + 1
            self.y_min = 1
            self.y_max = n + 1

            self.extent = (self.x_min, self.y_min, self.x_max, self.y_max)
            self.selected_polygon_ids = []
            self.status_bar = self.parentFrame.status_bar

            self.gradient_color = GradientColor(gradient_type='rdyibu')
            self.margin_right = 100

            # color schema: from blue to red
            self.color_matrix = []
            for i in range(n):
                color_row = []
                for j in range(n):
                    p = self.data[i][j]
                    color_row.append(self.gradient_color.get_color_at(p))
                self.color_matrix.append(color_row)

        except Exception as err:
            self.ShowMsgBox('Fail to init heat map! ' + str(err.message))
            self.isValidPlot = False
            self.parentFrame.Close(True)
            return None
Ejemplo n.º 3
0
    def compute_densityMap(cls, input, output):
        """
        The function will be executed in each process.
        """
        while True:
            args = input.get()
            method = args['method']
            id = args['id']

            if method == 'compute':
                # for computing KDE for each cell in grid
                points = args['data']
                kernel = args['kernel']
                bandwidth = args['bandwidth']
                cellSize = args['cell_size']
                grid_left = args['grid_left']
                grid_lower = args['grid_lower']
                grid_upper = args['grid_upper']
                rows, cols = args['rows'], args['cols']

                invert = False
                radius = bandwidth / cellSize
                tmpGrid = np.zeros((rows, cols))

                #print '%s:%s'%(os.getpid(),args.keys())

                for pt in points:
                    X, Y = pt
                    float_i = (Y - grid_lower) / cellSize
                    #float_i = (grid_upper -Y) / cellSize
                    i = int(floor(float_i - radius))
                    i = i if i >= 0 else 0
                    I = int(floor(float_i + radius))
                    I = I if I < rows else rows - 1

                    float_j = (X - grid_left) / cellSize
                    j = int(floor(float_j - radius))
                    j = j if j >= 0 else 0
                    J = int(floor(float_j + radius))
                    J = J if J < cols else cols - 1

                    for row in xrange(i, I + 1):
                        for col in xrange(j, J + 1):
                            x = grid_left + (col * cellSize)
                            y = grid_lower + (row * cellSize)
                            d = ((x - X)**2 + (y - Y)**2)**(0.5)
                            if d <= bandwidth:
                                z = d / bandwidth
                                if invert:
                                    tmpGrid[row, col] -= kernel(z)
                                else:
                                    tmpGrid[row, col] += kernel(z)

                output.put({
                    'id': id,
                    'grid': tmpGrid,
                    'grid_max': np.max(tmpGrid)
                })

            elif method == 'create':
                grid = args['grid']
                grid_max = args['grid_max']
                opaque = args['opaque']
                color_band = args['color_band']

                gradient_color = GradientColor(color_band)

                # make Byte Array for bmp
                rows, cols = grid.shape
                arr = np.zeros((rows, cols, 4), np.uint8)
                R, G, B, A = range(4)

                # flip from real model coords to screen coords
                raster = grid
                raster = raster[::-1]
                raster_min, raster_max = raster.min(), grid_max  #raster.max()
                raster_val_range = raster_max - raster_min
                if raster_val_range > 0:
                    raster_scaled = (raster - raster_min) / (raster_max -
                                                             raster_min)
                else:
                    raster_scaled = raster

                # tranfer 0~1 value to 0~255 pixel values,
                red_matrix, blue_matrix, green_matrix, opaque_matrix = \
                          np.zeros((rows,cols)),\
                          np.zeros((rows, cols)), \
                          np.zeros((rows,cols)), \
                          np.ones((rows,cols))*opaque* (255/100.0) # opaque ranges (0,100)

                for i, row in enumerate(raster_scaled):
                    for j, item in enumerate(row):
                        clr = gradient_color.get_color_at(item)

                        red_matrix[i][j] = clr.red
                        green_matrix[i][j] = clr.green
                        blue_matrix[i][j] = clr.blue
                        if item < 0.15:
                            opaque_matrix[i][j] = 0

                arr[:, :, R] = (red_matrix).astype("B")
                arr[:, :, G] = (green_matrix).astype("B")
                arr[:, :, B] = (blue_matrix).astype("B")
                arr[:, :, A] = (opaque_matrix).astype("B")  #self.opaque #alpha

                output.put({'id': id, 'data': arr})
Ejemplo n.º 4
0
    def __init__(self, parent, layers, **kwargs):
        ShapeMap.__init__(self, parent, layers)

        try:
            self.point_layer = self.layers[0]
            #self.bg_layer     = kwargs["background"]
            self.cell_size = kwargs["cell_size"]
            self.bandwidth = kwargs["bandwidth"]
            self.kernel = kwargs["kernel"]
            self.color_band = kwargs["color_band"]
            self.opaque = kwargs["opaque"]
            self.bufferWidth, self.bufferHeight = kwargs["size"]
            self.points = self.point_layer.shape_objects
            self.extent = self.point_layer.extent
            self.view = View2ScreenTransform(self.extent, self.bufferWidth,
                                             self.bufferHeight)

            if kwargs.has_key("query_points"):
                self.query_points = kwargs["query_points"]
            else:
                self.query_points = range(len(self.points))
            """
            if self.bg_layer: 
                self.layers.append(self.bg_layer)
            """

            if len(self.query_points) < len(self.points):
                id_group = [self.query_points]
                color_group = [
                    self.color_schema_dict[self.point_layer.name].colors[0]
                ]
                edge_color_group = [
                    self.color_schema_dict[self.point_layer.name].edge_color
                ]
                """
                non_query_points = list(set(range(len(self.points))) - set(self.query_points))
                id_group.append(non_query_points)
                color_group.append(wx.Colour(255,255,255,0))
                edge_color_group.append(wx.Colour(255,255,255,0))
                """
                self.draw_layers[self.point_layer].set_data_group(id_group)
                self.draw_layers[self.point_layer].set_fill_color_group(
                    color_group)
                self.draw_layers[self.point_layer].set_edge_color_group(
                    edge_color_group)

            # setup gradient color
            self.gradient_color = GradientColor(self.color_band)
            # for tree node
            self.color_schema_dict["Density Map"] = GradientColorSchema(
                self.color_band)
            self.isHideDensityMap = False
            # for export gif
            self.img_array_rgb = None

            self.isResizing = False
            self.cells_Updated = False
            self.bmp = None

            self.setup_densityMap()
            self.createDensityMap()

            # dummy Layer for density map
            self.layer_seq_list = []
            self.layer_seq_list.insert(0, "Density Map")
            self.layer_name_list.insert(0, "Density Map")

        except Exception as err:
            self.ShowMsgBox(
                """Density map could not be created. Please choose/input valid parameters.
            
Details: """ + str(err.message))
            self.UnRegister()
            self.parentFrame.Close(True)
            return None
Ejemplo n.º 5
0
    def __init__(self, gradient_type):
        self.gradient_color = GradientColor(gradient_type)

        ColorSchema.__init__(self, None, [""])
Ejemplo n.º 6
0
    def __init__(self, parent, layer, data, **kwargs):
        PlottingCanvas.__init__(self, parent, data)

        try:
            if isinstance(layer, str) or isinstance(layer, unicode):
                # in case of weights histogram
                self.layer_name = layer
            else:
                self.layer_name = layer.name
            self.isAutoScale = False
            self.intervals = 7
            #self.title = "Histogram (%s)" % (self.layer_name)
            self.title = ""
            self.x_label = data.keys()[0]
            self.y_label = "Counts in bins"
            self.data = data[self.x_label]

            self.enable_axis_x = False
            self.draw_full_axis = False
            self.margin_right = 250  # for legend

            # create a dict for input data for Brushing
            self.data_dict = sorted(self.data, key=self.data.get)  #[obj_id]
            sorted_data = sorted(self.data.values())  #[value]

            if self.x_label == 'Connectivity':
                self.intervals = len(set(sorted_data))
                self.intervals = sorted_data[-1] - sorted_data[0] + 1
                if self.intervals > 50:
                    self.enable_axis_x = True
                    self.margin_right = 40

            if self.intervals > 1:
                self.hist, low_range, binsize, extrapoints = histogram(
                    sorted_data, self.intervals)
            else:
                self.hist = np.array([len(sorted_data)])

            cnt = 0
            bin_idx = 0
            self.bin_index = {}  # key: obj_id, value: bin_idx
            for n in self.hist:
                for i in range(int(n)):
                    obj_id = self.data_dict[cnt]
                    self.bin_index[obj_id] = bin_idx
                    cnt += 1
                bin_idx += 1

            data_min, data_max = sorted_data[0], sorted_data[-1]

            if self.x_label == 'Connectivity':
                #unique_num_neighbors = list(set(sorted_data))
                self.data_intervals = []
                for n in range(sorted_data[0], sorted_data[-1] + 1):
                    self.data_intervals.append((n, n))
            else:
                end_pos = np.cumsum(self.hist)
                start_pos = end_pos - self.hist + 1
                self.data_intervals = [(start_pos[i], end_pos[i])
                                       for i in range(len(self.hist))]

            # a NxN matrix
            self.x_min = 1
            self.x_max = self.intervals + 1
            self.y_min = 0
            self.y_max = np.max(self.hist) + 1

            self.extent = (self.x_min, self.y_min, self.x_max, self.y_max)
            self.status_bar = None  #self.parentFrame.status_bar

            self.gradient_color = GradientColor(gradient_type='rdyibu')

            # color schema: from blue to red
            self.color_matrix = []
            for i in range(self.intervals):
                p = float(i + 1) / self.intervals
                self.color_matrix.append(self.gradient_color.get_color_at(p))

            self.selected_obj_ids = []

        except Exception as err:
            self.ShowMsgBox(
                """ Histogram could not be created. Please select a numeric variable.
            
Details: """ + str(err.message))
            self.isValidPlot = False
            self.parentFrame.Close(True)
            return None

        # linking-brushing events
        self.Register(stars.EVT_OBJS_SELECT, self.OnObjsSelected)
        self.Register(stars.EVT_OBJS_UNSELECT, self.OnNoObjSelect)