예제 #1
1
class Plot2D(Subject):
    """Base class for matplotlib 2D plots
    """
    def __init__(self, scene, **kwargs):
        Subject.__init__(self)
        self._scene = scene
        self._data = None

        self.fig = None
        self.ax = None
        self._show_plt = False
        self._colormap_symmetric = True

        self.title = 'unnamed'

        self._log = logging.getLogger(self.__class__.__name__)

    def __call__(self, *args, **kwargs):
        return self.plot(*args, **kwargs)

    def setCanvas(self, **kwargs):
        """Set canvas to plot in

        :param figure: Matplotlib figure to plot in
        :type figure: :py:class:`matplotlib.Figure`
        :param axes: Matplotlib axes to plot in
        :type axes: :py:class:`matplotlib.Axes`
        :raises: TypeError
        """
        axes = kwargs.get('axes', None)
        figure = kwargs.get('figure', None)

        if isinstance(axes, plt.Axes):
            self.fig, self.ax = axes.get_figure(), axes
            self._show_plt = False
        elif isinstance(figure, plt.Figure):
            self.fig, self.ax = figure, figure.gca()
            self._show_plt = False
        elif axes is None and figure is None and self.fig is None:
            self.fig, self.ax = plt.subplots(1, 1)
            self._show_plt = True
        else:
            raise TypeError('axes has to be of type matplotlib.Axes. '
                            'figure has to be of type matplotlib.Figure')
        self.image = AxesImage(self.ax)
        self.ax.add_artist(self.image)

    @property
    def data(self):
        """ Data passed to matplotlib.image.AxesImage """
        return self._data

    @data.setter
    def data(self, value):
        self._data = value
        self.image.set_data(self.data)
        self.colormapAdjust()

    @data.getter
    def data(self):
        if self._data is None:
            return num.empty((50, 50))
        return self._data

    def _initImagePlot(self, **kwargs):
        """ Initiate the plot

        :param figure: Matplotlib figure to plot in
        :type figure: :py:class:`matplotlib.Figure`
        :param axes: Matplotlib axes to plot in
        :type axes: :py:class:`matplotlib.Axes`
        """
        self.setCanvas(**kwargs)

        self.setColormap(kwargs.get('cmap', 'RdBu'))
        self.colormapAdjust()

        self.ax.set_xlim((0, self._scene.frame.E.size))
        self.ax.set_ylim((0, self._scene.frame.N.size))
        self.ax.set_aspect('equal')
        self.ax.invert_yaxis()

        self.ax.set_title(self.title)

        def close_figure(ev):
            self.fig = None
            self.ax = None

        try:
            self.fig.canvas.mpl_connect('close_event', close_figure)
        # specify!
        except:
            pass

    def plot(self, **kwargs):
        """Placeholder in prototype class

        :param figure: Matplotlib figure to plot in
        :type figure: :py:class:`matplotlib.Figure`
        :param axes: Matplotlib axes to plot in
        :type axes: :py:class:`matplotlib.Axes`
        :param **kwargs: kwargs are passed into `plt.imshow`
        :type **kwargs: dict
        :raises: NotImplemented
        """
        raise NotImplemented
        self._initImagePlot(**kwargs)
        if self._show_plt:
            plt.show()

    def _updateImage(self):
        self.image.set_data(self.data)

    def setColormap(self, cmap='RdBu'):
        """Set matplotlib colormap

        :param cmap: matplotlib colormap name, defaults to 'RdBu'
        :type cmap: str, optional
        """
        self.image.set_cmap(cmap)
        self._notify()

    def colormapAdjust(self):
        """Set colormap limits automatically

        :param symmetric: symmetric colormap around 0, defaults to True
        :type symmetric: bool, optional
        """
        vmax = num.nanmax(self.data)
        vmin = num.nanmin(self.data)
        self.colormap_limits = (vmin, vmax)

    @property
    def colormap_symmetric(self):
        return self._colormap_symmetric

    @colormap_symmetric.setter
    def colormap_symmetric(self, value):
        self._colormap_symmetric = value
        self.colormapAdjust()

    @property
    def colormap_limits(self):
        return self.image.get_clim()

    @colormap_limits.setter
    def colormap_limits(self, limits):
        if not isinstance(limits, tuple):
            raise AttributeError('Limits have to be a tuple (vmin, vmax)')
        vmin, vmax = limits

        if self.colormap_symmetric:
            _max = max(abs(vmin), abs(vmax))
            vmin, vmax = -_max, _max
        self.image.set_clim(vmin, vmax)

        self._notify()

    @staticmethod
    def _colormapsAvailable():
        return [  # ('Perceptually Uniform Sequential',
            #  ['viridis', 'inferno', 'plasma', 'magma']),
            # ('Sequential', ['Blues', 'BuGn', 'BuPu',
            #                 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd',
            #                 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',
            #               'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']),
            # ('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool',
            #                     'copper', 'gist_heat', 'gray', 'hot',
            #                     'pink', 'spring', 'summer', 'winter']),
            ('Diverging', [
                'BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'RdBu', 'RdGy',
                'RdYlBu', 'RdYlGn', 'Spectral', 'seismic', 'PuOr'
            ]),
            ('Qualitative', [
                'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1',
                'Set2', 'Set3'
            ]),
            # ('Miscellaneous', ['gist_earth', 'terrain', 'ocean',
            #                  'brg', 'CMRmap', 'cubehelix', 'gist_stern',
            #                    'gnuplot', 'gnuplot2', 'gist_ncar',
            #                    'nipy_spectral', 'jet', 'rainbow',
            #                    'gist_rainbow', 'hsv', 'flag', 'prism'])
        ]
예제 #2
0
def test_axesimage_setdata():
    ax = plt.gca()
    im = AxesImage(ax)
    z = np.arange(12, dtype=np.float64).reshape((4, 3))
    im.set_data(z)
    z[0, 0] = 9.9
    assert im._A[0, 0] == 0, 'value changed'
