コード例 #1
0
ファイル: networkartist.py プロジェクト: DruidTin/compas
    def draw_nodelabels(self, text=None, color=None):
        """Draw labels for a selection nodes.

        Parameters
        ----------
        text : dict
            A dictionary of node labels as key-text pairs.
            The default value is ``None``, in which case every node will be labelled with its key.
        color : str, tuple, dict
            The color sepcification of the labels.
            String values are interpreted as hex colors.
            Tuples are interpreted as RGB component specifications.
            If a dictionary of specififcations is provided,
            the keys of the should refer to node 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 node color (``self.settings['color.nodes']``).

        Returns
        -------
        list
            The GUIDs of the created Rhino objects.

        """
        if text is None:
            textdict = {key: str(key) for key in self.network.nodes()}
        elif isinstance(text, dict):
            textdict = text
        elif text == 'key':
            textdict = {key: str(key) for key in self.network.nodes()}
        elif text == 'index':
            textdict = {
                key: str(index)
                for index, key in enumerate(self.network.nodes())
            }
        else:
            raise NotImplementedError

        colordict = color_to_colordict(color,
                                       textdict.keys(),
                                       default=self.settings['color.nodes'],
                                       colorformat='rgb',
                                       normalize=False)
        labels = []
        for key, text in iter(textdict.items()):
            labels.append({
                'pos':
                self.network.node_coordinates(key),
                'name':
                "{}.nodelabel.{}".format(self.network.name, key),
                'color':
                colordict[key],
                'text':
                textdict[key]
            })

        guids = compas_rhino.draw_labels(labels,
                                         layer=self.layer,
                                         clear=False,
                                         redraw=False)
        self.guids += guids
        return guids
コード例 #2
0
    def draw_vertices(self, keys=None, color=None):
        """Draw a selection of vertices.

        Parameters
        ----------
        keys : list
            A list of vertex keys identifying which vertices to draw.
            Default is ``None``, in which case all vertices are drawn.
        color : str, tuple, dict
            The color specififcation for the vertices.
            Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
            To apply the same color to all vertices, provide a single color specification.
            Individual colors can be assigned using a dictionary of key-color pairs.
            Missing keys will be assigned the default vertex color (``self.settings['color.vertices']``).
            The default is ``None``, in which case all vertices are assigned the default vertex color.

        Returns
        -------
        list of :class:`Rhino.Geometry.Point3d`

        """
        vertices = keys or list(self.mesh.vertices())
        colordict = color_to_colordict(color,
                                       vertices,
                                       default=self.settings['color.vertices'],
                                       colorformat='rgb',
                                       normalize=False)
        points = []
        for vertex in vertices:
            points.append({
                'pos': self.mesh.vertex_coordinates(vertex),
                'name': "{}.vertex.{}".format(self.mesh.name, vertex),
                'color': colordict[vertex]
            })
        return compas_ghpython.draw_points(points)
コード例 #3
0
    def draw_faces(self, keys=None, color=None, join_faces=False):
        """Draw a selection of faces.

        Parameters
        ----------
        fkeys : list
            A list of face keys identifying which faces to draw.
            The default is ``None``, in which case all faces are drawn.
        color : str, tuple, dict
            The color specififcation for the faces.
            Colors should be specified in the form of a string (hex colors) or
            as a tuple of RGB components.
            To apply the same color to all faces, provide a single color
            specification. Individual colors can be assigned using a dictionary
            of key-color pairs. Missing keys will be assigned the default face
            color (``self.defaults['face.color']``).
            The default is ``None``, in which case all faces are assigned the
            default face color.

        Notes
        -----
        The faces are named using the following template:
        ``"{}.face.{}".format(self.datastructure.name, key)``.
        This name is used afterwards to identify faces in the Rhino model.

        """
        keys = keys or list(self.datastructure.faces())

        colordict = color_to_colordict(color,
                                       keys,
                                       default=self.defaults.get('color.face'),
                                       colorformat='rgb',
                                       normalize=False)
        faces = []
        for fkey in keys:
            faces.append({
                'points':
                self.datastructure.face_coordinates(fkey),
                'name':
                self.datastructure.face_name(fkey),
                'color':
                colordict[fkey],
                'layer':
                self.datastructure.face_attribute(fkey, 'layer', None)
            })

        guids = compas_rhino.draw_faces(faces,
                                        layer=self.layer,
                                        clear=False,
                                        redraw=False)
        if not join_faces:
            return guids
        guid = rs.JoinMeshes(guids, delete_input=True)
        rs.ObjectLayer(guid, self.layer)
        rs.ObjectName(guid, '{}.mesh'.format(self.datastructure.name))
        if color:
            rs.ObjectColor(guid, color)
        return guid
コード例 #4
0
ファイル: vertexartist.py プロジェクト: sehlstrom/compas
    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)
コード例 #5
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)
コード例 #6
0
ファイル: edgeartist.py プロジェクト: tclim/compas
    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)
