Exemplo n.º 1
0
def display_graph_edge_labels(graph,
                              attr_name=None,
                              layer=None,
                              clear_layer=False,
                              color=None,
                              formatter=None):
    """"""
    if not attr_name:
        attr_name = 'key'

    colordict = color_to_colordict(color,
                                   graph.edges(),
                                   default=graph.attributes['color.edge'],
                                   colorformat='rgb',
                                   normalize=False)

    if formatter:
        if not callable(formatter):
            raise Exception('The provided formatter is not callable.')
    else:
        formatter = str

    labels = []

    for index, u, v, attr in graph.edges_enum(True):

        if attr_name == 'key':
            value = '{0}-{1}'.format(u, v)
        elif attr_name == 'index':
            value = index
        else:
            value = attr[attr_name]

        labels.append({
            'pos':
            graph.edge_midpoint(u, v),
            'text':
            formatter(value),
            'name':
            '{0}.edge.label.{1}-{2}'.format(graph.attributes['name'], u, v),
            'color':
            colordict[(u, v)],
        })

    compas_rhino.xdraw_labels(labels,
                              layer=layer,
                              clear=clear_layer,
                              redraw=True)
Exemplo n.º 2
0
    def draw_edgelabels(self, text=None, color=None):
        """Draw labels for selected edges of the mesh.

        Parameters
        ----------

        Notes
        -----

        Examples
        --------

        """
        if text is None:
            textdict = {(u, v): "{}-{}".format(u, v) for u, v in self.mesh.edges()}
        elif isinstance(text, dict):
            textdict = text
        else:
            raise NotImplementedError
        colordict = to_valuedict(list(textdict.keys()), color, self.defaults['edge.color'])
        labels = []
        for (u, v), text in iter(textdict.items()):
            labels.append({
                'pos'  : self.mesh.edge_midpoint(u, v),
                'name' : self.mesh.edge_name(u, v),
                'color': colordict[(u, v)],
                'text' : textdict[(u, v)],
            })
        return compas_rhino.xdraw_labels(labels, layer=self.layer, clear=False, redraw=False)
Exemplo n.º 3
0
    def draw_facelabels(self, text=None, color=None):
        """Draw labels for selected faces of the mesh.

        Parameters
        ----------

        Notes
        -----

        Examples
        --------

        """
        if text is None:
            textdict = {key: str(key) for key in self.mesh.faces()}
        elif isinstance(text, dict):
            textdict = text
        else:
            raise NotImplementedError
        colordict = to_valuedict(list(textdict.keys()), color, self.defaults['face.color'])
        labels = []
        for key, text in iter(textdict.items()):
            labels.append({
                'pos'  : self.mesh.face_center(key),
                'name' : self.mesh.face_name(key),
                'color': colordict[key],
                'text' : textdict[key],
            })
        return compas_rhino.xdraw_labels(labels, layer=self.layer, clear=False, redraw=False)
Exemplo n.º 4
0
def display_graph_face_labels(graph,
                              attr_name=None,
                              layer=None,
                              clear_layer=False,
                              color=None,
                              formatter=None):
    """"""
    if not attr_name:
        attr_name = 'key'

    colordict = color_to_colordict(color,
                                   graph.faces(),
                                   default=graph.attributes['color.face'],
                                   colorformat='rgb',
                                   normalize=False)

    if formatter:
        if not callable(formatter):
            raise Exception('The provided formatter is not callable.')
    else:
        formatter = str

    labels = []

    for index, fkey in graph.faces_enum():
        if attr_name == 'key':
            value = fkey
        elif attr_name == 'index':
            value = index
        else:
            value = graph.facedata[fkey][attr_name]

        labels.append({
            'pos':
            graph.face_centroid(fkey),
            'text':
            formatter(value),
            'name':
            '{0}.face.label.{1}'.format(graph.attributes['name'], fkey),
            'color':
            colordict[fkey]
        })

    compas_rhino.xdraw_labels(labels,
                              layer=layer,
                              clear=clear_layer,
                              redraw=True)
Exemplo n.º 5
0
def display_graph_vertex_labels(graph,
                                attr_name=None,
                                layer=None,
                                clear_layer=False,
                                color=None,
                                formatter=None):
    """"""
    if not attr_name:
        attr_name = 'key'

    colordict = color_to_colordict(color,
                                   graph.vertices(),
                                   default=graph.attributes['color.vertex'],
                                   colorformat='rgb',
                                   normalize=False)

    if formatter:
        if not callable(formatter):
            raise Exception('The provided formatter is not callable.')
    else:
        formatter = str

    labels = []

    for index, key, attr in graph.vertices_enum(True):
        if 'key' == attr_name:
            value = key
        elif 'index' == attr_name:
            value = index
        else:
            value = attr[attr_name]

        name = '{0}.vertex.label.{1}'.format(graph.attriutes['name'],
                                             repr(key))

        labels.append({
            'pos': graph.vertex_coordinates(key),
            'text': formatter(value),
            'name': name,
            'color': colordict[key],
        })

    compas_rhino.xdraw_labels(labels,
                              layer=layer,
                              clear=clear_layer,
                              redraw=True)