예제 #3
0
class Ising2dPlot(animation.TimedAnimation):
    """GUI to examine Ising2d statistics using Monte Carlo."""

    _plots = []

    def __init__(self, network):
        self._network = network
        self._algorithm = MetropolisAlgorithm(network)

        fig = pyplot.figure()
        image_axis = fig.add_subplot(131, aspect='equal')
        self._plots.append(PlotTracker(network, 'energy',
                                       fig.add_subplot(132)))
        self._plots.append(
            PlotTracker(network, 'polarization', fig.add_subplot(133)))

        self.image = AxesImage(image_axis,
                               cmap='Greys',
                               interpolation='nearest')
        image_axis.set_xlim(0, network.cols - 1)
        image_axis.set_ylim(0, network.rows - 1)
        image_axis.add_image(self.image)

        burnAxis = pyplot.axes([0.1, 0.05, 0.8, 0.05])
        self.burnSlider = Slider(burnAxis,
                                 'Burn-off',
                                 0,
                                 1,
                                 valinit=0,
                                 valfmt=u'%d')
        self.burnoff = 0
        self.burnSlider.on_changed(lambda x: self._update_burnoff(x))

        animation.TimedAnimation.__init__(self, fig, blit=True)

    def _update_burnoff(self, x):
        print(x, self._it)
        self.burnoff = int(x * self._it)

    def _draw_frame(self, i):
        self._algorithm.update()

        # Update image
        self.image.set_array(self._network.onGrid)
        self._it = i

        # Update plots
        for plot in self._plots:
            plot.update(i, self.burnoff)

    def new_frame_seq(self):
        i = 0
        while True:
            yield i
            i += 1

    def _init_draw(self):
        self.image.set_array(self._network.onGrid)
    def __init__(self, ax, snapshot):
        self.snapshot = snapshot
        self.ax = ax
        self.ax.set_aspect("equal", "box-forced")

        self.grass = BboxImage(ax.bbox, interpolation="bicubic", zorder=-1000)
        self.ax.add_artist(self.grass)
        self.grass.set_data(GRASS)

        for lane in self.snapshot.lanes:
            path = Path(
                [
                    lane.p - LANE_SCALE * lane.m - lane.n * lane.w * 0.5,
                    lane.p - LANE_SCALE * lane.m + lane.n * lane.w * 0.5,
                    lane.q + LANE_SCALE * lane.m + lane.n * lane.w * 0.5,
                    lane.q + LANE_SCALE * lane.m - lane.n * lane.w * 0.5,
                    lane.p - LANE_SCALE * lane.m - lane.n * lane.w * 0.5,
                ],
                [
                    Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,
                    Path.CLOSEPOLY
                ],
            )
            ax.add_artist(
                PathPatch(
                    path,
                    facecolor=LANE_COLOR,
                    lw=0.5,
                    edgecolor=LANE_BCOLOR,
                    zorder=-100,
                ))

        self.robots = [
            AxesImage(self.ax, interpolation="bicubic", zorder=0)
            for robot in self.snapshot.robots
        ]
        for robot in self.robots:
            self.ax.add_artist(robot)

        self.human = AxesImage(self.ax, interpolation="bicubic", zorder=100)
        self.ax.add_artist(self.human)
        self.ts = np.linspace(0.0, self.snapshot.human.T, STEPS)
        xs = self.snapshot.human.ix(self.ts)
        self.h_future = ax.plot(xs[:, 0],
                                xs[:, 1],
                                zorder=50,
                                linestyle="--",
                                color="white",
                                linewidth=1.0)[0]
        self.h_past = ax.plot(xs[:, 0],
                              xs[:, 1],
                              zorder=40,
                              linestyle="-",
                              color="blue",
                              linewidth=2.0)[0]

        self.ax.set_xlim(-0.5, 0.5)
        self.ax.set_ylim(-0.2, 0.8)
예제 #5
0
        def update_axis(img: ndarray, ratio: float, im: AxesImage) -> AxesImage:
            image_slice = get_slice(img, ratio=ratio)
            # mask_slice = get_slice(mask, ratio=ratio)

            # vn, vm = get_vranges()
            im.set_data(image_slice)
            # im.set_data(mask_slice)
            # im.set_clim(vn, vm)
            # we don't have to update cb, it is linked
            return im
예제 #6
0
    def _addItem(self, axes, item):
        mplAxes = self._axes[axes]

        if isinstance(item, items.Curve):
            x, y = item.getData(copy=False)
            line = Line2D(xdata=x, ydata=y,
                          color=item.color,
                          marker=item.marker,
                          linewidth=item.linewidth,
                          linestyle=item.linestyle,
                          zorder=item.z)
            # TODO error bars, scatter plot..
            # TODO set picker
            mplAxes.add_line(line)
            self._items[item] = line

        elif isinstance(item, items.Image):
            # TODO ModestImage, set picker
            data = item.getData(copy=False)

            if len(data.shape) == 3:  # RGB(A) images
                image = AxesImage(mplAxes,
                                  origin='lower',
                                  interpolation='nearest')
            else:  # Colormap
                # TODO use own colormaps
                cmap = cm.get_cmap(item.colormap.cmap)
                if item.colormap.norm == 'log':
                    norm = LogNorm(item.colormap.vbegin, item.colormap.vend)
                else:
                    norm = Normalize(item.colormap.vbegin, item.colormap.vend)
                image = AxesImage(mplAxes,
                                  origin='lower',
                                  cmap=cmap,
                                  norm=norm,
                                  interpolation='nearest')
            image.set_data(data)
            image.set_zorder(item.z)

            height, width = data.shape[0:2]
            xmin, ymin = item.origin
            xmax = xmin + item.scale[0] * width
            ymax = xmax + item.scale[1] * height

            # set extent (left, right, bottom, top)
            if image.origin == 'upper':
                image.set_extent((xmin, xmax, ymax, ymin))
            else:
                image.set_extent((xmin, xmax, ymin, ymax))

            mplAxes.add_artist(image)
            self._items[item] = image

        else:
            logger.warning('Unsupported item type %s' % str(type(item)))
예제 #7
0
    def image(self):
        if self._image is not None:
            return self._image

        px, py, dx, dy = self._corners
        self._image = AxesImage(self.axes,
                                origin='lower',
                                interpolation='nearest')
        self._image.set_data(self.im)
        self._image.set_extent((dx[0], dx[-1], dy[0], dy[-1]))
        self.axes._set_artist_props(self._image)

        return self._image