コード例 #7
0
ファイル: meshartist.py プロジェクト: irfanirw/compas
    def draw_faces(self, keys=None, color=None, join_faces=False):
        """Draw a selection of faces.

        Parameters
        ----------
        fkeys : list
            A list of face keys identifying which faces to draw.
            The default is ``None``, in which case all faces are drawn.
        color : str, tuple, dict
            The color specififcation for the faces.
            Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
            To apply the same color to all faces, provide a single color specification.
            Individual colors can be assigned using a dictionary of key-color pairs.
            Missing keys will be assigned the default face color (``self.settings['color.faces']``).
            The default is ``None``, in which case all faces are assigned the default face color.
        join_faces : bool, optional
            Join the faces into 1 mesh.
            Default is ``False``, in which case the faces are drawn as individual meshes.

        Returns
        -------
        list
            The GUIDs of the created Rhino objects.

        """
        faces = keys or list(self.mesh.faces())
        face_color = color_to_colordict(color,
                                        faces,
                                        default=self.settings['color.faces'],
                                        colorformat='rgb',
                                        normalize=False)
        facets = []
        for face in faces:
            facets.append({
                'points': self.mesh.face_coordinates(face),
                'name': "{}.face.{}".format(self.mesh.name, face),
                'color': face_color[face]
            })

        guids = compas_rhino.draw_faces(facets,
                                        layer=self.layer,
                                        clear=False,
                                        redraw=False)
        if not join_faces:
            self.guid_face = zip(guids, faces)
            return guids

        guid = compas_rhino.rs.JoinMeshes(guids, delete_input=True)
        compas_rhino.rs.ObjectLayer(guid, self.layer)
        compas_rhino.rs.ObjectName(guid, '{}.mesh'.format(self.mesh.name))
        if color:
            compas_rhino.rs.ObjectColor(guid, color)

        self.guids += [guid]
        return [guid]
コード例 #8
0
    def draw_edges(self, keys=None, color=None):
        """Draw a selection of edges.

        Parameters
        ----------
        keys : list
            A list of edge keys (as uv pairs) identifying which edges to draw.
            The default is ``None``, in which case all edges are drawn.
        color : str, tuple, dict
            The color specififcation for the edges.
            Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
            To apply the same color to all edges, provide a single color specification.
            Individual colors can be assigned using a dictionary of key-color pairs.
            Missing keys will be assigned the default edge color (``self.settings['edge.color']``).
            The default is ``None``, in which case all edges are assigned the default edge color.

        Returns
        -------
        list
            The GUIDs of the created Rhino objects.

        Notes
        -----
        All edges are named using the following template: ``"{network.name}.edge.{u}-{v}"``.
        This name can be used afterwards to identify edges in the Rhino model.

        """
        keys = keys or list(self.network.edges())
        colordict = color_to_colordict(
            color,
            keys,
            default=self.settings.get('color.edges'),
            colorformat='rgb',
            normalize=False)
        lines = []
        for u, v in keys:
            lines.append({
                'start':
                self.network.node_coordinates(u),
                'end':
                self.network.node_coordinates(v),
                'color':
                colordict[(u, v)],
                'name':
                "{}.edge.{}-{}".format(self.network.name, u, v),
                'layer':
                self.network.edge_attribute((u, v), 'layer', None)
            })

        guids = compas_rhino.draw_lines(lines,
                                        layer=self.layer,
                                        clear=False,
                                        redraw=False)
        self.guids += guids
        return guids
コード例 #9
0
ファイル: meshartist.py プロジェクト: irfanirw/compas
    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.
            Tuples are interpreted as RGB component specifications.
            Individual colors can be assigned using a dictionary of edge-color pairs.
            Missing keys will be assigned the default edge color (``self.settings['color.edges']``).
            The default is ``None``, in which case all edges are assigned the default edge color.

        Returns
        -------
        list
            The GUIDs of the created Rhino objects.

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

        edge_color = color_to_colordict(color,
                                        edge_text.keys(),
                                        default=self.settings['color.edges'],
                                        colorformat='rgb',
                                        normalize=False)
        labels = []
        for edge in edge_text:
            labels.append({
                'pos':
                self.mesh.edge_midpoint(*edge),
                'name':
                "{}.edgelabel.{}-{}".format(self.mesh.name, *edge),
                'color':
                edge_color[edge],
                'text':
                edge_text[edge]
            })

        guids = compas_rhino.draw_labels(labels,
                                         layer=self.layer,
                                         clear=False,
                                         redraw=False)
        self.guid_edgelabel = zip(guids, edge_text.keys())
        return guids
