Example of TSP with networkx for the graph and algorithm, scipy for Euclidean distance, numpy for linear algebra
Pick door, window etc and will collect all of the same BuiltInCategory in the active view
Uses element id to create complete graph where all nodes are connected to each other by an edge, then adds required X & Y coordinates, weights all the edges with distance
Solves TSP, checks for clockwise by picking three points and producing the matrix determinant
Rolls the list to the picked element and numbers from one
Edit: If you need to install networkx check out my post here
from collections import deque
import clr
import networkx as nx
import numpy as np
from networkx.algorithms.approximation import christofides
from scipy.spatial import distance
clr.AddReference("RevitServices")
from RevitServices.Persistence import DocumentManager
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import FilteredElementCollector, FamilyInstance, LocationCurve
def xy(item):
if hasattr(item, "Location"):
loc = item.Location
if isinstance(loc, LocationCurve):
point = loc.Curve.Evaluate(0.5, True)
else:
point = loc.Point
return point.X, point.Y
def id(item):
return item.Id.Value
def weights(edge):
return *edge, distance.euclidean(G.nodes[edge[0]]["pos"], G.nodes[edge[1]]["pos"])
def to_string(number, offset=1, fill=2):
return str(number + offset).zfill(fill)
doc = DocumentManager.Instance.CurrentDBDocument
start_elem = UnwrapElement(IN[0]) # type:ignore
clockwise = IN[1] # type:ignore
elements = (
FilteredElementCollector(doc, doc.ActiveView.Id)
.OfCategory(start_elem.Category.BuiltInCategory)
.OfClass(FamilyInstance)
.ToElements()
)
# Use id for nodes
ids = list(map(id, elements))
G = nx.complete_graph(ids)
points = dict(zip(ids, map(xy, elements)))
nx.set_node_attributes(G, points, "pos")
edge_weights = map(weights, G.edges())
G.add_weighted_edges_from(edge_weights)
# Solve TSP with Christofides algorithm
# Remove last element to avoid duplicate start/end node
cycle = christofides(G)[:-1]
# Check clockwise with determinant of 3 points in cycle
u, v, w = cycle[0], cycle[len(cycle) // 3], cycle[(len(cycle) * 2) // 3]
det = np.linalg.det([[1, *points[u]], [1, *points[v]], [1, *points[w]]])
# Determinant xor clockwise
if (det < 0) ^ clockwise:
cycle.reverse()
# Rotate list to start element
start_id = id(start_elem)
start_index = cycle.index(start_id)
cycle = deque(cycle)
cycle.rotate(-start_index)
OUT = cycle, map(to_string, range(len(cycle)))