예제 #8
0
class Ising2dPlot(animation.TimedAnimation):
    """GUI to examine Ising2d statistics using Monte Carlo."""
    
    _plots = []
    
    def __init__(self, network):
        self._network = network
        self._algorithm = MetropolisAlgorithm(network)
        
        fig = pyplot.figure()
        image_axis = fig.add_subplot(131, aspect='equal')
        self._plots.append(PlotTracker(network, 'energy', fig.add_subplot(132)))
        self._plots.append(PlotTracker(network, 'polarization', fig.add_subplot(133)))
        
        self.image = AxesImage(image_axis, cmap='Greys',  interpolation='nearest')
        image_axis.set_xlim(0,network.cols - 1)
        image_axis.set_ylim(0,network.rows - 1)
        image_axis.add_image(self.image)
        
        burnAxis = pyplot.axes([0.1, 0.05, 0.8, 0.05])
        self.burnSlider = Slider(burnAxis, 'Burn-off', 0, 1, valinit=0, valfmt=u'%d')
        self.burnoff = 0
        self.burnSlider.on_changed(lambda x: self._update_burnoff(x))
        
        animation.TimedAnimation.__init__(self, fig, blit = True)

    def _update_burnoff(self, x):
        print(x,self._it)
        self.burnoff = int(x * self._it)

    def _draw_frame(self, i):
        self._algorithm.update()

        # Update image
        self.image.set_array(self._network.onGrid)
        self._it = i

        # Update plots
        for plot in self._plots:
            plot.update(i, self.burnoff)

    def new_frame_seq(self):
        i = 0
        while True:
            yield i
            i += 1

    def _init_draw(self):
        self.image.set_array(self._network.onGrid)
예제 #9
0
def update(frameNum: int, img: aximg, grid: np.ndarray, config: Configuration,
           output: TextIOWrapper) -> aximg:
    """[Updates the Universe with the set of rules and detecs the configurations that exist]

    Args:
        frameNum (int): Number of the current generation
        img (aximg): Image to display the Universe
        grid (np.ndarray): Universe in for of a 2D space
        config (Configuration): Configuration of the Universe
        output (TextIOWrapper): File to where write the data of the current Universe's generation

    Returns:
        aximg: img updated
    """

    config.generation = frameNum + 1
    # copy grid since we require 8 neighbors for calculation
    newGrid = grid.copy()

    n, m = grid.shape
    visitedGrid = np.zeros(n * m).reshape(n, m)

    for y in range(n):
        for x in range(m):
            # First we check how many configurations exist
            if grid[y, x] == ON and visitedGrid[y, x] != 255:
                for c in reversed(Configurations):
                    flag, toPaint = config.isConfiguration(x, y, c.value)
                    if flag:
                        #print("found {}".format(c.name))
                        config.configurations[c.name] += 1
                        config.generationConfigurations += 1
                        for cell in toPaint:
                            newY = y + cell[1]
                            newX = x + cell[0]
                            visitedGrid[newY, newX] = 255
                        break
            #  We apply the set of rules to know wich cells live
            if checkRules(grid, x, y):
                newGrid[y, x] = ON
            else:
                newGrid[y, x] = OFF

    # update data
    config.update(output, newGrid)
    img.set_data(newGrid)
    grid[:] = newGrid[:]

    return img,
예제 #10
0
def visualize(traj_real, traj_fake, seq_start_end):
    st.button('show animation')
    animation_image = st.empty()
    fig, ax = plt.subplots()
    ax.set_xlim(-50, 50)
    ax.set_ylim(-30, 30)
    plt.xlabel("Meters")
    plt.ylabel("Meters")
    CAR = {
        color:
        zoom(plt.imread('/home/ubuntu/CarGAN/img/car-{}.png'.format(color)),
             [0.3, 0.3, 1.])
        for color in ['gray', 'orange', 'purple', 'red', 'white', 'yellow']
    }
    #rect = patches.Rectangle((-50,-35),100,70,linewidth=1,edgecolor='none',facecolor='gray')
    #ax.add_patch(rect)
    scale = 5. / max(CAR['gray'].shape[:2])
    st.sidebar.subheader('Select a scene to visualize')
    scene_num = st.sidebar.selectbox('Scene #', range(0, len(seq_start_end)),
                                     1)
    start, end = seq_start_end[scene_num]
    num_agents = end - start
    traj_real = traj_real[:, start:end, :].cpu().detach().numpy(
    )  #trajectories of all the agents in the scene
    traj_fake = traj_fake[:, start:end, :].cpu().detach().numpy()
    color = ['gray', 'orange', 'purple', 'red', 'yellow', 'white']
    angle = np.zeros((traj_fake.shape[0], traj_fake.shape[1]))
    c = 0
    for i in range(num_agents):
        x_pos = traj_fake[:, i, 0]
        y_pos = traj_fake[:, i, 1]
        den = x_pos[1:] - x_pos[:-1]
        num = y_pos[1:] - y_pos[:-1]
        angle[1:, i] = np.arctan2(num, den)
        ax.plot(traj_fake[:, i, 0],
                traj_fake[:, i, 1],
                lw=0.5,
                linestyle='--',
                color=color[c],
                label="agent#" + str(i))
        plt.text(traj_fake[0, i, 0] + 2., traj_fake[0, i, 1] + 2., str(i))
        c += 1
    angle = angle.reshape((angle.shape[0], angle.shape[1], 1))
    x_vec = np.concatenate((traj_fake, angle), axis=2)
    cars = [
        AxesImage(ax, interpolation='bicubic', zorder=100)
        for _ in np.arange(x_vec.shape[1])
    ]
    for num in range(x_vec.shape[0]):
        c = 0
        for car in cars:
            ax.add_artist(car)
            set_image(car, CAR[color[c]], scale, x_vec[num, c, :])
            c += 1
        animation_image.pyplot(fig)
    final_scene_num = scene_num
    st.sidebar.subheader('Select an agent to make adversarial')
    final_agent_num = st.sidebar.selectbox('Agent #', range(0, end - start), 1)
    return final_scene_num, final_agent_num