Exemplo n.º 6
0
    def draw_edgelabels(self, text=None, color=None):
        """Draw labels for a selection of edges.

        Parameters
        ----------
        text : dict
            A dictionary of edge labels as key-text pairs.
            The default value is ``None``, in which case every edge will be labelled with its key.
        color : str, tuple, dict
            The color sepcification of the labels.
            String values are interpreted as hex colors (e.g. ``'#ff0000'`` for red).
            Tuples are interpreted as RGB component specifications (e.g. ``(255, 0, 0) for red``.
            Individual colors can be assigned using a dictionary
            of key-color pairs. Missing keys will be assigned the default face
            color (``self.defaults['edge.color']``).
            The default is ``None``, in which case all edges are assigned the
            default edge color.

        Notes
        -----
        All labels are assigned a name using the folling template:
        ``"{}.edge.{}".format(self.datastructure.name, key)``.

        """
        if text is None:
            textdict = {(u, v): "{}-{}".format(u, v)
                        for u, v in self.datastructure.edges()}
        elif isinstance(text, dict):
            textdict = text
        else:
            raise NotImplementedError

        colordict = color_to_colordict(color,
                                       textdict.keys(),
                                       default=self.defaults.get('color.edge'),
                                       colorformat='rgb',
                                       normalize=False)
        labels = []

        for (u, v), text in iter(textdict.items()):
            labels.append({
                'pos':
                self.datastructure.edge_midpoint(u, v),
                'name':
                self.datastructure.edge_label_name(u, v),
                'color':
                colordict[(u, v)],
                'text':
                textdict[(u, v)],
                'layer':
                self.datastructure.get_edge_attribute((u, v), 'layer', None)
            })

        return compas_rhino.xdraw_labels(labels,
                                         layer=self.layer,
                                         clear=False,
                                         redraw=False)
Exemplo n.º 7
0
    def draw_vertexlabels(self, text=None, color=None):
        """Draw labels for a selection vertices.

        Parameters
        ----------
        text : dict
            A dictionary of vertex labels as key-text pairs.
            The default value is ``None``, in which case every vertex will be labelled with its key.
        color : str, tuple, dict
            The color sepcification of the labels.
            String values are interpreted as hex colors (e.g. ``'#ff0000'`` for red).
            Tuples are interpreted as RGB component specifications (e.g. ``(255, 0, 0) for red``.
            If a dictionary of specififcations is provided, the keys of the
            should refer to vertex keys and the values should be color
            specifications in the form of strings or tuples.
            The default value is ``None``, in which case the labels are assigned
            the default vertex color (``self.defaults['color.vertex']``).

        Notes
        -----
        All labels are assigned a name using the folling template:
        ``"{}.vertex.label.{}".format(self.datastructure.name, key)``.

        """
        if text is None:
            textdict = {key: str(key) for key in self.datastructure.vertices()}
        elif isinstance(text, dict):
            textdict = text
        else:
            raise NotImplementedError

        colordict = color_to_colordict(
            color,
            textdict.keys(),
            default=self.defaults.get('color.vertex'),
            colorformat='rgb',
            normalize=False)
        labels = []

        for key, text in iter(textdict.items()):
            labels.append({
                'pos':
                self.datastructure.vertex_coordinates(key),
                'name':
                self.datastructure.vertex_label_name(key),
                'color':
                colordict[key],
                'text':
                textdict[key],
                'layer':
                self.datastructure.get_vertex_attribute(key, 'layer', None)
            })

        return compas_rhino.xdraw_labels(labels,
                                         layer=self.layer,
                                         clear=False,
                                         redraw=False)
