Beispiel #1
0
    def plot(self,
             ax=None,
             color=np.random.rand(3),
             show_domain=True,
             res=(5, 5),
             **kwargs):
        try:
            from tulip.graphics import newax, quiver
        except:
            logger.error('failed to import graphics')
            warn('pyvectorized not found. No plotting.')
            return

        (x, res) = pc.grid_region(self.domain, res=res)
        n = self.A.shape[0]
        DA = self.A - np.eye(n)
        v = DA.dot(x) + self.K

        if ax is None:
            ax, fig = newax()

        if show_domain:
            self.domain.plot(ax, color)

        quiver(x, v, ax, **kwargs)

        return ax
Beispiel #2
0
 def plot(self, ax=None, show_domain=True):
     if ax is None:
         ax, fig = newax()
     
     for subsystem in self.list_subsys:
         subsystem.plot(ax, color=np.random.rand(3),
                        show_domain=show_domain)
     return ax
Beispiel #3
0
    def plot(self, ax=None, show_domain=True, **kwargs):
        try:
            from tulip.graphics import newax
        except:
            logger.error("failed to import graphics")
            return

        if ax is None:
            ax, fig = newax()

        for subsystem in self.list_subsys:
            subsystem.plot(ax, color=np.random.rand(3), show_domain=show_domain, **kwargs)
        return ax
Beispiel #4
0
    def plot(self, ax=None, show_domain=True, **kwargs):
        try:
            from tulip.graphics import newax
        except:
            logger.error('failed to import graphics')
            return

        if ax is None:
            ax, fig = newax()

        for subsystem in self.list_subsys:
            subsystem.plot(ax, color=np.random.rand(3),
                           show_domain=show_domain, **kwargs)
        return ax
Beispiel #5
0
def plot_trajectory(ppp, x0, u_seq, ssys,
                    ax=None, color_seed=None):
    """Plots a PropPreservingPartition and the trajectory generated by x0
    input sequence u_seq.

    See Also
    ========
    C{plot_partition}, plot

    @type ppp: L{PropPreservingPartition}
    @param x0: initial state
    @param u_seq: matrix where each row contains an input
    @param ssys: system dynamics
    @param color_seed: see C{plot_partition}
    @return: axis object
    """
    try:
        from tulip.graphics import newax
    except:
        logger.error('failed to import graphics.newax')
        return

    if ax is None:
        ax, fig = newax()

    plot_partition(plot_numbers=False, ax=ax, show=False)

    A = ssys.A
    B = ssys.B

    if ssys.K is not None:
        K = ssys.K
    else:
        K = np.zeros(x0.shape)

    x = x0.flatten()
    x_arr = x0
    for i in range(u_seq.shape[0]):
        x = (
            np.dot(A, x).flatten() +
            np.dot(B, u_seq[i, :] ).flatten() +
            K.flatten())
        x_arr = np.vstack([x_arr, x.flatten()])

    ax.plot(x_arr[:,0], x_arr[:,1], 'o-')

    return ax
Beispiel #6
0
def plot_trajectory(ppp, x0, u_seq, ssys,
                    ax=None, color_seed=None):
    """Plots a PropPreservingPartition and the trajectory generated by x0
    input sequence u_seq.

    See Also
    ========
    C{plot_partition}, plot

    @type ppp: L{PropPreservingPartition}
    @param x0: initial state
    @param u_seq: matrix where each row contains an input
    @param ssys: system dynamics
    @param color_seed: see C{plot_partition}
    @return: axis object
    """
    try:
        from tulip.graphics import newax
    except:
        logger.error('failed to import graphics.newax')
        return
    
    if ax is None:
        ax, fig = newax()
    
    plot_partition(plot_numbers=False, ax=ax, show=False)
    
    A = ssys.A
    B = ssys.B
    
    if ssys.K is not None:
        K = ssys.K
    else:
        K = np.zeros(x0.shape)
    
    x = x0.flatten()
    x_arr = x0
    for i in range(u_seq.shape[0]):
        x = np.dot(A, x).flatten() +\
            np.dot(B, u_seq[i, :] ).flatten() +\
            K.flatten()
        x_arr = np.vstack([x_arr, x.flatten()])
    
    ax.plot(x_arr[:,0], x_arr[:,1], 'o-')
    
    return ax