예제 #11
0
    def create_artists(self, legend, artist, xdescent, ydescent, width, height,
                       fontsize, trans):
        # Obtain the Axes object of this legend
        ax = legend.axes

        # Obtain the colormap of the artist
        cmap = artist.cmap

        # Create an AxesImage to contain the colormap with proper dimensions
        image = AxesImage(ax,
                          cmap=cmap,
                          transform=trans,
                          extent=[xdescent, width, ydescent, height])

        # Set the data of the image
        image.set_data(np.arange(cmap.N)[np.newaxis, ...])

        # Return the AxesImage object
        return ([image])
예제 #12
0
    def _do_init(self) -> Gtk.Widget:
        from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
        from matplotlib.figure import Figure
        from matplotlib.image import AxesImage

        self._widget = Gtk.Grid()

        figure = Figure(tight_layout=True)

        self._figure_canvas = FigureCanvas(figure)
        self._figure_canvas.props.hexpand = True
        self._figure_canvas.props.vexpand = True
        self._figure_canvas.show()
        self._widget.add(self._figure_canvas)

        # Axes
        self._axes = figure.add_subplot(1, 1, 1)
        self._axes.set_aspect('equal', 'box')
        self._axes.xaxis.tick_top()
        for item in (*self._axes.get_xticklabels(),
                     *self._axes.get_yticklabels()):
            item.set_fontsize(8)

        self._axes_bg_image = AxesImage(ax=self._axes)

        # Placeholder transparent 1x1 image (rgba format)
        self._axes_bg_image.set_data(np.zeros((1, 1, 4)))
        self._axes.add_image(self._axes_bg_image)

        self._profile_extract_line = self._axes.plot([],
                                                     linestyle='-',
                                                     color='#0080ff',
                                                     linewidth=1.5)[0]
        self._profile_fit_line = self._axes.plot([],
                                                 linestyle='-',
                                                 color='#ff0080',
                                                 linewidth=1)[0]

        self.presenter.view_ready()

        return self._widget
예제 #13
0
 def _disable_normalisation_option(self, mappable: AxesImage, option_index: int, norm_type: Normalize,
                                   tooltip: str) -> None:
     """Disables a non-linear normalisation option and sets the new normalisation to Linear."""
     if option_index == 0:
         raise ValueError("The Linear normalisation option cannot be disabled.")
     self.norm.model().item(option_index, 0).setEnabled(False)
     self.norm.setItemData(option_index, tooltip, Qt.ToolTipRole)
     if isinstance(mappable.norm, norm_type):
         mappable.norm = self._create_linear_normalize_object()
         self.norm.blockSignals(True)
         self.norm.setCurrentIndex(0)
         self.norm.blockSignals(False)
예제 #14
0
파일: conway.py 프로젝트: cubomx/conway-gol
def update(frameNum:int, img:image, grid:np.ndarray, N: int):
    global X, Y, step
    # copy grid since we require 8 neighbors for calculation
    # and we go line by line 
    newGrid = grid.copy()

    cells = count_cells(grid, X, Y)

    step += 1
    
    newGrid = first_rule(grid, newGrid, N)

    if step <= 200:
        saveData(step, cells, file_)
    if step == 201:
        close_file(file_)

    
    # update data
    img.set_data(newGrid)
    grid[:] = newGrid[:]
    return img,
예제 #15
0
def cursor_info(image: AxesImage, xdata: float, ydata: float) -> Optional[CursorInfo]:
    """Return information on the image for the given position in
    data coordinates.
    :param image: An instance of an image type
    :param xdata: X data coordinate of cursor
    :param xdata: Y data coordinate of cursor
    :return: None if point is not valid on the image else return CursorInfo type
    """
    extent = image.get_extent()
    xmin, xmax, ymin, ymax = extent
    arr = image.get_array()
    data_extent = Bbox([[ymin, xmin], [ymax, xmax]])
    array_extent = Bbox([[0, 0], arr.shape[:2]])
    trans = BboxTransform(boxin=data_extent, boxout=array_extent)
    point = trans.transform_point([ydata, xdata])
    if any(np.isnan(point)):
        return None

    point = point.astype(int)
    if 0 <= point[0] < arr.shape[0] and 0 <= point[1] < arr.shape[1]:
        return CursorInfo(array=arr, extent=extent, point=point)
    else:
        return None
예제 #16
0
 def __init__(self, network):
     self._network = network
     self._algorithm = MetropolisAlgorithm(network)
     
     fig = pyplot.figure()
     image_axis = fig.add_subplot(131, aspect='equal')
     self._plots.append(PlotTracker(network, 'energy', fig.add_subplot(132)))
     self._plots.append(PlotTracker(network, 'polarization', fig.add_subplot(133)))
     
     self.image = AxesImage(image_axis, cmap='Greys',  interpolation='nearest')
     image_axis.set_xlim(0,network.cols - 1)
     image_axis.set_ylim(0,network.rows - 1)
     image_axis.add_image(self.image)
     
     burnAxis = pyplot.axes([0.1, 0.05, 0.8, 0.05])
     self.burnSlider = Slider(burnAxis, 'Burn-off', 0, 1, valinit=0, valfmt=u'%d')
     self.burnoff = 0
     self.burnSlider.on_changed(lambda x: self._update_burnoff(x))
     
     animation.TimedAnimation.__init__(self, fig, blit = True)
예제 #17
0
 def __init__(self, t, xy, roi, n, *args, **kwargs):
     
     self.figure = None
     self._t = t
     self._xy = xy # (n,2) array
     self._roi = roi # [ [xmin, xmax], [ymin, ymax] ]
     self._n = n # integer
     
     # construct artists for current position, future and past paths
     self._current = Line2D( [], [], marker='o', color='black', linestyle='none', markersize=10, clip_on=True )
     self._future = [ Line2D( [], [], marker='.', color='red', linestyle='none', clip_on=True ) for x in range(self._n+1) ]
     self._past = [ Line2D( [], [], marker='.', color='blue', linestyle='none', clip_on=True ) for x in range(self._n+1) ]
     
     # construct artists for background
     img, _, _ = np.histogram2d( xy[:,0], xy[:,1], bins=[100,100], range=roi, normed=True )
     img[img>0.] = 0.2
     
     self._all = [ AxesImage( None, data=img.T, cmap='gray_r', norm=matplotlib.colors.Normalize(vmin=0, vmax=1.) ) for  x in range(self._n+1) ]
     
     super(PositionTimeStrip, self).__init__(*args, **kwargs)