Exemplo n.º 8
0
    def draw_edgelabels(self, text=None, color=None):
        """Draw labels for selected edges of the network.

        Parameters
        ----------
        text : dict
            A dictionary of edge labels as key-text pairs.
            The default value is ``None``, in which case every edge of the network
            will be labelled with its key.
        color : str, tuple, dict
            The color sepcification of the labels.
            String values are interpreted as hex colors (e.g. ``'#ff0000'`` for red).
            Tuples are interpreted as RGB component specifications (e.g. ``(255, 0, 0) for red``.
            If a dictionary of specififcations is provided, the keys of the
            should refer to edge keys in the network and the values should be color
            specifications in the form of strings or tuples.
            The default value is ``None``, in which case the labels are assigned
            the default edge color (``self.defaults['color.edge']``).

        Notes
        -----
        All labels are assigned a name using the folling template:
        ``"{}.edge.{}".format(self.datastructure.name, key)``.

        Examples
        --------
        >>>

        """
        if text is None:
            textdict = {(u, v): "{}-{}".format(u, v)
                        for u, v in self.datastructure.edges()}
        elif isinstance(text, dict):
            textdict = text
        else:
            raise NotImplementedError

        colordict = color_to_colordict(color,
                                       textdict.keys(),
                                       default=self.defaults['color.edge'],
                                       colorformat='rgb',
                                       normalize=False)
        labels = []

        for (u, v), text in iter(textdict.items()):
            labels.append({
                'pos': self.datastructure.edge_midpoint(u, v),
                'name': self.datastructure.edge_name(u, v),
                'color': colordict[(u, v)],
                'text': textdict[(u, v)],
            })

        return compas_rhino.xdraw_labels(labels,
                                         layer=self.layer,
                                         clear=False,
                                         redraw=False)
Exemplo n.º 9
0
def display_mesh_edge_labels(mesh,
                             attr_name=None,
                             layer=None,
                             color=None,
                             formatter=None):
    """Display labels for the edges of a mesh.

    Parameters:
        mesh (compas.datastructures.mesh.Mesh): The mesh object.
        attr_name (str): Optional. The name of the attribute value to display in the label.
            Default is ``None``. If ``None``, the key of the edge is displayed.
        layer (str): Optional. The layer to draw in. Default is ``None``.
        color (str, tuple, list, dict): Optional. The color specification. Default is ``None``.
            The following values are supported:

                * str: A HEX color. For example, ``'#ff0000'``.
                * tuple, list: RGB color. For example, ``(255, 0, 0)``.
                * dict: A dictionary of RGB and/or HEX colors.

            If ``None``, the default edge color of the mesh will be used.
        formatter (callable): Optional. A formatting function. Default is ``None``.

    Example:

        .. code-block:: python

            import compas
            import compas_rhino as rhino

            from compas.datastructures.mesh import Mesh

            mesh = Mesh.from_obj(compas.get_data('faces.obj'))

            compas_rhino.display_mesh_edge_labels(mesh)


    See Also:
        * :func:`display_mesh_vertex_labels`
        * :func:`display_mesh_face_labels`

    """
    compas_rhino.delete_objects(
        compas_rhino.get_objects(
            name="{0}.edge.label.*".format(mesh.attributes['name'])))

    if not attr_name:
        attr_name = 'key'

    colordict = color_to_colordict(color,
                                   mesh.edges(),
                                   default=mesh.attributes['color.edge'],
                                   colorformat='rgb',
                                   normalize=False)
    if formatter:
        if not callable(formatter):
            raise Exception('The provided formatter is not callable.')
    else:
        formatter = str

    labels = []

    for index, (u, v, attr) in enumerate(mesh.edges(True)):

        if attr_name == 'key':
            value = '{0}-{1}'.format(u, v)
        elif attr_name == 'index':
            value = index
        else:
            value = attr[attr_name]

        labels.append({
            'pos':
            mesh.edge_midpoint(u, v),
            'text':
            formatter(value),
            'name':
            '{0}.edge.label.{1}-{2}'.format(mesh.attributes['name'], u, v),
            'color':
            colordict[(u, v)],
        })

    compas_rhino.xdraw_labels(labels, layer=layer, clear=False, redraw=True)
Exemplo n.º 10
0
def display_network_face_labels(network, attr_name=None, layer=None, color=None, formatter=None):
    """Display labels for the faces of a network.

    Parameters:
        network (compas.datastructures.network.Network): The network object.
        attr_name (str): Optional. The name of the attribute value to display in the label.
            Default is ``None``. If ``None``, the key of the face is displayed.
        layer (str): Optional. The layer to draw in. Default is ``None``.
        color (str, tuple, list, dict): Optional. The color specification. Default is ``None``.
            The following values are supported:

                * str: A HEX color. For example, ``'#ff0000'``.
                * tuple, list: RGB color. For example, ``(255, 0, 0)``.
                * dict: A dictionary of RGB and/or HEX colors.

            If ``None``, the default face color of the network will be used.
        formatter (callable): Optional. A formatting function. Default is ``None``.

    Example:

        .. code-block:: python

            import compas
            import compas_rhino as compas_rhino

            from compas.datastructures.network import Network

            network = Network.from_obj(compas.get_data('lines.obj'))

            compas_compas_rhino.display_network_face_labels(network)


    See Also:
        * :func:`display_network_vertex_labels`
        * :func:`display_network_edge_labels`

    """
    compas_rhino.delete_objects(compas_rhino.get_objects(name="{0}.face.label.*".format(network.attributes['name'])))

    if not attr_name:
        attr_name = 'key'

    colordict = color_to_colordict(color,
                                   network.faces(),
                                   default=network.attributes['color.face'],
                                   colorformat='rgb',
                                   normalize=False)

    if formatter:
        if not callable(formatter):
            raise Exception('The provided formatter is not callable.')
    else:
        formatter = str

    labels = []

    for index, fkey in enumerate(network.faces()):
        if attr_name == 'key':
            value = fkey
        elif attr_name == 'index':
            value = index
        else:
            value = network.facedata[fkey][attr_name]

        labels.append({
            'pos'  : network.face_centroid(fkey),
            'text' : formatter(value),
            'name' : '{0}.face.label.{1}'.format(network.attributes['name'], fkey),
            'color': colordict[fkey]
        })

    compas_rhino.xdraw_labels(
        labels,
        layer=layer,
        clear=False,
        redraw=True
    )