Beispiel #7
0
 def plot(self, ax=None, color=np.random.rand(3), show_domain=True):
     if quiver is None:
         warn('pyvectorized not found. No plotting.')
         return
     
     (x, res) = pc.grid_region(self.domain)
     n = self.A.shape[0]
     DA = self.A - np.eye(n)
     v = DA.dot(x)
     
     if ax is None:
         ax, fig = newax()
     
     if show_domain:
         self.domain.plot(ax, color)
     quiver(x, v, ax)
     
     return ax
Beispiel #8
0
    def plot(self, ax=None, color=np.random.rand(3), show_domain=True, res=(5, 5), **kwargs):
        try:
            from tulip.graphics import newax, quiver
        except:
            logger.error("failed to import graphics")
            warn("pyvectorized not found. No plotting.")
            return

        (x, res) = pc.grid_region(self.domain, res=res)
        n = self.A.shape[0]
        DA = self.A - np.eye(n)
        v = DA.dot(x) + self.K

        if ax is None:
            ax, fig = newax()

        if show_domain:
            self.domain.plot(ax, color)

        quiver(x, v, ax, **kwargs)

        return ax
Beispiel #9
0
    def plot_props(self, ax=None, text_color='yellow'):
        """Plot labeled regions of continuous propositions.
        """
        try:
            from tulip.graphics import newax
        except:
            logger.error('failed to import graphics')
            return

        if ax is None:
            ax, fig = newax()

        l, u = self.domain.bounding_box
        ax.set_xlim(l[0, 0], u[0, 0])
        ax.set_ylim(l[1, 0], u[1, 0])

        for (prop, poly) in self.prop_regions.iteritems():
            isect_poly = poly.intersect(self.domain)

            isect_poly.plot(ax, color='none', hatch='/')
            isect_poly.text(prop, ax, color=text_color)
        return ax
Beispiel #10
0
    def plot_props(self, ax=None, text_color='yellow'):
        """Plot labeled regions of continuous propositions.
        """
        try:
            from tulip.graphics import newax
        except:
            logger.error('failed to import graphics')
            return

        if ax is None:
            ax, fig = newax()

        l, u = self.domain.bounding_box
        ax.set_xlim(l[0,0], u[0,0])
        ax.set_ylim(l[1,0], u[1,0])

        for (prop, poly) in self.prop_regions.items():
            isect_poly = poly.intersect(self.domain)

            isect_poly.plot(ax, color='none', hatch='/')
            isect_poly.text(prop, ax, color=text_color)
        return ax
Beispiel #11
0
def plot_partition(
    ppp, trans=None, ppp2trans=None, only_adjacent=False,
    ax=None, plot_numbers=True, color_seed=None, show=False
):
    """Plot partition with arrows from digraph.
    
    For filtering edges based on label use L{plot_ts_on_partition}.

    See Also
    ========
    L{abstract.prop2partition.PropPreservingPartition}, L{plot_trajectory}

    @type ppp: L{PropPreservingPartition}
    
    @param trans: Transition matrix. If used,
        then transitions in C{ppp} are shown with arrows.
        Otherwise C{ppp.adj} is plotted.
        
        To show C{ppp.adj}, pass: trans = True
    
    @param plot_numbers: If True,
        then annotate each Region center with its number.
    
    @param show: If True, then show the plot.
        Otherwise return axis object.
        Axis object is good for creating custom plots.
    
    @param ax: axes where to plot
    
    @param color_seed: seed for reproducible random coloring
    
    @param ppp2trans: order mapping ppp indices to trans states
    @type ppp2trans: list of trans states
    """
    if mpl is None:
        warn('matplotlib not found')
        return
    
    # needs to be converted to adjacency matrix ?
    if isinstance(trans, nx.MultiDiGraph):
        if trans is not None and ppp2trans is None:
            msg = 'trans is a networkx MultiDiGraph, '
            msg += 'so ppp2trans required to define state order,\n'
            msg += 'used when converting the graph to an adjacency matrix.'
            raise Exception(msg)
        
        trans = nx.to_numpy_matrix(trans, nodelist=ppp2trans)
        trans = np.array(trans)
    
    l,u = ppp.domain.bounding_box
    arr_size = (u[0,0]-l[0,0])/50.0
    
    # new figure ?
    if ax is None:
        ax, fig = newax()
    
    # no trans given: use partition's
    if trans is True and ppp.adj is not None:
        ax.set_title('Adjacency from Partition')
        trans = ppp.adj
    elif trans is None:
        trans = 'none'
    else:
        ax.set_title('Adjacency from given Transitions')
    
    ax.set_xlim(l[0,0],u[0,0])
    ax.set_ylim(l[1,0],u[1,0])
    
    # repeatable coloring ?
    if color_seed is not None:
        prng = np.random.RandomState(color_seed)
    else:
        prng = np.random.RandomState()
    
    # plot polytope patches
    for i, reg in enumerate(ppp.regions):
        # select random color,
        # same color for all polytopes in each region
        col = prng.rand(3)
        
        # single polytope or region ?
        reg.plot(color=col, ax=ax)
        if plot_numbers:
            reg.text(str(i), ax, color='red')
    
    # not show trans ?
    if trans is 'none':
        if show:
            mpl.pyplot.show()
        return ax
    
    # plot transition arrows between patches
    rows, cols = np.nonzero(trans)
    for i, j in zip(rows, cols):
        # mask non-adjacent cell transitions ?
        if only_adjacent:
            if ppp.adj[i, j] == 0:
                continue
        
        plot_transition_arrow(ppp.regions[i], ppp.regions[j], ax, arr_size)
    
    if show:
        mpl.pyplot.show()
    
    return ax