コード例 #10
0
ファイル: meshartist.py プロジェクト: fstwn/compas
    def draw_facelabels(self, text=None, color=None):
        """Draw labels for a selection of faces.

        Parameters
        ----------
        text : dict
            A dictionary of face labels as key-text pairs.
            The default value is ``None``, in which case every face 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 face 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 face color (``self.settings['color.face']``).

        Notes
        -----
        The face labels are named using the following template:
        ``"{}.face.label.{}".format(self.mesh.name, key)``.
        This name is used afterwards to identify faces and face labels in the Rhino model.

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

        colordict = color_to_colordict(color,
                                       textdict.keys(),
                                       default=self.settings.get('color.face'),
                                       colorformat='rgb',
                                       normalize=False)

        labels = []
        for key, text in iter(textdict.items()):
            labels.append({
                'pos':
                self.mesh.face_center(key),
                'name':
                "{}.face.label.{}".format(self.mesh.name, key),
                'color':
                colordict[key],
                'text':
                textdict[key]
            })
        return compas_rhino.draw_labels(labels,
                                        layer=self.layer,
                                        clear=False,
                                        redraw=False)
コード例 #11
0
ファイル: edgeartist.py プロジェクト: tclim/compas
    def draw_edges(self, keys=None, color=None):
        """Draw a selection of edges of the network.

        Parameters
        ----------
        keys : list
            A list of edge keys (as uv pairs) identifying which edges to draw.
            The default is ``None``, in which case all edges are drawn.
        color : str, tuple, dict
            The color specififcation for the edges.
            Colors should be specified in the form of a string (hex colors) or
            as a tuple of RGB components.
            To apply the same color to all faces, provide a single color
            specification. Individual colors can be assigned using a dictionary
            of key-color pairs. Missing keys will be assigned the default face
            color (``self.defaults['face.color']``).
            The default is ``None``, in which case all faces are assigned the
            default edge color.

        Notes
        -----
        All edges are named using the following template:
        ``"{}.edge.{}-{}".fromat(self.datastructure.name, u, v)``.
        This name is used afterwards to identify edges of the network in the Rhino model.

        Examples
        --------
        >>> artist.draw_edges()
        >>> artist.draw_edges(color='#ff0000')
        >>> artist.draw_edges(color=(255, 0, 0))
        >>> artist.draw_edges(keys=self.datastructure.edges_xxx())
        >>> artist.draw_edges(color={(u, v): '#00ff00' for u, v in self.datastructure.edges_xxx()})

        """
        keys = keys or list(self.datastructure.edges())
        colordict = color_to_colordict(color,
                                       keys,
                                       default=self.defaults['color.edge'],
                                       colorformat='rgb',
                                       normalize=False)
        lines = []
        for u, v in keys:
            lines.append({
                'start': self.datastructure.vertex_coordinates(u),
                'end': self.datastructure.vertex_coordinates(v),
                'color': colordict[(u, v)],
                'name': self.datastructure.edge_name(u, v)
            })
        return compas_rhino.xdraw_lines(lines,
                                        layer=self.layer,
                                        clear=False,
                                        redraw=False)
コード例 #12
0
ファイル: faceartist.py プロジェクト: yishizu/compas
    def draw_faces(self, keys=None, color=None, join_faces=False):
        """Draw a selection of faces.

        Parameters
        ----------
        fkeys : list
            A list of face keys identifying which faces to draw.
            The default is ``None``, in which case all faces are drawn.
        color : str, tuple, dict
            The color specififcation for the faces.
            Colors should be specified in the form of a string (hex colors) or
            as a tuple of RGB components.
            To apply the same color to all faces, provide a single color
            specification. Individual colors can be assigned using a dictionary
            of key-color pairs. Missing keys will be assigned the default face
            color (``self.defaults['face.color']``).
            The default is ``None``, in which case all faces are assigned the
            default face color.

        Notes
        -----
        The faces are named using the following template:
        ``"{}.face.{}".format(self.datastructure.name, key)``.

        """
        keys = keys or list(self.datastructure.faces())

        colordict = color_to_colordict(color,
                                       keys,
                                       default=self.defaults.get('color.face'),
                                       colorformat='rgb',
                                       normalize=False)
        faces = []
        for fkey in keys:
            faces.append({
                'points':
                self.datastructure.face_coordinates(fkey),
                'name':
                "{}.face.{}".format(self.datastructure.name, fkey),
                'color':
                colordict[fkey],
                'layer':
                self.datastructure.face_attribute(fkey, 'layer')
            })

        meshes = compas_ghpython.draw_faces(faces)
        if not join_faces:
            return meshes
        else:
            joined_mesh = Rhino.Geometry.Mesh()
            [joined_mesh.Append(mesh) for mesh in meshes]
            return joined_mesh
コード例 #13
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.settings['color.edges']``).
            The default is ``None``, in which case all edges are assigned the
            default edge color.

        Returns
        -------
        list of :class:`Rhino.Geometry.TextDot`

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

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

        for (u, v), text in iter(textdict.items()):
            labels.append({
                'pos':
                self.volmesh.edge_midpoint(u, v),
                'name':
                "{}.edgelabel.{}-{}".format(self.volmesh.name, u, v),
                'color':
                colordict[(u, v)],
                'text':
                textdict[(u, v)]
            })

        return compas_ghpython.draw_labels(labels)
コード例 #14
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.
            Tuples are interpreted as RGB component specifications.
            Individual colors can be assigned using a dictionary of key-color pairs.
            Missing keys will be assigned the default face color (``self.settings['edge.color']``).
            The default is ``None``, in which case all edges are assigned the default edge color.

        Returns
        -------
        list
            The GUIDs of the created Rhino objects.

        Notes
        -----
        The edge labels are named using the following template: ``"{mesh.name}.edge_label.{u}-{v}"``.
        This name can be used afterwards to identify edges in the Rhino model.

        """
        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 = color_to_colordict(color,
                                       textdict.keys(),
                                       default=self.settings.get('color.edges'),
                                       colorformat='rgb',
                                       normalize=False)
        labels = []
        for (u, v), text in iter(textdict.items()):
            labels.append({
                'pos': self.mesh.edge_midpoint(u, v),
                'name': "{}.edge_label.{}-{}".format(self.mesh.name, u, v),
                'color': colordict[(u, v)],
                'text': textdict[(u, v)]})

        guids = compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False)
        self.guids += guids
        return guids
