volmdlr_tools.graph package#
Subpackages#
- volmdlr_tools.graph.utils package
- volmdlr_tools.graph.kinematics package
- Submodules
- volmdlr_tools.graph.kinematics.findjoint module
JointFinderJointFinder.analyse_intersection_result()JointFinder.analysis()JointFinder.check_direction()JointFinder.check_displacement()JointFinder.construct_matrix_dof()JointFinder.count_dof_constraints()JointFinder.create_torsor_from_unconstrained()JointFinder.detect_minimal_constraints()JointFinder.equivalent_torsor()JointFinder.find_subspace_intersection()JointFinder.get_dict_constraints_name()JointFinder.get_kinematic_list()JointFinder.get_most_unknown()JointFinder.get_torsor_kinematic_list()JointFinder.get_torsor_static_list()JointFinder.joint_torsor()JointFinder.merge_torsors()JointFinder.should_merge_torsors()
- volmdlr_tools.graph.kinematics.torsor module
DynamicTorsorGeometricTorsorGeometricTorsor.from_kinematic_torsor()GeometricTorsor.geometric_torsor_matrix()GeometricTorsor.geometric_torsor_rotation_x()GeometricTorsor.geometric_torsor_rotation_y()GeometricTorsor.geometric_torsor_rotation_z()GeometricTorsor.geometric_torsor_translation_x()GeometricTorsor.geometric_torsor_translation_y()GeometricTorsor.geometric_torsor_translation_z()GeometricTorsor.type()
KinematicTorsorKineticTorsorStaticTorsorTorsorTorsor.addition()Torsor.check_direction_dof()Torsor.check_rotary()Torsor.comparison_unknown()Torsor.compute_norm()Torsor.copy()Torsor.dict_to_object()Torsor.equivalent_torsor()Torsor.get_unknown()Torsor.moment_dual()Torsor.resultant_dual()Torsor.to_dict()Torsor.to_dual()Torsor.torsor_to_column()Torsor.transport_moment()Torsor.transport_resultant()
- Module contents
Submodules#
volmdlr_tools.graph.assembly module#
Specific module to create and manipulate assembly graphs of volmdlr volume model.
- class volmdlr_tools.graph.assembly.GraphAssembly(root_compound: Compound = None, name: str = '', *, graph: Graph = None)#
Bases:
GraphClass to create, manipulate and plot volmdlr assembly graphs.
- are_siblings(list_nodes: list[int]) bool#
Return True if all nodes in the given list children of the same parent and False otherwise.
- Parameters:
list_nodes – A list containing the node IDs.
- Returns:
True if all nodes share a common parent, False otherwise.
- calculate_gravity_center(nodes: list[int]) None#
Calculate the center of gravity for given list of node in the assembly.
- Parameters:
nodes – list of nodes.
- classmethod dict_to_object(dict_: JsonObject, **kwargs) SerializableObject#
Deserialize a dictionary to a Graph object. Custom to handle networkx graph.
- property directed_acyclic_graph: DiGraph#
Return the directed acyclic graph of the assembly tree.
- classmethod from_compound(compound: Compound) GraphAssembly#
Create a GraphAssembly from a compound.
- classmethod from_doc_model(doc_model: DocModel) GraphAssembly#
Create a GraphAssembly from a DocModel, without building a VolumeModel.
- Parameters:
doc_model – The DocModel whose B-Rep assembly is graphed.
- Returns:
The same graph as from_volume_model(doc_model.to_volume_model()).
- Raises:
ValueError – If the DocModel has no root prototype or no B-Rep geometry.
- classmethod from_volume_model(volume_model: VolumeModel) GraphAssembly#
Create a GraphAssembly from a volume model.
- get_aag(node: int, smooth_angular_tol: float = 1e-06) graph_faces.AttributedAdjacencyGraph#
Get agg for corresponding node solid.
- get_all_children(node: int) GraphAssembly#
Get all levels of children until the leaf of the given parent ID and return as a subgraph.
- Parameters:
node – The parent node ID.
- Returns:
A GraphAssembly instance containing the subgraph.
- get_children(node: int) list[int]#
Get all first-level children IDs of the given parent ID.
- Parameters:
node – The parent node ID.
- Returns:
A list of child node IDs.
- get_close_solids(solid_node_id: int, maximum_distance: float) NodeView#
Get the close solids from a solid.
- Parameters:
solid_node_id – The node id of the solid.
maximum_distance – The maximum distance to consider a solid as close.
- Returns:
A dict of the close solids with their attributes.
- get_disconected_subassemblies() list[GraphAssembly]#
Identifies and retrieves disconnected subassemblies of a graph-based structure.
This function isolates separate subassemblies by analyzing the connected components of the graph where specific edge properties and node attributes are used for filtering. It calculates bounding box proximity and determines proximity distances on edges to filter and identify interconnections between nodes classified as “Solid”. The result is a list of subassemblies, each represented as its own graph structure.
- Returns:
A list of subassemblies represented as graph objects. If the graph is connected, the method returns a single-item list containing the original graph.
- Return type:
list
- get_mesh(node_id: int) Shape#
Get the mesh from a node id.
- Parameters:
node_id – The node id to get the mesh from.
- Returns:
The mesh corresponding to the node id.
- get_node_id(shape: Shape) int | None#
Get the NodeID in the graph from a given shape.
- Parameters:
shape – The shape to search in the graph.
- Returns:
The ID of the given shape.
- get_parent(node: int) int#
Get the parent node of a given node.
- Parameters:
node – The node ID to query.
- Returns:
The parent node ID, or None if no parent exists.
- get_path(node: int) list[int]#
Return the path from the root to get in the specified node.
- get_shape(node_id: int) Shape#
Get the shape from a node id.
- Parameters:
node_id – The node id to get the shape from.
- Returns:
The shape corresponding to the node id.
- get_solids_by_radius_proximity(solid_node_id: int, radius: float) NodeView#
Get all the solids whose center of mass is within a specified radius of the center of mass of a target solid.
- Parameters:
solid_node_id – The node ID of the target solid.
radius – The radius within which to search for nearby solids.
- Returns:
A NodeView where keys are node IDs of solids whose center of mass is within a specified radius.
- get_solids_inside_sphere(center: Point3D, radius: float) NodeView#
Get all the solids that are inside a sphere defined by a center point and a radius.
The solid will be considered inside the sphere if its center_of_mass is inside of the sphere.
- Parameters:
center – The center point of the sphere.
radius – The radius of the sphere.
- Returns:
A NodeView where keys are node IDs of solids inside the sphere.
- markdown_tree() str#
Implementation of a tag for displays.
- print_tree() None#
Print the XPDM XML tree.
- process_geom_constraint_to_joints(constraints: list[GeometricConstraint], edge: tuple[int, int])#
Converts geometric constraints between two solids into appropriate joint types.
This function analyzes the given geometric constraints between two solids and determines the appropriate joint type to represent their mechanical relationship.
- set_bounding_box_attribute() None#
Set the bounding box attribute for all nodes.
- set_center_of_mass_attribute() None#
Set the center of mass attribute for all nodes.
- set_connection_geometry(tol: float = 1e-06)#
Set the connection geometry attribute for all solids. The edge attribute “” will be set.
- Parameters:
tol – The tolerance to consider two solids as connected.
- set_distance_attribute(exact: bool = True) None#
Set a distance attribute between all solids in the assembly graph.
This method calculates the pairwise distances between all solids and assigns them to the edges in the graph as an attribute named “distance.”
- Parameters:
exact – If True, uses exact geometry for distance calculations. If False, uses discretized shapes for faster but approximate calculations.
- Returns:
None. The method modifies the graph in-place by adding a “distance” attribute to edges between solids.
- set_distance_siblings_attribute(exact: bool = True) None#
Set the distance attribute for edges between sibling shapes in the assembly graph.
This method calculates distances between shapes that share a common parent and assigns them as an attribute named “distance_siblings” to the corresponding edges.
- Parameters:
exact – If True, uses exact geometry for distance calculations. If False, uses discretized shapes for faster but approximate calculations.
- Returns:
None. The method modifies the graph in-place by adding a “distance_siblings” attribute to edges between sibling shapes.
- set_edges_between_all_solids()#
Establishes edges between all nodes classified as “Solid” within the graph.
This function utilizes a filter to identify edges connecting nodes where both nodes are of the class “Solid”. It ensures that such connections are established across the graph through the create_edges method.
- Returns:
None
- set_geometric_constraints(tol: float = 1e-06) None#
Configure geometric constraints for edges between solids.
This method sets connections between all solids in the system and assigns geometric constraints attributes to the edges based on the conditions defined by the distance and class of the solids.
- Parameters:
tol – A tolerance value used to filter edges by distance.
- set_parent_attribute() None#
Set parent attribute for nodes of the graph.
- to_dict(use_pointers: bool = True, memo=None, path: str = '#', id_method=True, id_memo=None, **kwargs) JsonObject#
Convert the Graph object to a serializable dictionary. Custom to handle networkx graph.
volmdlr_tools.graph.core module#
Generic graph class.
- class volmdlr_tools.graph.core.Graph(name: str = '', *, graph: Graph | None = None)#
Bases:
DessiaObjectGeneric graph class, with serialization and plotting capabilities.
This class is composed of a networkx graph, and provides methods to manipulate it. This class can be overridden to create specific graph classes, with specific creation methods.
- create_edge(edge: tuple[int, int], attributes: dict[str, Any] = None) None#
Create an edge with attributes, if not already existing.
- Parameters:
edge – The edge to create.
attributes – The attributes of the edge, optional.
- create_edges(filter_function: Callable[[tuple[int, int]], bool], attributes: dict[str, Any] = None) None#
Create edges between all nodes that satisfy the filter function, that takes an Edge as argument.
- Parameters:
filter_function – The function to filter the edges to create, based on the two nodes of the edge.
attributes – The attributes of the edges to create, optional.
- classmethod dict_to_object(dict_: JsonObject, **kwargs) SerializableObject#
Deserialize a dictionary to a Graph object. Custom to handle networkx graph.
- edge_subgraph(filter_function: Callable[[tuple[int, int]], bool]) Graph#
Create a subgraph from the edges that satisfy the filter function, that takes an Edge as argument.
- Parameters:
filter_function – A callable to filter the edges to create the subgraph from.
- Returns:
The subgraph created.
- property edges: EdgeView#
Return a read-only view of the eges of the graph.
You can get EdgeDataView object from it, by passing data=True argument to the NodeView object.
- get_connected_components(nodes: Iterable[int] | None = None, filter_function: Callable[[int], bool] | None = None, edge_filter: Callable[[int, int], bool] | None = None) list[set[int]]#
Get the connected components of the graph restricted to a set of nodes.
Two nodes fall in one component when a path joins them without leaving the kept nodes, nor crossing an edge the edge filter refuses. Nodes the graph does not hold are left out.
- Parameters:
nodes – The nodes to keep, every node of the graph when
None.filter_function – Optional filter that keeps only the nodes it accepts.
edge_filter – Optional filter that keeps only the edges it accepts, given their two nodes.
- Returns:
One set of node IDs per component, ordered by their smallest node.
- get_edge_attribute(edge: tuple[int, int], attribute: str) Any#
Get a specific attribute of a specific Edg. If the attribute does not exist, return None.
- Parameters:
edge – The edge to get the attribute from.
attribute – The key of the attribute to get.
- Returns:
The attribute of the edge.
- get_edge_data(node1: int, node2: int, default: Any = None) Any#
Get edge data between two nodes, with optional default value.
- Parameters:
node1 – First node ID.
node2 – Second node ID.
default – Default value to return if edge doesn’t exist.
- Returns:
Edge data dictionary or default value.
- get_edges(filter_function: ~typing.Callable[[tuple[int, int]], bool] = <function Graph.<lambda>>) EdgeView#
Get all edges that satisfy the filter function, that takes an Edge as argument.
- Parameters:
filter_function – A callable that take an Edge and return a bool (for filtering).
- Returns:
The edges that satisfy the filter function.
- get_node_attribute(node: int, attribute: str) Any#
Get a specific attribute of a specific node. If the attribute does not exist, return None.
- Parameters:
node – The node id to get the attribute from.
attribute – The key of the attribute to get.
- Returns:
The attribute of the node.
- get_nodes(filter_function: ~typing.Callable[[int], bool] = <function Graph.<lambda>>) NodeView#
Get all nodes that satisfy the filter function, that takes a NodeID as argument.
- Parameters:
filter_function – A callable that take a NodeID and return a bool (for filtering).
- Returns:
The nodes that satisfy the filter function.
- has_edge(node1: int, node2: int) bool#
Check if an edge exists between two nodes.
- Parameters:
node1 – First node ID.
node2 – Second node ID.
- Returns:
True if edge exists, False otherwise.
- property n_edges: int#
Get the number of edges of the graph.
- Returns:
The number of edges.
- property n_nodes: int#
Get the number of nodes of the graph.
- Returns:
The number of nodes.
- neighbors(node: int, filter_function: ~typing.Callable[[tuple[int, int]], bool] = <function Graph.<lambda>>) NodeView#
Get the neighbors of a node.
- Parameters:
node – The node id to get the neighbors from.
filter_function – The function to filter the neighbors to get based on the edge between the node and the neighbor.
- Returns:
The neighbors of the node.
- property nodes: NodeView#
Return a read-only view of the nodes of the graph.
You can get NodeDataView object from it, by passing data=True argument to the NodeView object.
- plot_data(reference_path: str = '#', **kwargs) list[NetworkxGraph]#
Return the plot_data object for local plot_data usage.
- plot_graph(reference_path: str = '#', **kwargs) NetworkxGraph#
Specific display tag for PlotData. Add a picture argument.
- set_edge_attribute(edge: tuple[int, int], attribute: str, value: Any) None#
Set an attribute to an edge.
- Parameters:
edge – The edge to set the attribute to.
attribute – The key of the attribute to set.
value – The value of the attribute.
- set_edges_attribute(attribute: str, attribute_function: Callable[[tuple[int, int]], Any], filter_function: Callable[[tuple[int, int]], bool] | None = None) None#
Set a dynamically computed attribute on all the edges that satisfy the filtering function.
- Parameters:
attribute – The key of the attribute to set.
attribute_function – A callable that take an Edge and return a value, to compute the attribute value.
filter_function – An optional callable to filter the edges to apply the attribute to.
- set_node_attribute(node: int, attribute: str, value: Any) None#
Set an attribute to a node.
- Parameters:
node – The node id to set the attribute to.
attribute – The key of the attribute to set.
value – The value of the attribute.
- set_nodes_attribute(attribute: str, attribute_function: Callable[[int], Any], filter_function: Callable[[int], bool] | None = None) None#
Set a dynamically computed attribute on all the nodes that satisfy the filtering function.
- Parameters:
attribute – The key of the attribute to set.
attribute_function – A callable that take a NodeID and return a value, to compute the attribute value.
filter_function – An optional callable to filter the nodes to apply the attribute to. Default is all nodes.
- subgraph(filter_function: Callable[[int], bool]) Graph#
Create a subgraph from the nodes that satisfy the filter function, that takes a NodeID as argument.
- Parameters:
filter_function – A callable to filter the nodes to create the subgraph from.
- Returns:
The subgraph created.
- to_dict(use_pointers: bool = True, memo=None, path: str = '#', id_method=True, id_memo=None, **kwargs) JsonObject#
Convert the Graph object to a serializable dictionary. Custom to handle networkx graph.
volmdlr_tools.graph.faces module#
Attributed Adjacency Graph (AAG) Module for CAD Feature Recognition.
References: - Joshi S., Chang T.C. Graph-based heuristics for recognition of machined
features from a 3D solid model // Comput. Des. 1988. Vol. 20, N 2. P. 58-66.
- class volmdlr_tools.graph.faces.AttributedAdjacencyGraph(shape: Shape, allow_smooth: bool = True, smooth_angular_tol: float = 1e-06, name: str = '', *, graph: Graph | None = None)#
Bases:
GraphAttributed Adjacency Graph (AAG) for faces of a BRep model.
The AAG provides a formal graph structure that captures the adjacency relationships between faces of a BRep model, along with attributes such as surface type, angles between faces, and geometric properties. The AAG extends a B-Rep (Boundary Representation) model with semantics, allowing for graph-based traversal and feature recognition.
Advantages of using an AAG: - Provides a formal graph view of the CAD model for applying graph algorithms. - Caches serial indices of sub-shapes, avoiding repeated use of TopExp utilities
for an unchanged CAD model.
Enables the representation of features and semantics through graph attributes.
Explicitly defines the adjacency relationships between faces, making it useful for feature recognition and geometric analysis.
The AAG is based on the work by Joshi and Chang (1988), who proposed a graph-based approach for recognizing machined features in 3D solid models.
- Indexing convention:
All indices (faces, edges, vertices) are 0-based in the public API. OCP’s 1-based indexing is an internal implementation detail.
- Angle precondition:
Construction records which faces are adjacent, not the angle at which they meet.
calculate_faces_angles()computes those angles, and until it has,is_angle_concave(),is_angle_convex()andis_angle_smooth()raiseRuntimeErrorrather than answerFalseabout an angle nobody has measured.angles_calculatedreports whether the precondition holds, so a caller can satisfy it without provoking the exception first.The predicates read the angle strictly, so an edge left bare in a graph that reports its angles computed raises
KeyErrorinstead of being answeredFalse.FeatureAngleType.UNDEFINED– what the kernel returns for faces sharing no usable common edge – is a measured answer, and reads as neither concave nor convex nor smooth.Computing the angles is deliberately not lazy: it costs one geometric kernel call per adjacency edge, and a boolean-returning predicate is the wrong place to hide that.
- aag_overall_weight() int#
Create a sort of signature for an aag.
In general, it uses the graph structure and faces relationship to create a value that could be used as some sort of id. The node weights are defined using the networkx graph degree of each node, and the edge weights are calculated using the angle in degrees between two adjacent faces.
Populate topology attributes and the face-signature database.
Deprecated since version Prefer:
add_face_topology_attributes()when only area/topology is needed (cheap), oradd_face_signatures()when the signature matrix is required (expensive). This wrapper calls both for backward compatibility.
- add_face_signatures(tolerance: float = 1.0, n_bins: int = 150, n_points: int = 100000) None#
Build the D2/PCA face-signature database.
Expensive — triangulates every face and samples point clouds for signature computation. Only needed by shape-pattern matching. Ensures topology attributes are populated as well. Idempotent via
faces_signatures_calculated.
- add_face_topology_attributes() None#
Populate per-face topology attributes (area, number_holes, number_edges, edge_perimeter).
Every face of the shape is read, on every one of its shells, under its node id. Cheap — iterates the faces once without triangulating or sampling points. Idempotent via
faces_topology_calculated.
- add_mates(mate_faces: list[TopoDS_Shape]) None#
Add adjacency relationships (mates) between pairs of faces in the graph.
Helper function to build_adjacency_graph, whose nodes already stand for every face. For each pair of adjacent faces, this method adds a bare edge between them in the graph. The angle at that edge is not computed here:
calculate_faces_angles()attributes the edge with the angle, common-edge indices and edge color.- Parameters:
mate_faces – A list of faces that share a common edge.
- angles_calculated: bool#
Whether every adjacency edge carries its angle – the precondition of the angle predicates. Derived from the graph held, not a record of a call having happened.
- build_adjacency_graph() None#
Construct an adjacency graph of the faces in a B-Rep (Boundary Representation) model.
Every face of the shape is a node, numbered by its id in the shape, whether or not it shares an edge with another face: a face no other touches is a node without neighbours. Each edge in the graph represents an adjacency relation between two faces that share a common edge.
- calculate_face_angle(face1_id: int, face2_id: int) None#
Update aag graph edges with the angle information between two faces.
- calculate_faces_angles() None#
Update aag graph edges with the angle information between two faces.
Satisfies the precondition of
is_angle_concave(),is_angle_convex()andis_angle_smooth(), and leavesangles_calculatedTrue. Costs one geometric kernel call per adjacency edge, so it is a caller’s job to invoke, not a predicate’s to infer.
- collapse(face_indices: int | set[int], *, merge_edge_indices: bool = True, carry_node_attributes: bool = False) Graph#
Return a new graph with the given face nodes collapsed.
For each collapsed face, every pair of its external neighbors becomes directly adjacent. The dihedral angle on the new arc is deduced from the two arcs that passed through the collapsed node.
The original AAG graph is not modified.
- Parameters:
face_indices – A single face index or a set of face indices to collapse.
merge_edge_indices – If True (default), the
common_edges_indicesof the two incoming arcs are merged (union) onto the new arc. Set False when only topology matters, not edge geometry.carry_node_attributes – If True, node attributes from each collapsed face are collected and stored on new arcs under key
"collapsed_nodes"as a list of attribute dicts.
- Returns:
A new
nx.Graphwith the collapsed topology.
- contains_face(face: TopoDS_Shape) bool#
Tell whether
faceis one of the shape’s faces.
- copy(deep=True, memo=None) AttributedAdjacencyGraph#
Copy of AttributtedAdjacencyGraph.
- Returns:
return a copied instance of the AttributtedAdjacencyGraph.
- classmethod dict_to_object(dict_: JsonObject, **kwargs) SerializableObject#
Deserialize a dictionary to a AttributedAdjacencyGraph object.
- property edge_count: int#
Return the total number of edges in the shape.
Return whether two edges have at least one endpoint vertex in common.
- Parameters:
edge_index_a – 0-based index of the first edge.
edge_index_b – 0-based index of the second edge.
- Returns:
True when the edges share an endpoint vertex.
- property face_count: int#
Return the total number of faces in the shape.
- property faces_attributes_calculated: bool#
Backward-compat alias — True when the signature matrix has been built.
Deprecated since version Prefer:
faces_signatures_calculated(orfaces_topology_calculatedif only the topology attributes matter).
- faces_euler_characteristic(nodes: Iterable[int], *, open_attached_inner_wires: bool = False) int#
Return V - E + F over the faces nodes, counting each shared vertex and edge once.
Each face counts as a disc, whatever inner wires it has.
With open_attached_inner_wires, a face is the annulus it is where another face of nodes attaches along one of its inner wires, and each such wire takes one off the count: the walls of a narrower passage crossing a wider one then count the same as two equal ones. An inner wire that opens onto a face outside nodes, a cross-hole recognised on its own, stays closed.
- Parameters:
nodes – 0-based face indices.
open_attached_inner_wires – Count the inner wires that faces of nodes attach along as holes.
- find_faces_adjacent_to_edges(edges: list) set[int]#
Find AAG face indices that contain any of the given OCP edges.
- classmethod from_doc_model(doc_model: DocModel, prototype: Prototype | None = None, allow_smooth: bool = True, smooth_angular_tol: float = 1e-06, name: str = '')#
Initialize the AttributedAdjacencyGraph with the shape of a DocModel prototype, the root one by default.
- Parameters:
doc_model – The DocModel to read, without converting it to a VolumeModel.
prototype – The prototype whose shape is graphed, in its own frame; only its B-Rep is read.
- classmethod from_shape(shape: Shape, allow_smooth: bool = True, smooth_angular_tol: float = 1e-06, name: str = '')#
Initialize the AttributedAdjacencyGraph with a shape.
- classmethod from_volume_model(volume_model: VolumeModel, allow_smooth: bool = True, smooth_angular_tol: float = 1e-06, name: str = '')#
Initialize the AttributedAdjacencyGraph with a volume model, taking its first primitive.
- get_boundary_edge_indices() set[int]#
Return the set of 0-based edge indices that belong to only one face.
These are the open boundary edges of the shell.
- get_bounding_box(face: TopoDS_Shape = None, index: int = None) BoundingBox#
Get the bounding box of a face or an index.
- get_common_edge_indices(face1_idx: int, face2_idx: int) list[int]#
Get the cached integer edge indices common to two faces.
- Parameters:
face1_idx – First face index (node ID).
face2_idx – Second face index (node ID).
- Returns:
0-based edge indices, or an empty list if the faces don’t share an AAG edge.
- get_common_edges(face1_idx: int, face2_idx: int) list[TopoDS_Shape]#
Get common edges between two faces by their indices.
This is the primary efficient method that works directly with face indices. Uses the AAG’s pre-computed common_edges_indices for O(1) lookup.
- Parameters:
face1_idx – First face index (node ID)
face2_idx – Second face index (node ID)
- Returns:
List of common edges (TopoDS_Shape) or empty list if none found
- get_common_edges_between_faces(face1: TopoDS_Shape, face2: TopoDS_Shape) list[TopoDS_Shape]#
Get common edges between two faces (convenience method).
This method provides convenience when working directly with TopoDS_Shape objects. It converts faces to indices and delegates to get_common_edges().
- Parameters:
face1 – First face (TopoDS_Shape)
face2 – Second face (TopoDS_Shape)
- Returns:
List of common edges (TopoDS_Shape) or empty list if none found
- get_edge(edge_index: int) TopoDS_Shape | None#
Retrieve an edge from the indexed map by its index.
- Parameters:
edge_index – The 0-based index of the edge to retrieve.
- Returns:
The edge corresponding to the given index, or None if invalid.
- get_edge_angle(face1_idx: int, face2_idx: int) FeatureAngleType | None#
Return the cached angle classification for the AAG edge between two faces.
- Parameters:
face1_idx – First face index (node ID).
face2_idx – Second face index (node ID).
- Returns:
The stored
angle(aFeatureAngleType), orNoneif the edge is missing or its angle was never computed.
- get_edge_index(edge: Edge | TopoDS_Shape) int#
Retrieve a 0-based edge index from an edge object. Returns -1 if not found.
- get_edge_indices_from_vertex(vertex_index: int) list[int]#
Return 0-based edge indices connected to a vertex.
- Parameters:
vertex_index – 0-based vertex index.
- Returns:
List of 0-based edge indices.
- get_edge_vertex_indices(edge_index: int) tuple[int, int]#
Return the 0-based start and end vertex indices of an edge.
Endpoints are ordered by orientation: the FORWARD vertex is the start, the REVERSED vertex is the end. A closed edge (e.g. a full circle) returns the same index for both.
- Parameters:
edge_index – 0-based edge index.
- Returns:
(start_vertex_index, end_vertex_index).
- get_face(face_index: int) TopoDS_Shape#
Retrieve a face from the indexed map by its index.
- Parameters:
face_index – The index of the face to retrieve.
- Returns:
The face corresponding to the given index.
- get_face_area(face_id: int) float#
Return the area of a face, measured once and kept on its node.
A face whose area cannot be evaluated reads as zero, with a warning.
- Parameters:
face_id – The index of the face.
- Returns:
The face area.
- get_face_boundary_edge_indices(face_index: int) set[int]#
Return the set of 0-based edge indices that form the boundary of a face.
- Parameters:
face_index – 0-based face index.
- Returns:
Set of 0-based edge indices.
- get_face_index(face: Face | TopoDS_Shape) int#
Retrieve a face index from a face object.
This method handles both volmdlr shapes.Face objects and OCP TopoDS_Shape objects. For shapes.Face objects, it uses the wrapped TopoDS_Face. For TopoDS_Shape objects, it uses them directly.
- Parameters:
face – The face object (shapes.Face or TopoDS_Shape) to get the index for.
- Returns:
The index corresponding to the given face, or -1 if not found.
- get_face_indices_sharing_edge(edge_index: int) list[int]#
Return 0-based face indices adjacent to an edge.
- Parameters:
edge_index – 0-based edge index.
- Returns:
List of 0-based face indices.
- get_face_neighbor_indices(face_index: int) frozenset[int]#
Return the 0-based indices of the faces sharing an edge with a face.
A face is never its own neighbour, even across a seam, and a face sharing no edge with another face has none.
- Parameters:
face_index – 0-based face index.
- Returns:
The indices of the neighbouring faces.
- get_face_vertex_count(face_index: int) int#
Return the number of vertices for a given face.
- Parameters:
face_index – 0-based face index.
- get_face_vertex_indices(face_index: int) list[int]#
Return 0-based vertex indices for a given face.
Uses an IndexedMapOfShape to collect vertices, which guarantees deduplication (a vertex shared by multiple edges on the same face appears only once).
- Parameters:
face_index – 0-based face index.
- Returns:
List of unique 0-based vertex indices belonging to the face.
- get_face_wires(face_index: int) tuple#
Return the (outer_wire, inner_wires) for a face, with caching.
- Parameters:
face_index – 0-based face index.
- Returns:
Tuple of (outer_wire, list_of_inner_wires).
- get_faces(face_indices: list[int]) list[TopoDS_Shape]#
Retrieve multiple faces from the indexed map by their indices.
- Parameters:
face_indices – List of face indices to retrieve.
- Returns:
List of faces corresponding to the given indices.
- get_faces_on_concave_angles() list[TopoDS_Shape]#
Get all faces that are connected to edges with concave angles.
Calculates face angles if not already computed, then finds all edges with concave angles and returns the faces connected to those edges.
- Returns:
List of face objects that are adjacent to concave angle edges.
- get_faces_on_convex_angles() list[TopoDS_Shape]#
Get all faces that are connected to edges with convex angles.
Calculates face angles if not already computed, then finds all edges with convex angles and returns the faces connected to those edges.
- Returns:
List of face objects that are adjacent to convex angle edges.
- get_faces_sharing_edge(edge_index: int) list#
Return the list of adjacent faces to a given edge.
- get_inner_wire_neighbors(face_index: int, filter_function: ~typing.Callable[[tuple[int, int]], bool] = <function AttributedAdjacencyGraph.<lambda>>) list[int]#
Get the neighboring faces reached across the inner wires of a face.
These are the faces of the features hanging inside the face. A free edge of an inner wire, bordering no other face, adds no neighbor.
The face angles must be computed first (
calculate_faces_angles()), as forget_neighbors_thru_edge_ids().- Parameters:
face_index – The index of the face to find neighbors for.
filter_function – Extra predicate receiving the AAG edge
(face_index, neighbor); return True to KEEP the neighbor.
- Returns:
Indices of the neighboring faces sharing an edge of any inner wire, each listed once.
- Raises:
RuntimeError – When the face angles have not been computed.
- get_map_edges_face_size() int#
Get the size of the map edges face.
- get_neighbors_thru(face_index: int, edge: TopoDS_Shape) list[int]#
Get the neighboring faces of a given face that share a specific edge.
- Parameters:
face_index – The index of the face to find neighbors for.
edge – The edge shared by neighboring faces.
- Returns:
A list of indices representing neighboring faces that share the specified edge.
- get_neighbors_thru_edge_ids(face_index: int, edge_ids: ~OCP.OCP.TColStd.TColStd_PackedMapOfInteger, filter_function: ~typing.Callable[[tuple[int, int]], bool] = <function AttributedAdjacencyGraph.<lambda>>) list[int]#
Get neighboring faces of a given face that share common edges, identified by their edge indices.
- Parameters:
face_index – The index of the face to find neighbors for.
edge_ids – A packed map of edge indices to check for commonality.
filter_function – Extra predicate receiving the AAG edge
(face_index, neighbor); return True to KEEP the neighbor. Pass e.g.is_angle_convexto restrict the result to convex transitions – an angle predicate carries the class’s angle precondition with it.
- Returns:
A list of indices representing neighboring faces that share the specified edges.
- Raises:
RuntimeError – When the face angles have not been computed: the shared edge indices are recorded by
calculate_faces_angles().
- get_neighbors_thru_wire(face_index: int, wire: ~OCP.OCP.TopoDS.TopoDS_Shape, filter_function: ~typing.Callable[[tuple[int, int]], bool] = <function AttributedAdjacencyGraph.<lambda>>) list[int]#
Get the neighboring faces reached across one specific wire of a face.
Restricts the neighbor query to the edges of
wire, so a caller can separate the faces met across the outer boundary from those met across an inner loop. A wire that is not one offace_index’s own contributes no matching edge indices and yields an empty list.The face angles must be computed first (
calculate_faces_angles()), as forget_neighbors_thru_edge_ids().- Parameters:
face_index – The index of the face to find neighbors for.
wire – One of the face’s wires, as returned by
get_face_wires().filter_function – Extra predicate receiving the AAG edge
(face_index, neighbor); return True to KEEP the neighbor.
- Returns:
Indices of the neighboring faces sharing an edge of
wire.- Raises:
RuntimeError – When the face angles have not been computed.
- get_oriented_faces_thru_edge(edge_index: int) tuple[int, int] | None#
Return the (left_face, right_face) indices of an edge, ordered by orientation.
Sides follow the material-on-the-left rule: walking along the edge’s own direction with the outside of the solid toward the viewer:
edge direction ^ | left | right face | face |
Returns
Nonewhen the edge is not cleanly bounded by two faces (an open boundary edge has one, a non-manifold edge has three or more). A seam edge, bounded twice by a single periodic face, returns that face for both sides.- Parameters:
edge_index – 0-based edge index.
- Returns:
(left_face_id, right_face_id), orNonewhen the edge is not cleanly bounded by exactly two faces (open boundary or non-manifold) or when its sides are inconsistent (neither or both adjacent faces claim the left side).
- get_outer_wire_neighbors(face_index: int, filter_function: ~typing.Callable[[tuple[int, int]], bool] = <function AttributedAdjacencyGraph.<lambda>>) list[int]#
Get the neighboring faces reached across the outer wire of a face.
A free edge of the outer wire, bordering no other face, adds no neighbor.
The face angles must be computed first (
calculate_faces_angles()), as forget_neighbors_thru_edge_ids().- Parameters:
face_index – The index of the face to find neighbors for.
filter_function – Extra predicate receiving the AAG edge
(face_index, neighbor); return True to KEEP the neighbor.
- Returns:
Indices of the neighboring faces sharing an edge of the outer wire.
- Raises:
RuntimeError – When the face angles have not been computed.
- get_region_neighbors(face_indices: ~collections.abc.Iterable[int], excluding: ~collections.abc.Collection[int] = (), filter_function: ~typing.Callable[[tuple[int, int]], bool] = <function AttributedAdjacencyGraph.<lambda>>) set[int]#
Return the faces bordering a set of faces from outside it.
A face of the set is never one of them, even where two faces of the set share an edge.
- Parameters:
face_indices – The 0-based indices of the faces of the set, each a face of the graph.
excluding – Faces left out of the answer even where they border the set.
filter_function – Extra predicate receiving the AAG edge
(inside, outside); return True to KEEP the outside face across that edge. A face is kept when the predicate keeps it across any one of its edges with the set. Pass e.g.is_angle_convexto keep only the faces met at a convex edge.
- Returns:
The indices of the faces outside both the set and excluding that share an edge with a face of the set.
- get_smooth_edge_ids(face1_id: int, face2_id: int) list[int]#
Return the common-edge indices between two AAG faces if their AAG edge is smooth.
Triggers angle calculation on demand if the edge has no cached angle yet. Returns an empty list if the faces are not adjacent or the transition is not smooth.
- Parameters:
face1_id – First face index.
face2_id – Second face index.
- Returns:
Common-edge indices for the smooth boundary, or [].
- get_surface_type(face_id: int) str#
Return the name of the type of surface a face lies on, such as
"Plane"or"CylindricalSurface".- Parameters:
face_id – The index of the face.
- Returns:
The surface type name.
- get_total_vertex_count() int#
Return the total number of vertices in the shape.
- get_vertex(vertex_index: int) TopoDS_Shape | None#
Retrieve a vertex by its 0-based index.
- Parameters:
vertex_index – 0-based vertex index.
- Returns:
The vertex shape, or None if index is out of bounds.
- get_vertex_index(vertex: TopoDS_Vertex) int#
Get 0-based vertex index.
- get_wire_edge_indices(wire: TopoDS_Shape) set[int]#
Collect the 0-based edge indices for every edge in wire.
- Parameters:
wire – TopoDS_Wire (or any shape iterable by
TopAbs_EDGE).- Returns:
Set of edge indices known to the AAG; unknown edges are skipped.
- init_attributes() None#
Create the Attributed Adjacency Graph from a given shape.
- is_angle_concave(edge: tuple[int, int]) bool#
Check if the angle at a given edge is concave.
Requires the face angles: see the angle precondition in the class docstring.
- Parameters:
edge – The edge to check for concave angle.
- Returns:
True if the angle at the edge is concave, False otherwise.
- Raises:
RuntimeError – When the face angles have not been computed; the message names
calculate_faces_angles()as the remedy.
- is_angle_convex(edge: tuple[int, int]) bool#
Check if the angle at a given edge is convex.
Requires the face angles: see the angle precondition in the class docstring.
- Parameters:
edge – The edge to check for convex angle.
- Returns:
True if the angle at the edge is convex, False otherwise.
- Raises:
RuntimeError – When the face angles have not been computed; the message names
calculate_faces_angles()as the remedy.
- is_angle_sharp_convex(edge: tuple[int, int]) bool#
Check if the angle at a given edge is convex and not tangent: a corner the faces turn at.
Requires the face angles: see the angle precondition in the class docstring.
- Parameters:
edge – The edge to check.
- Returns:
True if the faces meet at a convex edge that is not smooth, False otherwise.
- Raises:
RuntimeError – When the face angles have not been computed; the message names
calculate_faces_angles()as the remedy.
- is_angle_smooth(edge: tuple[int, int]) bool#
Check if the angle at a given edge is smooth.
Requires the face angles: see the angle precondition in the class docstring.
- Parameters:
edge – The edge to check for smooth angle.
- Returns:
True if the angle at the edge is smooth, False otherwise.
- Raises:
RuntimeError – When the face angles have not been computed; the message names
calculate_faces_angles()as the remedy.
- is_open_shell() bool#
Return True if the shell has boundary (open) edges.
- is_surface(face_id: int, *surface_types: str) bool#
Return whether a face lies on a surface of one of the given types.
- Parameters:
face_id – The index of the face.
surface_types – The surface type names accepted, such as
"Plane"or"CylindricalSurface".
- Returns:
True when the face’s surface type is one of them; False when none is given.
- non_data_hash_attributes = ['graph', 'selected_faces', '_index', 'map_face_wires', 'allow_smooth', 'smooth_angular_tol', 'angles_calculated', 'faces_topology_calculated', 'faces_signatures_calculated', 'bboxes_faces', 'faces_signature_matrix']#
- plot_data(reference_path: str = '#', **kwargs) list#
Create the plot_data object used to represent the graph.
- property shape_index: ShapeIndex#
The index of the shape’s faces, edges and vertices that the graph’s face and edge ids are read in.
- to_dict(use_pointers: bool = True, memo=None, path: str = '#', id_method=True, id_memo=None, **kwargs) JsonObject#
Convert the AttributedAdjacencyGraph object to a serializable dictionary.
- touches(faces: Iterable[int], others: Collection[int]) bool#
Return whether a face of one set shares an edge with a face of another.
A face belonging to both sets does not make them touch by itself: a face is never its own neighbour.
- Parameters:
faces – The 0-based indices of the faces of the first set, each a face of the graph.
others – The faces of the second set.
- Returns:
True when some face of faces shares an edge with some face of others.
volmdlr_tools.graph.feature_vertex_graph module#
Signed feature-vertex graph derived from an Attributed Adjacency Graph.
Nodes are vertex indices lying on at least one signed (non-smooth) edge; edges are signed model edges carrying their vexity and oriented left/right faces. The graph is a pure index-based view of the AAG: it stores no geometry and keeps no reference to the source AAG. Consumers needing geometry pair this graph with the AAG.
- class volmdlr_tools.graph.feature_vertex_graph.FeatureVertexGraph(name: str = '', *, graph: MultiGraph | None = None)#
Bases:
GraphUndirected signed feature-vertex graph (multigraph keyed by model edge index).
Built from an
AttributedAdjacencyGraphviafrom_aag(). Edges that cannot be placed (boundary, seam, non-manifold, degenerate) are recorded inskipped_edgesrather than dropped silently. Pure-smooth and undefined edges are intentionally excluded (not feature boundaries) and are not skipped.deblend_skippedis empty on a freshly built graph; it is populated byvolmdlr_tools.graph.virtual_topology.deblend()with(face_id, reason)records for blends left in place (see that function for the reason codes).- concave_view() FeatureVertexGraph#
Return a sub-graph of the concave edges (sharp and tangent).
- convex_view() FeatureVertexGraph#
Return a sub-graph of the convex edges (sharp and tangent).
- classmethod dict_to_object(dict_: JsonObject, **kwargs) SerializableObject#
Rebuild the graph and skipped-edge tally from a dictionary produced by
to_dict().Parallel edges and all edge attributes (vexity, orientation, seam flag) are restored.
- property feature_vertex_indices: set[int]#
Return the set of vertex indices that are nodes of this graph.
- filter_edges(predicate: Callable[[dict], bool]) FeatureVertexGraph#
Return a fresh graph keeping only edges whose data satisfies
predicate.Nodes left with no edges are dropped.
skipped_edgesis carried over.- Parameters:
predicate – callable applied to each edge’s data dict.
- Returns:
a new
FeatureVertexGraphsnapshot.
- classmethod from_aag(aag: AttributedAdjacencyGraph) FeatureVertexGraph#
Build the feature-vertex graph from an Attributed Adjacency Graph.
- Parameters:
aag – the source graph; its face angles are computed if needed.
- Returns:
a new
FeatureVertexGraphsnapshot.
- to_dict(use_pointers: bool = True, memo=None, path: str = '#', id_method=True, id_memo=None, **kwargs) JsonObject#
Serialize the graph to a JSON-compatible dictionary.
The dictionary includes edge vexity, orientation, and the skipped-edge tally.
volmdlr_tools.graph.parting_lines module#
Parting lines: where the walls of a part lean off one direction in opposite senses.
A part made in a two-part mould, or forged between two dies, has its walls drafted so that each half can be drawn off: above the line where the halves meet the walls lean one way, below it they lean the other. That line is the parting line, and the direction the halves are drawn along is the pull direction.
The edges of a parting line are convex and each turns by a small angle, twice the draft at most. Each one says on its own which way the part is pulled: square to the edge, between the normals of its two faces. Edges that agree on that direction and close into a loop, with every wall leaning by one angle all along its edge, seed a parting plane. The line then carries on along every other edge lying in that plane whose two faces stand on opposite sides of it, such as a stretch of wall that is not drafted. It is a parting line when the faces above it and the faces below it are not joined without crossing it. Faces that run straight through the plane, such as a bore a core pin leaves, join neither side and are listed apart.
No direction needs to be given: the part may lie in its file at any angle. Two kinds of line are told apart: the outline of the part is parted, or only its holes are drafted from both sides and meet in the plane while its outer walls run straight through it.
A parting line that steps from one plane to another, and one whose drafted edges never close into a loop, are not read.
- class volmdlr_tools.graph.parting_lines.PartingLine(direction: tuple[float, float, float], levels: tuple[float, ...], edge_indices: tuple[int, ...], upper_face_indices: frozenset[int], lower_face_indices: frozenset[int], through_face_indices: frozenset[int], upper_draft: float, lower_draft: float, kind: Literal['outline', 'holes'])#
Bases:
objectA line along which a part’s walls lean off one direction in opposite senses, cutting the part in two.
- Parameters:
direction – The unit pull direction; the upper faces lie on its side of the line.
levels – Where the parting planes stand along
direction, one per plane the line lies in.edge_indices – 0-based indices of the edges the line runs along.
upper_face_indices – 0-based indices of the faces above the line.
lower_face_indices – 0-based indices of the faces below the line.
through_face_indices – 0-based indices of the faces running straight through the parting plane, such as a bore or an outer wall that is not drafted; they belong to neither side.
upper_draft – The median lean of the upper walls off
directionat the line, in radians.lower_draft – The median lean of the lower walls, in radians.
kind –
"outline"when the outline of the part is parted,"holes"when only its holes are drafted from both sides and meet in the plane.
- direction: tuple[float, float, float]#
- edge_indices: tuple[int, ...]#
- kind: Literal['outline', 'holes']#
- levels: tuple[float, ...]#
- lower_draft: float#
- lower_face_indices: frozenset[int]#
- through_face_indices: frozenset[int]#
- upper_draft: float#
- upper_face_indices: frozenset[int]#
- volmdlr_tools.graph.parting_lines.find_parting_lines(aag: AttributedAdjacencyGraph) tuple[PartingLine, ...]#
Return the parting lines of a part, with no pull direction given.
Computes the face angles of aag when they are not computed yet.
- Parameters:
aag – The graph of the part.
- Returns:
The parting lines found, each edge in one line at most; empty when the part has none.
Module contents#
Graph module.