예제 #18
0
 def __init__(self, *args, **kargs):
     ArtGL.__init__(self)
     AxesImage.__init__(self, *args, **kargs)
     self._gl_interp = 'nearest'
     self._gl_rgbacache_id = None
예제 #19
0
 def set_interpolation(self, s):
     if s != None and s != 'nearest':
         raise NotImplementedError('Only nearest neighbor supported')
     AxesImage.set_interpolation(self, s)
예제 #20
0
    def plot_data2D(self, data2D, dataX, dataY, tabs_canvas_index, plot_canvas_index, title="", xtitle="", ytitle="", mode=2):

        for i in range(1+self.tab[tabs_canvas_index].layout().count()):
            self.tab[tabs_canvas_index].layout().removeItem(self.tab[tabs_canvas_index].layout().itemAt(i))

        if mode == 0:
            figure = FigureCanvas(gol.plot_image(data2D,
                                                 dataX,
                                                 dataY,
                                                 xtitle=xtitle,
                                                 ytitle=ytitle,
                                                 title=title,
                                                 show=False,
                                                 aspect='auto'))


            self.plot_canvas[plot_canvas_index] = figure
        else:

            origin = (dataX[0],dataY[0])
            scale = (dataX[1]-dataX[0],dataY[1]-dataY[0])

            data_to_plot = data2D.T

            colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}


            if mode == 1:
                #TODO: delete: srio commented this part as it is never used
                raise Exception("Cannot use XoppyPlot.XoppyImageView()")
                # self.plot_canvas[plot_canvas_index] = XoppyPlot.XoppyImageView()
                # colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}
                #
                # self.plot_canvas[plot_canvas_index]._imagePlot.setDefaultColormap(colormap)
                # self.plot_canvas[plot_canvas_index].setImage(numpy.array(data_to_plot), origin=origin, scale=scale)
            elif mode == 2:

                self.plot_canvas[plot_canvas_index] = Plot2D()

                self.plot_canvas[plot_canvas_index].resetZoom()
                self.plot_canvas[plot_canvas_index].setXAxisAutoScale(True)
                self.plot_canvas[plot_canvas_index].setYAxisAutoScale(True)
                self.plot_canvas[plot_canvas_index].setGraphGrid(False)
                self.plot_canvas[plot_canvas_index].setKeepDataAspectRatio(True)
                self.plot_canvas[plot_canvas_index].yAxisInvertedAction.setVisible(False)

                self.plot_canvas[plot_canvas_index].setXAxisLogarithmic(False)
                self.plot_canvas[plot_canvas_index].setYAxisLogarithmic(False)
                #silx 0.4.0
                self.plot_canvas[plot_canvas_index].getMaskAction().setVisible(False)
                self.plot_canvas[plot_canvas_index].getRoiAction().setVisible(False)
                self.plot_canvas[plot_canvas_index].getColormapAction().setVisible(False)
                self.plot_canvas[plot_canvas_index].setKeepDataAspectRatio(False)



                self.plot_canvas[plot_canvas_index].addImage(numpy.array(data_to_plot),
                                                             legend="zio billy",
                                                             scale=scale,
                                                             origin=origin,
                                                             colormap=colormap,
                                                             replace=True)

                self.plot_canvas[plot_canvas_index].setActiveImage("zio billy")

                # COLOR TABLE
                from matplotlib.image import AxesImage
                image = AxesImage(self.plot_canvas[plot_canvas_index]._backend.ax)
                image.set_data(numpy.array(data_to_plot))
                self.plot_canvas[plot_canvas_index]._backend.fig.colorbar(image, ax=self.plot_canvas[plot_canvas_index]._backend.ax)

            self.plot_canvas[plot_canvas_index].setGraphXLabel(xtitle)
            self.plot_canvas[plot_canvas_index].setGraphYLabel(ytitle)
            self.plot_canvas[plot_canvas_index].setGraphTitle(title)

        self.tab[tabs_canvas_index].layout().addWidget(self.plot_canvas[plot_canvas_index])
예제 #21
0
    def plot_data2D(self, data2D, dataX, dataY, tabs_canvas_index, plot_canvas_index, title="", xtitle="", ytitle="", mode=2):

        self.tab[tabs_canvas_index].layout().removeItem(self.tab[tabs_canvas_index].layout().itemAt(0))

        if mode == 0:
            figure = FigureCanvas(gol.plot_image(data2D,
                                                 dataX,
                                                 dataY,
                                                 xtitle=xtitle,
                                                 ytitle=ytitle,
                                                 title=title,
                                                 show=False,
                                                 aspect='auto'))


            self.plot_canvas[plot_canvas_index] = figure
        else:
            xmin = numpy.min(dataX)
            xmax = numpy.max(dataX)
            ymin = numpy.min(dataY)
            ymax = numpy.max(dataY)

            origin = (xmin, ymin)
            scale = (abs((xmax-xmin)/len(dataX)), abs((ymax-ymin)/len(dataY)))

            # PyMCA inverts axis!!!! histogram must be calculated reversed
            data_to_plot = []
            for y_index in range(0, len(dataY)):
                x_values = []
                for x_index in range(0, len(dataX)):
                    x_values.append(data2D[x_index][y_index])

                data_to_plot.append(x_values)

            if mode == 1:
                self.plot_canvas[plot_canvas_index] = XoppyPlot.XoppyImageView()
                colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}

                self.plot_canvas[plot_canvas_index]._imagePlot.setDefaultColormap(colormap)
                self.plot_canvas[plot_canvas_index].setImage(numpy.array(data_to_plot), origin=origin, scale=scale)
            elif mode == 2:
                self.plot_canvas[plot_canvas_index] = PlotWindow(colormap=False,
                                                                 flip=False,
                                                                 grid=False,
                                                                 togglePoints=False,
                                                                 logx=False,
                                                                 logy=False,
                                                                 copy=False,
                                                                 save=True,
                                                                 aspect=True,
                                                                 roi=False,
                                                                 control=False,
                                                                 position=True,
                                                                 plugins=False)

                colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}

                self.plot_canvas[plot_canvas_index].setDefaultColormap(colormap)

                self.plot_canvas[plot_canvas_index].addImage(numpy.array(data_to_plot),
                                                             legend="zio billy",
                                                             xScale=(origin[0], scale[0]),
                                                             yScale=(origin[1], scale[1]),
                                                             colormap=colormap,
                                                             replace=True,
                                                             replot=True)
                self.plot_canvas[plot_canvas_index].setActiveImage("zio billy")

                from matplotlib.image import AxesImage
                image = AxesImage(self.plot_canvas[plot_canvas_index]._plot.ax)
                image.set_data(numpy.array(data_to_plot))

                self.plot_canvas[plot_canvas_index]._plot.graph.fig.colorbar(image, ax=self.plot_canvas[plot_canvas_index]._plot.ax)

            self.plot_canvas[plot_canvas_index].setGraphXLabel(xtitle)
            self.plot_canvas[plot_canvas_index].setGraphYLabel(ytitle)
            self.plot_canvas[plot_canvas_index].setGraphTitle(title)

        self.tab[tabs_canvas_index].layout().addWidget(self.plot_canvas[plot_canvas_index])