コード例 #15
0
    def draw_facelabels(self, text=None, color=None):
        """Draw labels for a selection of faces.

        Parameters
        ----------
        text : dict
            A dictionary of face labels as key-text pairs.
            The default value is ``None``, in which case every face 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 face 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 face color (``self.settings['color.faces']``).

        Returns
        -------
        list of :class:`Rhino.Geometry.TextDot`

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

        colordict = color_to_colordict(color,
                                       textdict.keys(),
                                       default=self.settings['color.faces'],
                                       colorformat='rgb',
                                       normalize=False)

        labels = []
        for key, text in iter(textdict.items()):
            labels.append({
                'pos':
                self.volmesh.face_center(key),
                'name':
                "{}.facelabel.{}".format(self.volmesh.name, key),
                'color':
                colordict[key],
                'text':
                textdict[key]
            })
        return compas_ghpython.draw_labels(labels)
コード例 #16
0
    def draw_vertices(self, keys=None, color=None):
        """Draw a selection of vertices.

        Parameters
        ----------
        keys : list
            A list of vertex keys identifying which vertices to draw.
            Default is ``None``, in which case all vertices are drawn.
        color : str, tuple, dict
            The color specififcation for the vertices.
            Colors should be specified in the form of a string (hex colors) or
            as a tuple of RGB components.
            To apply the same color to all vertices, provide a single color
            specification. Individual colors can be assigned using a dictionary
            of key-color pairs. Missing keys will be assigned the default vertex
            color (``self.defaults['color.vertex']``).
            The default is ``None``, in which case all vertices are assigned the
            default vertex color.

        Notes
        -----
        The vertices are named using the following template:
        ``"{}.vertex.{}".format(self.datastructure.name], key)``.
        This name is used afterwards to identify vertices in the Rhino model.

        """
        keys = keys or list(self.datastructure.vertices())
        colordict = color_to_colordict(
            color,
            keys,
            default=self.defaults.get('color.vertex'),
            colorformat='rgb',
            normalize=False)
        points = []
        for key in keys:
            points.append({
                'pos':
                self.datastructure.vertex_coordinates(key),
                'name':
                self.datastructure.vertex_name(key),
                'color':
                colordict[key],
                'layer':
                self.datastructure.get_vertex_attribute(key, 'layer', None)
            })
        return compas_rhino.draw_points(points,
                                        layer=self.layer,
                                        clear=False,
                                        redraw=False)
コード例 #17
0
ファイル: artists.py プロジェクト: ytakzk/compas_assembly
    def draw_interfaces(self, keys=None, color=None):
        """Draw the interfaces between the blocks.

        Parameters
        ----------
        keys : list
            A list of interface identifiers (i.e. assembly edge (u, v) tuples).
            Default is ``None``, in which case all interfaces are drawn.
        color : str, tuple, dict
            The color specififcation for the interfaces.
            Colors should be specified in the form of a string (hex colors) or
            as a tuple of RGB components.
            To apply the same color to all interfaces, provide a single color
            specification. Individual colors can be assigned using a dictionary
            of key-color pairs. Missing keys will be assigned the default interface
            color (``self.defaults['color.interface']``).
            The default is ``None``, in which case all interfaces are assigned the
            default interface color.

        Notes
        -----
        * Interfaces are drawn as mesh faces.
        * Interfaces are drawn on a sub-layer *Interfaces* of the base layer, if a base layer was provided.
        * Interface names have the following pattern: ``"{assembly_name}.interface.{from block_id}-{to block_id}"``
        * Interfaces have a direction, as suggested by the naming convention.

        """
        layer = "{}::Interfaces".format(self.layer) if self.layer else None
        faces = []

        keys = keys or list(self.assembly.edges())
        colordict = color_to_colordict(
            color,
            keys,
            default=self.defaults.get('color.interface'),
            colorformat='rgb',
            normalize=False)

        for u, v, attr in self.assembly.edges(True):
            faces.append({
                'points':
                attr['interface_points'],
                'name':
                "{}.interface.{}-{}".format(self.assembly.name, u, v),
                'color':
                colordict[(u, v)]
            })
        compas_rhino.xdraw_faces(faces, layer=layer, clear=False, redraw=False)
コード例 #18
0
    def draw_edges(self, keys=None, color=None):
        """Draw a selection of edges.

        Parameters
        ----------
        keys : list
            A list of edge keys (as uv pairs) identifying which edges to draw.
            The default is ``None``, in which case all edges are drawn.
        color : str, tuple, dict
            The color specififcation for the edges.
            Colors should be specified in the form of a string (hex colors) or
            as a tuple of RGB components.
            To apply the same color to all edges, provide a single color
            specification. 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 edges are named using the following template:
        ``"{}.edge.{}-{}".fromat(self.datastructure.name, u, v)``.
        This name is used afterwards to identify edges in the Rhino model.

        """
        keys = keys or list(self.datastructure.edges())
        colordict = color_to_colordict(color,
                                       keys,
                                       default=self.defaults.get('color.edge'),
                                       colorformat='rgb',
                                       normalize=False)
        lines = []
        for u, v in keys:
            start, end = self.datastructure.edge_coordinates(u, v)
            lines.append({
                'start':
                start,
                'end':
                end,
                'color':
                colordict[(u, v)],
                'name':
                "{}.edge.{}-{}".format(self.datastructure.name, u, v),
                'layer':
                self.datastructure.edge_attribute((u, v), 'layer')
            })
        return compas_ghpython.draw_lines(lines)
コード例 #19
0
    def draw_faces(self, keys=None, color=None, join_faces=False):
        """Draw a selection of faces.

        Parameters
        ----------
        fkeys : list
            A list of face keys identifying which faces to draw.
            The default is ``None``, in which case all faces are drawn.
        color : str, tuple, dict
            The color specififcation for the faces.
            Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
            To apply the same color to all faces, provide a single color specification.
            Individual colors can be assigned using a dictionary of key-color pairs.
            Missing keys will be assigned the default face color (``self.settings['color.faces']``).
            The default is ``None``, in which case all faces are assigned the default face color.

        Returns
        -------
        list of :class:`Rhino.Geometry.Mesh`

        """
        keys = keys or list(self.mesh.faces())

        colordict = color_to_colordict(color,
                                       keys,
                                       default=self.settings['color.faces'],
                                       colorformat='rgb',
                                       normalize=False)
        faces = []
        for fkey in keys:
            faces.append({
                'points': self.mesh.face_coordinates(fkey),
                'name': "{}.face.{}".format(self.mesh.name, fkey),
                'color': colordict[fkey]
            })

        meshes = compas_ghpython.draw_faces(faces)
        if not join_faces:
            return meshes

        joined_mesh = Rhino.Geometry.Mesh()
        for mesh in meshes:
            joined_mesh.Append(mesh)
        return [joined_mesh]
コード例 #20
0
ファイル: meshartist.py プロジェクト: irfanirw/compas
    def draw_edges(self, keys=None, color=None):
        """Draw a selection of edges.

        Parameters
        ----------
        keys : list
            A list of edge keys (as uv pairs) identifying which edges to draw.
            The default is ``None``, in which case all edges are drawn.
        color : str, tuple, dict
            The color specififcation for the edges.
            Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
            To apply the same color to all edges, provide a single color specification.
            Individual colors can be assigned using a dictionary of key-color pairs.
            Missing keys will be assigned the default edge color (``self.settings['color.edges']``).
            The default is ``None``, in which case all edges are assigned the default edge color.

        Returns
        -------
        list
            The GUIDs of the created Rhino objects.

        """
        edges = keys or list(self.mesh.edges())
        edge_color = color_to_colordict(color,
                                        edges,
                                        default=self.settings['color.edges'],
                                        colorformat='rgb',
                                        normalize=False)
        lines = []
        for edge in edges:
            lines.append({
                'start': self.mesh.vertex_coordinates(edge[0]),
                'end': self.mesh.vertex_coordinates(edge[1]),
                'color': edge_color[edge],
                'name': "{}.edge.{}-{}".format(self.mesh.name, *edge)
            })

        guids = compas_rhino.draw_lines(lines,
                                        layer=self.layer,
                                        clear=False,
                                        redraw=False)
        self.guid_edge = zip(guids, edges)
        return guids
コード例 #21
0
ファイル: networkartist.py プロジェクト: DruidTin/compas
    def draw_nodes(self, keys=None, color=None):
        """Draw a selection of nodes.

        Parameters
        ----------
        keys : list
            A list of node keys identifying which nodes to draw.
            Default is ``None``, in which case all nodes are drawn.
        color : str, tuple, dict
            The color specififcation for the nodes.
            Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
            To apply the same color to all nodes, provide a single color specification.
            Individual colors can be assigned using a dictionary of key-color pairs.
            Missing keys will be assigned the default node color (``self.settings['color.nodes']``).
            The default is ``None``, in which case all nodes are assigned the default node color.

        Returns
        -------
        list
            The GUIDs of the created Rhino objects.

        """
        nodes = keys or list(self.network.nodes())
        node_color = color_to_colordict(color,
                                        nodes,
                                        default=self.settings['color.nodes'],
                                        colorformat='rgb',
                                        normalize=False)
        points = []
        for node in nodes:
            points.append({
                'pos': self.network.node_coordinates(node),
                'name': "{}.node.{}".format(self.network.name, node),
                'color': node_color[node]
            })

        guids = compas_rhino.draw_points(points,
                                         layer=self.layer,
                                         clear=False,
                                         redraw=False)
        self.guid_node = zip(guids, nodes)
        return guids
コード例 #22
0
    def draw_edges(self, keys=None, color=None):
        """Draw a selection of edges.

        Parameters
        ----------
        keys : list
            A list of edge keys (as uv pairs) identifying which edges to draw.
            The default is ``None``, in which case all edges are drawn.
        color : str, tuple, dict
            The color specififcation for the edges.
            Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
            To apply the same color to all edges, provide a single color specification.
            Individual colors can be assigned using a dictionary of key-color pairs.
            Missing keys will be assigned the default face color (``self.settings['color.edges']``).
            The default is ``None``, in which case all edges are assigned the default edge color.

        Returns
        -------
        list of :class:`Rhino.Geometry.Line`

        """
        edges = keys or list(self.volmesh.edges())
        colordict = color_to_colordict(color,
                                       edges,
                                       default=self.settings['color.edges'],
                                       colorformat='rgb',
                                       normalize=False)
        lines = []
        for edge in edges:
            start, end = self.volmesh.edge_coordinates(*edge)
            lines.append({
                'start':
                start,
                'end':
                end,
                'color':
                colordict[edge],
                'name':
                "{}.edge.{}-{}".format(self.volmesh.name, *edge)
            })
        return compas_ghpython.draw_lines(lines)
コード例 #23
0
ファイル: meshartist.py プロジェクト: mpopescu/compas
 def draw_normals(self, keys=None, color=None, scale=None):
     keys = keys or list(self.mesh.vertices())
     scale = scale or self.defaults.get('scale.normal')
     colordict = color_to_colordict(color,
                                    keys,
                                    default=self.defaults.get('color.normal'),
                                    colorformat='rgb',
                                    normalize=False)
     lines = []
     for key in keys:
         a = self.mesh.vertex_coordinates(key)
         n = self.mesh.vertex_normal(key)
         b = add_vectors(a, scale_vector(n, scale))
         lines.append({
             'start': a,
             'end': b,
             'color': colordict[key],
             'name': "{}.normal.{}".format(self.mesh.name, key),
             'layer': self.layer,
             'arrow': 'end'})
     return compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False)
コード例 #24
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.datastructure.faces()}
        elif isinstance(text, dict):
            textdict = text
        else:
            raise NotImplementedError

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

        labels = []
        for key, text in iter(textdict.items()):
            labels.append({
                'pos': self.datastructure.face_center(key),
                'name': self.datastructure.face_name(key),
                'color': colordict[key],
                'text': textdict[key],
            })
        return compas_rhino.xdraw_labels(labels,
                                         layer=self.layer,
                                         clear=False,
                                         redraw=False)
コード例 #25
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)
コード例 #26
0
def draw_mesh(
    mesh,
    layer=None,
    clear_layer=False,
    show_faces=True,
    show_vertices=False,
    show_edges=False,
    show_wireframe=False,
    vertexcolor=None,
    edgecolor=None,
    wireframecolor=None,
    facecolor=None,
):
    """
    Draw a mesh object in Rhino.

    Parameters:
        mesh (compas.datastructures.mesh.Mesh): The mesh object.
        layer (str): Optional. The layer to draw in. Default is ``None``.
        clear_layer (bool): Optional. Clear the drawing layer. Default is ``True``.
        show_faces (bool): Optional. Show the faces. Default is ``True``.
        show_vertices (bool): Optional. Show the vertices. Default is ``True``.
        show_edges (bool): Optional. Show the edges. Default is ``True``.
        vertexcolor (str, tuple, list, dict): Optional. The vertex color specification. Default is ``None``.
        edgecolor (str, tuple, list, dict): Optional. The edge color specification. Default is ``None``.
        facecolor (str, tuple, list, dict): Optional. The face color specification. Default is ``None``.
        redraw (bool): Optional. Redraw instructions. Default is ``True``.

    Note:
        Colors can be specifiedin different ways:

        * str: A hexadecimal color that will be applied to all elements subject to the specification.
        * tuple, list: RGB color that will be applied to all elements subject to the specification.
        * dict: RGB or hex color dict with a specification for some or all of the related elements.

    Important:
        RGB colors should specify color values between 0 and 255.

    """

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

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

    # facecolor = color_to_colordict(facecolor,
    #                                mesh.faces(),
    #                                default=mesh.attributes['color.face'],
    #                                colorformat='rgb',
    #                                normalize=False)

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

    if clear_layer:
        if not layer:
            compas_rhino.clear_current_layer()
        else:
            compas_rhino.clear_layer(layer)

    if show_faces:
        key_index = {key: index for index, key in enumerate(mesh.vertices())}
        xyz = [mesh.vertex_coordinates(key) for key in mesh.vertices()]
        faces = []
        color = mesh.attributes['color.face']

        for fkey in mesh.face:
            face = mesh.face_vertices(fkey, ordered=True)
            v = len(face)

            if v < 3:
                print('Degenerate face: {0} => {1}'.format(fkey, face))
            elif v == 3:
                faces.append([key_index[k] for k in face + [face[-1]]])
            elif v == 4:
                faces.append([key_index[k] for k in face])
            else:
                c = len(xyz)
                xyz.append(mesh.face_center(fkey))
                for i in range(-1, len(face) - 1):
                    key = face[i]
                    nbr = face[i + 1]
                    vertices = [
                        c, key_index[key], key_index[nbr], key_index[nbr]
                    ]
                    faces.append(vertices)

        compas_rhino.xdraw_mesh(xyz,
                                faces,
                                color,
                                '{0}.mesh'.format(mesh.attributes['name']),
                                layer=layer,
                                clear=False,
                                redraw=False)

    if show_edges:
        lines = []
        color = mesh.attributes['color.edge']
        for u, v in mesh.edges():
            lines.append({
                'start':
                mesh.vertex_coordinates(u),
                'end':
                mesh.vertex_coordinates(v),
                'name':
                '{0}.edge.{1}-{2}'.format(mesh.attributes['name'], repr(u),
                                          repr(v)),
                'color':
                edgecolor.get((u, v), color),
            })
        compas_rhino.xdraw_lines(lines, layer=layer, clear=False, redraw=False)

    if show_wireframe:
        lines = []
        color = mesh.attributes['color.edge']
        for u, v in mesh.wireframe():
            lines.append({
                'start':
                mesh.vertex_coordinates(u),
                'end':
                mesh.vertex_coordinates(v),
                'name':
                '{0}.edge.{1}-{2}'.format(mesh.attributes['name'], repr(u),
                                          repr(v)),
                'color':
                edgecolor.get((u, v), color),
            })
        compas_rhino.xdraw_lines(lines, layer=layer, clear=False, redraw=False)

    if show_vertices:
        points = []
        color = mesh.attributes['color.vertex']
        for key in mesh.vertices():
            points.append({
                'pos':
                mesh.vertex_coordinates(key),
                'name':
                '{0}.vertex.{1}'.format(mesh.attributes['name'], repr(key)),
                'color':
                vertexcolor.get(key, color),
            })
        compas_rhino.xdraw_points(points,
                                  layer=layer,
                                  clear=False,
                                  redraw=False)

    rs.EnableRedraw()
    rs.Redraw()
コード例 #27
0
    def draw_form(self,
                  vertices_on=True,
                  edges_on=True,
                  faces_on=False,
                  forces_on=True,
                  external_on=True,
                  arrows_on=False,
                  vertexcolor=None,
                  edgecolor=None,
                  facecolor=None,
                  edgelabel=None,
                  vertexlabel=None,
                  facelabel=None,
                  vertexsize=None,
                  forcescale=1.0,
                  lines=None,
                  points=None):
        """"""
        # preprocess

        vertexlabel = vertexlabel or {}
        edgelabel = edgelabel or {}
        facelabel = facelabel or {}
        vertexsize = size_to_sizedict(vertexsize, self.form.vertices(), self.default_vertexsize)
        vertexcolor = color_to_colordict(vertexcolor, self.form.vertices(), self.default_vertexcolor)
        edgecolor = color_to_colordict(edgecolor, self.form.edges(), self.default_edgecolor)
        facecolor = color_to_colordict(facecolor, self.form.faces(), self.default_facecolor)

        # scale and position

        x = self.form.vertices_attribute('x')
        y = self.form.vertices_attribute('y')

        if lines:
            x += [line['start'][0] for line in lines]
            x += [line['end'][0] for line in lines]
            y += [line['start'][1] for line in lines]
            y += [line['end'][1] for line in lines]

        xmin, ymin = min(x), min(y)
        xmax, ymax = max(x), max(y)
        dx, dy = -xmin, -ymin
        scale = max(fabs(xmax - xmin) / 10.0, fabs(ymax - ymin) / 10.0)

        # vertices

        if vertices_on:
            _points = []
            for key, attr in self.form.vertices(True):
                bgcolor = vertexcolor[key]
                _points.append({
                    'pos': [(attr['x'] + dx) / scale, (attr['y'] + dy) / scale],
                    'radius': vertexsize[key],
                    'facecolor': vertexcolor[key],
                    'edgecolor': self.default_edgecolor,
                    'linewidth': self.default_edgewidth * 0.5,
                    'text': None if key not in vertexlabel else str(vertexlabel[key]),
                    'textcolor': '#000000' if is_color_light(bgcolor) else '#ffffff',
                    'fontsize': self.default_fontsize,
                })
            draw_xpoints_xy(_points, self.ax1)

        # edges

        if edges_on:
            leaves = set(self.form.leaves())

            _lines = []
            _arrows = []

            for (u, v), attr in self.form.edges(True):
                sp, ep = self.form.edge_coordinates(u, v, 'xy')
                sp = ((sp[0] + dx) / scale, (sp[1] + dy) / scale)
                ep = ((ep[0] + dx) / scale, (ep[1] + dy) / scale)

                if external_on:
                    if u in leaves or v in leaves:
                        text = None if (u, v) not in edgelabel else str(edgelabel[(u, v)])
                        _arrows.append({
                            'start': sp,
                            'end': ep,
                            'width': self.default_externalforcewidth if not attr['is_ind'] else self.default_edgewidth * 3,
                            'color': self.default_externalforcecolor if not attr['is_ind'] else '#000000',
                            'text': text,
                            'fontsize': self.default_fontsize
                        })
                    else:
                        if forces_on:
                            width = forcescale * fabs(attr['f'])
                            color = self.default_tensioncolor if attr['f'] > 0 else self.default_compressioncolor
                            text = None if (u, v) not in edgelabel else str(edgelabel[(u, v)])
                            _lines.append({
                                'start': sp,
                                'end': ep,
                                'width': width,
                                'color': color,
                                'text': text,
                                'fontsize': self.default_fontsize
                            })
                        _arrows.append({
                            'start': sp,
                            'end': ep,
                            'width': self.default_edgewidth
                        })
                else:
                    if forces_on:
                        width = forcescale * fabs(attr['f'])
                        color = self.default_tensioncolor if attr['f'] > 0 else self.default_compressioncolor
                        text = None if (u, v) not in edgelabel else str(edgelabel[(u, v)])
                        _lines.append({
                            'start': sp,
                            'end': ep,
                            'width': width,
                            'color': color,
                            'text': text,
                            'fontsize': self.default_fontsize
                        })
                    _arrows.append({
                        'start': sp,
                        'end': ep,
                        'width': self.default_edgewidth if not attr['is_ind'] else self.default_edgewidth * 3
                    })

            if _arrows:
                if arrows_on:
                    draw_xarrows_xy(_arrows, self.ax1)
                else:
                    draw_xlines_xy(_arrows, self.ax1)
            if _lines:
                draw_xlines_xy(_lines, self.ax1, alpha=0.5)

        # faces

        if faces_on:
            _face_polygons = []
            for fkey in self.form.faces():
                vkeys = [vkey for vkey in self.form.face_vertices(fkey)]
                polygon_vertices = [self.form.vertex_coordinates(vkey, axes='xy') for vkey in vkeys]
                polygon_vertices = [[(x + dx) / scale, (y + dy) / scale] for (x, y) in polygon_vertices]  # scale the polygon
                _face_polygons.append({
                    'points': polygon_vertices,
                    'facecolor': '#e5e5e5',
                    'edgecolor': '#ffffff',
                    'edgewidth': 10.0,
                    'text': str(fkey) if fkey not in facelabel else str(facelabel[fkey]),
                    'fontsize': self.default_fontsize * 2,  # TEMP! TO DIFFER FROM OTHER LABELS
                    'textcolor': self.default_textcolor,
                })
            if _face_polygons:
                draw_xpolygons_xy(_face_polygons, self.ax1)

        # points

        if points:
            _points = []
            for point in points:
                x, y, _ = point['pos']
                _points.append({
                    'pos': [(x + dx) / scale, (y + dy) / scale],
                    'text': point.get('text', ''),
                    'radius': point.get('size', self.default_pointsize),
                    'textcolor': point.get('textcolor', self.default_textcolor),
                    'facecolor': point.get('facecolor', self.default_pointcolor),
                    'edgecolor': point.get('edgecolor', self.default_linecolor),
                    'fontsize': self.default_fontsize
                })
            draw_xpoints_xy(_points, self.ax1)

        # lines

        if lines:
            _lines = {}
            style = lines[0].get('style', self.default_linestyle)
            for line in lines:
                temp = line.get('style', self.default_linestyle)
                if temp == style:
                    if temp not in _lines:
                        _lines[temp] = []
                else:
                    _lines[temp] = []
                style = temp
                _lines[temp].append({
                    'start': [(line['start'][0] + dx) / scale, (line['start'][1] + dy) / scale],
                    'end': [(line['end'][0] + dx) / scale, (line['end'][1] + dy) / scale],
                    'width': line.get('width', self.default_linewidth),
                    'color': line.get('color', self.default_linecolor),
                    'text': line.get('text', ''),
                    'textcolor': line.get('textcolor', self.default_textcolor),
                    'fontsize': self.default_fontsize
                })
            for style in _lines:
                draw_xlines_xy(_lines[style], self.ax1, linestyle=style)
コード例 #28
0
    def draw_force(self,
                   vertices_on=True,
                   edges_on=True,
                   faces_on=False,
                   forces_on=True,
                   arrows_on=True,
                   vertexcolor=None,
                   edgecolor=None,
                   facecolor=None,
                   edgelabel=None,
                   vertexlabel=None,
                   vertexsize=None,
                   lines=None,
                   points=None):
        """"""
        # preprocess

        vertexlabel = vertexlabel or {}
        edgelabel = edgelabel or {}
        vertexsize = size_to_sizedict(vertexsize, self.force.vertices(),
                                      self.default_vertexsize)
        vertexcolor = color_to_colordict(vertexcolor, self.force.vertices(),
                                         self.default_vertexcolor)
        edgecolor = color_to_colordict(edgecolor, self.force.edges(),
                                       self.default_edgecolor)

        # scale and position

        x = self.force.vertices_attribute('x')
        y = self.force.vertices_attribute('y')
        if lines:
            x += [line['start'][0] for line in lines]
            x += [line['end'][0] for line in lines]
            y += [line['start'][1] for line in lines]
            y += [line['end'][1] for line in lines]
        xmin, ymin = min(x), min(y)
        xmax, ymax = max(x), max(y)
        dx, dy = -xmin, -ymin
        scale = max(fabs(xmax - xmin) / 10.0, fabs(ymax - ymin) / 10.0)

        # vertices

        if vertices_on:
            _points = []
            for key, attr in self.force.vertices(True):
                bgcolor = vertexcolor[key]
                _points.append({
                    'pos':
                    ((attr['x'] + dx) / scale, (attr['y'] + dy) / scale),
                    'radius':
                    vertexsize[key],
                    'facecolor':
                    bgcolor,
                    'edgecolor':
                    self.default_edgecolor,
                    'linewidth':
                    self.default_edgewidth * 0.5,
                    'text':
                    None if key not in vertexlabel else str(vertexlabel[key]),
                    'textcolor':
                    '#000000' if is_color_light(bgcolor) else '#ffffff',
                    'fontsize':
                    self.default_fontsize
                })
            draw_xpoints_xy(_points, self.ax2)

        # edges

        if edges_on:
            leaves = set(self.form.leaves())
            _arrows = []
            for (u, v), attr in self.force.edges(True):
                sp, ep = self.force.edge_coordinates(u, v, 'xy')
                sp = ((sp[0] + dx) / scale, (sp[1] + dy) / scale)
                ep = ((ep[0] + dx) / scale, (ep[1] + dy) / scale)
                form_u, form_v = self.form.face_adjacency_edge(u, v)
                if form_u in leaves or form_v in leaves:
                    _arrows.append({
                        'start': sp,
                        'end': ep,
                        'color': self.default_externalforcecolor,
                        'width': self.default_externalforcewidth
                    })
                else:
                    _arrows.append({
                        'start': sp,
                        'end': ep,
                        'color': self.default_edgecolor,
                        'width': self.default_edgewidth,
                    })
            if arrows_on:
                draw_xarrows_xy(_arrows, self.ax2)
            else:
                draw_xlines_xy(_arrows, self.ax2)

        # lines

        if lines:
            _lines = {}
            style = lines[0].get('style', self.default_linestyle)
            for line in lines:
                temp = line.get('style', self.default_linestyle)
                if temp == style:
                    if temp not in _lines:
                        _lines[temp] = []
                else:
                    _lines[temp] = []
                style = temp
                _lines[temp].append({
                    'start': [(line['start'][0] + dx) / scale,
                              (line['start'][1] + dy) / scale],
                    'end': [(line['end'][0] + dx) / scale,
                            (line['end'][1] + dy) / scale],
                    'width':
                    line.get('width', self.default_linewidth),
                    'color':
                    line.get('color', self.default_linecolor),
                    'text':
                    line.get('text', ''),
                    'textcolor':
                    line.get('textcolor', self.default_textcolor),
                    'fontsize':
                    self.default_fontsize
                })
            for style in _lines:
                draw_xlines_xy(_lines[style], self.ax2, linestyle=style)
コード例 #29
0
ファイル: drawing.py プロジェクト: duchaoyu/compas_3gs
from __future__ import absolute_import