Beispiel #12
0
def plot_partition(
    ppp, trans=None, ppp2trans=None, only_adjacent=False,
    ax=None, plot_numbers=True, color_seed=None
):
    """Plot partition with arrows from digraph.

    For filtering edges based on label use L{plot_ts_on_partition}.

    See Also
    ========
    L{abstract.prop2partition.PropPreservingPartition}, L{plot_trajectory}

    @type ppp: L{PropPreservingPartition}

    @param trans: Transition matrix. If used,
        then transitions in C{ppp} are shown with arrows.
        Otherwise C{ppp.adj} is plotted.

        To show C{ppp.adj}, pass: trans = True

    @param plot_numbers: If True,
        then annotate each Region center with its number.

    @param ax: axes where to plot

    @param color_seed: seed for reproducible random coloring

    @param ppp2trans: order mapping ppp indices to trans states
    @type ppp2trans: list of trans states
    """
    try:
        import matplotlib as mpl
        from tulip.graphics import newax
    except:
        logger.error('failed to import matplotlib')
        return

    # needs to be converted to adjacency matrix ?
    if isinstance(trans, nx.MultiDiGraph):
        if trans is not None and ppp2trans is None:
            msg = 'trans is a networkx MultiDiGraph, '
            msg += 'so ppp2trans required to define state order,\n'
            msg += 'used when converting the graph to an adjacency matrix.'
            raise Exception(msg)

        trans = nx.to_numpy_matrix(trans, nodelist=ppp2trans)
        trans = np.array(trans)

    l,u = ppp.domain.bounding_box
    arr_size = (u[0,0]-l[0,0])/50.0

    # new figure ?
    if ax is None:
        ax, fig = newax()

    # no trans given: use partition's
    if trans is True and ppp.adj is not None:
        ax.set_title('Adjacency from Partition')
        trans = ppp.adj
    elif trans is None:
        trans = 'none'
    else:
        ax.set_title('Adjacency from given Transitions')

    ax.set_xlim(l[0,0],u[0,0])
    ax.set_ylim(l[1,0],u[1,0])

    # repeatable coloring ?
    if color_seed is not None:
        prng = np.random.RandomState(color_seed)
    else:
        prng = np.random.RandomState()

    # plot polytope patches
    for i, reg in enumerate(ppp.regions):
        # select random color,
        # same color for all polytopes in each region
        col = prng.rand(3)

        # single polytope or region ?
        reg.plot(color=col, ax=ax)
        if plot_numbers:
            reg.text(str(i), ax, color='red')

    # not show trans ?
    if trans is 'none':
        mpl.pyplot.show()
        return ax

    # plot transition arrows between patches
    rows, cols = np.nonzero(trans)
    for i, j in zip(rows, cols):
        # mask non-adjacent cell transitions ?
        if only_adjacent:
            if ppp.adj[i, j] == 0:
                continue

        plot_transition_arrow(ppp.regions[i], ppp.regions[j], ax, arr_size)

    mpl.pyplot.show()

    return ax