Exemplo n.º 11
0
def draw_network(network,
                 layer=None,
                 clear_layer=False,
                 vertexcolor=None,
                 edgecolor=None,
                 edgelabel=None):
    """Draw a network data structure in Rhino.

    Parameters:
        network (compas.datastructures.network.Network): The network object.
        layer (str): Optional. The layer to draw in. Default is ``None``. If
            ``None``, the currenlt layer is used.
        clear_layer (bool): Optional. Clear the layer if ``True``. Default is ``False``.
        vertexcolor (list, tuple, str, dict): Optional. The color specification
            for the vertices. Default is ``None``.

                * list, tuple: rgb color, with color specs between 0 and 255 (e.g. ``(255, 0, 0)``).
                * str: hex color (e.g. ``'#ff0000'``).
                * dict: dictionary of hex or rgb colors.

        edgecolor (list, tuple, str, dict): Optional. The color specification
            for the edges. Default is ``None``.

                * list, tuple: rgb color, with color specs between 0 and 255 (e.g. ``(255, 0, 0)``).
                * str: hex color (e.g. ``'#ff0000'``).
                * dict: dictionary of hex or rgb color.

    Note:
        * Any network objects with the same name that are already present in the
          model will be deleted by this function.
        * To also clear the entire layer the network will be drawn on, for
          example, if you have a dedicated network layer, use the ``clear_layer`` flag as well.

    See Also:
        * :class:`compas.datastructures.network.Network`
        * :func:`compas_compas_rhino.utilities.drawing.xdraw_lines`
        * :func:`compas_compas_rhino.utilities.drawing.xdraw_points`

    Example:

        .. code-block:: python
            :emphasize-lines: 7

            import compas
            from compas.datastructures.network import Network
            import compas_rhino as compas_rhino

            network = Network.from_obj(compas.get_data('lines.obj'))

            compas_compas_rhino.draw_network(network)

    """
    vertexcolor = color_to_colordict(vertexcolor,
                                     network.vertices(),
                                     default=network.attributes['color.vertex'],
                                     colorformat='rgb',
                                     normalize=False)

    edgecolor = color_to_colordict(edgecolor,
                                   network.edges(),
                                   default=network.attributes['color.edge'],
                                   colorformat='rgb',
                                   normalize=False)

    edgelabel = edgelabel or {}

    points = []
    for key, attr in network.vertices(True):
        points.append({
            'pos'  : network.vertex_coordinates(key),
            'name' : '{0}.vertex.{1}'.format(network.attributes['name'], repr(key)),
            'color': vertexcolor[key]
        })

    lines = []
    for u, v, attr in network.edges(True):
        lines.append({
            'start': network.vertex_coordinates(u),
            'end'  : network.vertex_coordinates(v),
            'name' : '{0}.edge.{1}-{2}'.format(network.attributes['name'], repr(u), repr(v)),
            'color': edgecolor[(u, v)]
        })

    labels = []
    for (u, v), text in edgelabel.items():
        labels.append({
            'pos'  : network.edge_midpoint(u, v),
            'text' : str(text),
            'name' : '{0}.edge.label.{1}-{2}'.format(network.attributes['name'], repr(u), repr(v)),
            'color': edgecolor[(u, v)],
        })

    guids = compas_rhino.get_objects(name='{0}.*'.format(network.attributes['name']))
    compas_rhino.delete_objects(guids)

    compas_rhino.xdraw_points(
        points,
        layer=layer,
        clear=clear_layer,
        redraw=False
    )
    compas_rhino.xdraw_lines(
        lines,
        layer=layer,
        clear=False,
        redraw=False
    )
    compas_rhino.xdraw_labels(
        labels,
        layer=layer,
        clear=False,
        redraw=True
    )