예제 #22
0
class DropFitView(View['DropFitPresenter', Gtk.Widget]):
    def _do_init(self) -> Gtk.Widget:
        from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
        from matplotlib.figure import Figure
        from matplotlib.image import AxesImage

        self._widget = Gtk.Grid()

        figure = Figure(tight_layout=True)

        self._figure_canvas = FigureCanvas(figure)
        self._figure_canvas.props.hexpand = True
        self._figure_canvas.props.vexpand = True
        self._figure_canvas.show()
        self._widget.add(self._figure_canvas)

        # Axes
        self._axes = figure.add_subplot(1, 1, 1)
        self._axes.set_aspect('equal', 'box')
        self._axes.xaxis.tick_top()
        for item in (*self._axes.get_xticklabels(),
                     *self._axes.get_yticklabels()):
            item.set_fontsize(8)

        self._axes_bg_image = AxesImage(ax=self._axes)

        # Placeholder transparent 1x1 image (rgba format)
        self._axes_bg_image.set_data(np.zeros((1, 1, 4)))
        self._axes.add_image(self._axes_bg_image)

        self._profile_extract_line = self._axes.plot([],
                                                     linestyle='-',
                                                     color='#0080ff',
                                                     linewidth=1.5)[0]
        self._profile_fit_line = self._axes.plot([],
                                                 linestyle='-',
                                                 color='#ff0080',
                                                 linewidth=1)[0]

        self.presenter.view_ready()

        return self._widget

    def set_drop_image(self, image: Optional[np.ndarray]) -> None:
        if image is None:
            self._axes.set_axis_off()
            self._axes_bg_image.set_data(np.zeros((1, 1, 4)))
            self._figure_canvas.draw()
            return

        self._axes.set_axis_on()

        # Use a scaled down image so it draws faster.
        thumb_size = (min(400, image.shape[1]), min(400, image.shape[0]))
        image_thumb = cv2.resize(image, dsize=thumb_size)
        self._axes_bg_image.set_data(image_thumb)

        self._axes_bg_image.set_extent((0, image.shape[1], image.shape[0], 0))
        self._figure_canvas.draw()

    def set_drop_profile_extract(self, profile: Optional[np.ndarray]) -> None:
        if profile is None:
            self._profile_fit_line.set_visible(False)
            self._figure_canvas.draw()
            return

        self._profile_fit_line.set_data(profile.T)
        self._profile_fit_line.set_visible(True)
        self._figure_canvas.draw()

    def set_drop_profile_fit(self, profile: Optional[np.ndarray]) -> None:
        if profile is None:
            self._profile_extract_line.set_visible(False)
            self._figure_canvas.draw()
            return

        self._profile_extract_line.set_data(profile.T)
        self._profile_extract_line.set_visible(True)
        self._figure_canvas.draw()

    def _do_destroy(self) -> None:
        self._widget.destroy()
예제 #23
0
        num = pos_y[1:] - pos_y[:-1]
        angle[i, 1:] = num / den
        angle[i, :] = [0. if math.isnan(x) else x for x in angle[i, :]]
        ax.plot(sc[i, :, 0].cpu().detach().numpy(),
                sc[i, :, 1].cpu().detach().numpy(),
                color=color[c],
                linestyle='--')
        ax.plot(gt[i, :, 0].cpu().detach().numpy(),
                gt[i, :, 1].cpu().detach().numpy(),
                color=color[c])
        c += 1
    angle = angle.reshape(gt.size(0), gt.size(1), 1)
    x_vec = np.concatenate(
        (sc_np[seq_num:seq_num + 4], angle[seq_num:seq_num + 4]), axis=2)
    t = np.arange(x_vec.shape[1])
    t = st.slider('Time', 0, x_vec.shape[1] - 1, 0)
    cars = [
        AxesImage(ax, interpolation='bicubic', zorder=100)
        for _ in np.arange(x_vec.shape[0])
    ]
    c = 0
    for car in cars:
        ax.add_artist(car)
        set_image(car, CAR[color[c]], scale, x_vec[c, t, :])
        c += 1
plt.ylabel('Meters')
plt.xlabel('Meters')
ax.set_xlim(-35., 35.)
ax.set_ylim(-35., 35.)
st.write(fig)
def update(frameNum: int, img: mltimg.AxesImage, grid: np.ndarray, N: int,
           ax: mltax.Axes, G: int):

    newGrid = grid.copy()
    visited = np.zeros(N * N).reshape(N, N)
    counters = np.zeros(len(BEINGS))
    reported = []
    global FRAME
    if frameNum == 1:
        print("SUCCESS Simulation begins.")

    # implementation of the rules of Life
    for i in range(N):
        for j in range(N):
            rareCase = False
            myNeighbours = checkNeighbours(i, j, grid)
            me = int(grid[i][j])
            if myNeighbours == 0:
                rareCase = True
            if me != 0 and myNeighbours < 2:  # underpopulation
                newGrid[i][j] = 0
            if me != 0 and (myNeighbours == 2
                            or myNeighbours == 3):  # next generation
                newGrid[i][j] = 255
            if me != 0 and myNeighbours > 3:  # overpopulation
                newGrid[i][j] = 0
            if me != 255 and myNeighbours == 3:  # reproduction
                newGrid[i][j] = 255
            # count Life patterns if not checked already
            if int(visited[i][j]) == 0:
                res, visited = countLife(i, j, grid, visited, rareCase)
                # if something detected, count it
                if len(res) > 0:
                    reported.append(res)
                    counters[int(res[0])] += 1
                    global TOTAL_COUNTERS
                    TOTAL_COUNTERS[int(res[0])] += 1

    # update total counters for seeds and others
    num, visited = countOthers(grid, visited)
    global TOTAL_OTHERS
    TOTAL_OTHERS += num

    global TOTAL_LIVES
    TOTAL_LIVES += len(reported)

    # report the count at every frame
    handleReport("------ Generation {0} ------\n".format(FRAME))
    handleReport("Total Life Beings: {0}\n".format(len(reported)))
    handleReport("Total Other Beings: {0}\n".format(num))
    handleReport("+++++++++++++++++++++++++++\n")
    for i in range(len(BEINGS)):
        handleReport("{n}: {v}\n".format(n=BEINGS_STR[i], v=int(counters[i])))
    handleReport("+++++++++++++++++++++++++++\n")
    for j in range(len(reported)):
        handleReport("{i}. {n} at {y}, {x}\n".format(
            i=j + 1,
            n=BEINGS_STR[reported[j][0]],
            y=reported[j][1],
            x=reported[j][2]))

    # at last, calculate percentage of appearance
    if frameNum == (G - 1):
        handleReport("======= Incidence % =======\n")
        if TOTAL_LIVES == 0 and TOTAL_OTHERS == 0:
            TOTAL_LIVES = 1  # to avoid div by zero
        for i in range(len(BEINGS)):
            handleReport("{n}: {v} %\n".format(
                n=BEINGS_STR[i],
                v=round(
                    (TOTAL_COUNTERS[i] / (TOTAL_LIVES + TOTAL_OTHERS)) * 100.0,
                    2)))
        handleReport("{n}: {v} %\n".format(
            n="others",
            v=round((TOTAL_OTHERS / (TOTAL_LIVES + TOTAL_OTHERS)) * 100.0, 2)))
        handleReport("", True)
        print("SUCCESS Simulation Report is now available.")

    # update data
    ax.set_title("Conway's Game of Life\nGeneration = {0}".format(frameNum +
                                                                  1))
    img.set_data(newGrid)
    img.set_cmap('binary')
    grid[:] = newGrid[:]
    FRAME += 1
    return img,
예제 #25
0
color_list = []
for shape_dict in m.states_info:
    cur_name = shape_dict['NAME']
    state_names.append(cur_name)
    # Don't have data-collection for PR, so skip
    if cur_name == 'Puerto Rico':
        color_list.append([0, 0, 0, 0])
        continue
    state_count = states[states["name"] == cur_name]["count_by_pop"]
    cur_color = cmap(norm(state_count))[0]
    color_list.append(cur_color)

ax = plt.gca()

# Color each state and render on map
for nshape, seg in enumerate(m.states):
    color = rgb2hex(color_list[nshape])
    poly = Polygon(seg, facecolor=color, edgecolor=color)
    ax.add_patch(poly)

plt.title('Number of Tweets per Million Residents\n about COVID-19 per State')

# Render the colorbar legend
img = AxesImage(states["count_by_pop"], cmap, norm=norm)
cb = plt.colorbar(img)

print(states[["name", "count", "count_by_pop"]])

plt.savefig('../plots/state_counts_by_pop.png')
plt.show()
예제 #26
0
class RenderCapture(object):

    """
    A RemderCapture saves an image of a fully-rendered
    Axes instance, and provides a method for re-rendering
    a properly transformed image during panning and zooming
    """

    def __init__(self, axes, renderer):
        self.axes = axes
        self._corners = self._get_corners(axes)
        px, py, dx, dy = self._corners

        im = self.extract_image(renderer)
        im = im[py[0]: py[-1] + 1, px[0]: px[-1] + 1, :]
        self.im = im
        self._mesh = None
        self._image = None
        self.image

    @property
    def image(self):
        if self._image is not None:
            return self._image

        px, py, dx, dy = self._corners
        self._image = AxesImage(self.axes,
                                origin='lower',
                                interpolation='nearest')
        self._image.set_data(self.im)
        self._image.set_extent((dx[0], dx[-1], dy[0], dy[-1]))
        self.axes._set_artist_props(self._image)

        return self._image

    @property
    def mesh(self):
        if self._mesh is not None:
            return self._mesh
        px, py, dx, dy = self._corners
        x, y, c = self.axes._pcolorargs('pcolormesh', dx, dy,
                                        self.im[:, :, 0],
                                        allmatch=False)
        ny, nx = x.shape
        coords = np.column_stack((x.ravel(), y.ravel()))
        collection = QuadMesh(nx - 1, ny - 1, coords,
                              shading='flat', antialiased=False,
                              edgecolors='None',
                              cmap='gray')
        collection.set_array(c.ravel())
        collection.set_clip_path(self.axes.patch)
        collection.set_transform(self.axes.transData)
        self._mesh = collection
        return self._mesh

    def draw(self, renderer, *args, **kwargs):
        if self.axes.get_xscale() == 'linear' and \
                self.axes.get_yscale() == 'linear':
            self.image.draw(renderer, *args, **kwargs)
        else:
            self.mesh.draw(renderer, *args, **kwargs)

    @staticmethod
    def _get_corners(axes):
        """
        Return the device and data coordinates
        for a box slightly inset from the edge
        of an axes instance

        Returns 4 1D arrays:
        px : Pixel X locations for each column of the box
        py : Pixel Y locations for each row of the box
        dx : Data X locations for each column of the box
        dy : Data Y locations for each row of the box
        """
        xlim = axes.get_xlim()
        ylim = axes.get_ylim()
        pts = np.array([[xlim[0], ylim[0]],
                        [xlim[1], ylim[1]]])

        corners = axes.transData.transform(pts).astype(np.int)

        # move in 5 pixels, to avoid grabbing the tick marks
        px = np.arange(corners[0, 0] + 5, corners[1, 0] - 5)
        py = np.arange(corners[0, 1] + 5, corners[1, 1] - 5)

        tr = axes.transData.inverted().transform
        dx = tr(np.column_stack((px, px)))[:, 0]
        dy = tr(np.column_stack((py, py)))[:, 1]
        return px, py, dx, dy

    @staticmethod
    def extract_image(renderer):
        try:
            buf = renderer.buffer_rgba()
        except TypeError:  # mpl v1.1 has different signature
            buf = renderer.buffer_rgba(0, 0)

        result = np.frombuffer(buf, dtype=np.uint8)
        result = result.reshape((int(renderer.height),
                                 int(renderer.width), 4)).copy()
        return np.flipud(result)
예제 #27
0
def imshow_classification_overlay(ax, _data, pol_suf, xq='theta',
                                  yq='wavelength', cmap='custom',
                                  repr_measure='silhouettes',
                                  make_comparable_to=None,
                                  bkg_black=True, exponent=1., clip_zero=0.0,
                                  clip_softly=True, overdrive=0.,
                                  plot_cbar=True, **kwargs):
    from matplotlib.image import AxesImage
    from sklearn.preprocessing import minmax_scale
    data = deepcopy(_data)

    # The image data based on the cluster labels
    data_labels = get_pivot_data(data, 'Classification' + pol_suf, xq, yq)
    image = data_labels.values

    if repr_measure == 'distances':
        if not make_comparable_to is None:
            raise NotImplementedError('`make_comparable_to` ia only ' +
                                      'implemented for `repr_measure="silhouettes"`')
        # Alpha data based on the Euclidian distances
        distances = data['Euclidian_Distances' + pol_suf]
        data['_pl_alpha'] = minmax_scale(1. / distances)
        data_alpha = get_pivot_data(data, '_pl_alpha', xq, yq)
        alpha = data_alpha.values
    elif repr_measure == 'silhouettes':
        silhouettes = get_pivot_data(data, 'Silhouettes' + pol_suf, xq,
                                     yq).values

        if make_comparable_to is None:
            _gmin = silhouettes.min()
            _gmax = silhouettes.max()
            _ptp = silhouettes.ptp()
        else:
            sil_comp = make_comparable_to['Silhouettes' + pol_suf]

            _min1, _max1 = silhouettes.min(), silhouettes.max()
            _min2, _max2 = sil_comp.min(), sil_comp.max()
            _gmax = max([_max1, _max2])
            _gmin = min([_min1, _min2])
            _ptp = _gmax - _gmin
        sil_range = (_gmin, _gmax)
        alpha = (silhouettes - _gmin) / _ptp
    elif repr_measure == 'probability':
        alpha = get_pivot_data(data, 'Probability' + pol_suf, xq, yq).values
        sil_range = (0., 1.)

    # Manipulate the alphas based on clipping and n_sqrts settings
    if overdrive > 0.:
        alpha = np.clip(alpha * (1. + overdrive), 0., 1.)
    if exponent != 1.:
        alpha = np.power(alpha, exponent)
    if clip_zero > 0. and clip_zero < 1.:
        if clip_softly:
            alpha = minmax_scale(alpha.ravel(), (clip_zero, 1.)). \
                reshape(alpha.shape)
        else:
            alpha = np.clip(alpha, clip_zero, 1.)

    #    # Set new maximum
    #    if max_final < 1.:
    #        alpha = minmax_scale(alpha.ravel(), (clip_zero, max_final)).\
    #                                                        reshape(alpha.shape)
    if clip_zero >= 1.:
        alpha = np.ones_like(alpha)
    extent = (data_labels.columns.min(), data_labels.columns.max(),
              data_labels.index.min(), data_labels.index.max())

    # make a color map of fixed colors
    n_colors = int(image.max()) + 1
    cmap, bounds, norm = get_discrete_cmap(n_colors, cmap)

    # Set default kwargs
    kwdefaults = dict(origin='lower', aspect='auto',
                      interpolation='none')
    for dkey, dval in kwdefaults.iteritems():
        if not dkey in kwargs:
            kwargs[dkey] = dval

    # get dummy_image for colorbar
    im_dummy = ax.imshow(image, extent=extent, cmap=cmap,
                         norm=norm, **kwargs)
    ax.images.pop()  # remove it afterwards

    # Get an AxesImage to convert to RGBA
    im = AxesImage(ax, cmap, norm, kwdefaults['interpolation'],
                   kwdefaults['origin'], extent)
    rgba = im.to_rgba(image)

    # Set the alpha column to the alpha values based on the distance measure
    rgba[:, :, 3] = alpha

    # Create a black background image if bkg_black is True
    if bkg_black:
        im_black = deepcopy(rgba)
        im_black[:, :, :3] = 0.
        im_black[:, :, 3] = 1.
        im = ax.imshow(im_black, extent=extent, **kwargs)
    im = ax.imshow(rgba, extent=extent, **kwargs)

    # Draw the colorbar
    if plot_cbar:
        if hasattr(ax, 'cax'):
            cax = ax.cax
        else:
            cax = None
        cb = plt.colorbar(im_dummy, cmap=cmap, norm=norm, boundaries=bounds,
                          ticks=bounds[1:] - 0.5, cax=cax)
        cb.set_ticklabels([str(int(it)) for it in bounds[1:]])

    # Set labels
    if hasattr(ax, 'cax') and plot_cbar:
        ax.cax.set_ylabel('Labels')
    ax.set_xlabel(xq)
    ax.set_ylabel(yq)
    ax.set_title('Clustering of $E$-field data')
    if repr_measure == 'distances':
        return im, im_dummy, bounds
    return im, im_dummy, bounds, sil_range
예제 #28
0
 def __init__(self, ax,
              **kwargs
             ):
     AxesImage.__init__(self, ax,
                        **kwargs)
예제 #29
0
 def set_interpolation(self, s):
     if s != None and s != 'nearest':
         raise NotImplementedError('Only nearest neighbor supported')
     AxesImage.set_interpolation(self, s)
예제 #30
0
 def __init__(self, ax, **kwargs):
     AxesImage.__init__(self, ax, **kwargs)