COMPAS 2.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (468) hide show
  1. compas/__init__.py +274 -0
  2. compas/__main__.py +31 -0
  3. compas/_iotools.py +80 -0
  4. compas/_os.py +746 -0
  5. compas/colors/__init__.py +14 -0
  6. compas/colors/cmcrameri/acton.txt +256 -0
  7. compas/colors/cmcrameri/actonS.txt +100 -0
  8. compas/colors/cmcrameri/bam.txt +256 -0
  9. compas/colors/cmcrameri/bamO.txt +256 -0
  10. compas/colors/cmcrameri/bamako.txt +256 -0
  11. compas/colors/cmcrameri/bamakoS.txt +100 -0
  12. compas/colors/cmcrameri/batlow.txt +256 -0
  13. compas/colors/cmcrameri/batlowK.txt +256 -0
  14. compas/colors/cmcrameri/batlowS.txt +100 -0
  15. compas/colors/cmcrameri/batlowW.txt +256 -0
  16. compas/colors/cmcrameri/berlin.txt +256 -0
  17. compas/colors/cmcrameri/bilbao.txt +256 -0
  18. compas/colors/cmcrameri/bilbaoS.txt +100 -0
  19. compas/colors/cmcrameri/broc.txt +256 -0
  20. compas/colors/cmcrameri/brocO.txt +256 -0
  21. compas/colors/cmcrameri/buda.txt +256 -0
  22. compas/colors/cmcrameri/budaS.txt +100 -0
  23. compas/colors/cmcrameri/bukavu.txt +256 -0
  24. compas/colors/cmcrameri/cork.txt +256 -0
  25. compas/colors/cmcrameri/corkO.txt +256 -0
  26. compas/colors/cmcrameri/davos.txt +256 -0
  27. compas/colors/cmcrameri/davosS.txt +100 -0
  28. compas/colors/cmcrameri/devon.txt +256 -0
  29. compas/colors/cmcrameri/devonS.txt +100 -0
  30. compas/colors/cmcrameri/fes.txt +256 -0
  31. compas/colors/cmcrameri/grayC.txt +256 -0
  32. compas/colors/cmcrameri/grayCS.txt +100 -0
  33. compas/colors/cmcrameri/hawaii.txt +256 -0
  34. compas/colors/cmcrameri/hawaiiS.txt +100 -0
  35. compas/colors/cmcrameri/imola.txt +256 -0
  36. compas/colors/cmcrameri/imolaS.txt +100 -0
  37. compas/colors/cmcrameri/lajolla.txt +256 -0
  38. compas/colors/cmcrameri/lajollaS.txt +100 -0
  39. compas/colors/cmcrameri/lapaz.txt +256 -0
  40. compas/colors/cmcrameri/lapazS.txt +100 -0
  41. compas/colors/cmcrameri/lisbon.txt +256 -0
  42. compas/colors/cmcrameri/nuuk.txt +256 -0
  43. compas/colors/cmcrameri/nuukS.txt +100 -0
  44. compas/colors/cmcrameri/oleron.txt +256 -0
  45. compas/colors/cmcrameri/oslo.txt +256 -0
  46. compas/colors/cmcrameri/osloS.txt +100 -0
  47. compas/colors/cmcrameri/roma.txt +256 -0
  48. compas/colors/cmcrameri/romaO.txt +256 -0
  49. compas/colors/cmcrameri/tofino.txt +256 -0
  50. compas/colors/cmcrameri/tokyo.txt +256 -0
  51. compas/colors/cmcrameri/tokyoS.txt +100 -0
  52. compas/colors/cmcrameri/turku.txt +256 -0
  53. compas/colors/cmcrameri/turkuS.txt +100 -0
  54. compas/colors/cmcrameri/vanimo.txt +256 -0
  55. compas/colors/cmcrameri/vik.txt +256 -0
  56. compas/colors/cmcrameri/vikO.txt +256 -0
  57. compas/colors/color.py +1118 -0
  58. compas/colors/colordict.py +103 -0
  59. compas/colors/colormap.py +306 -0
  60. compas/colors/html_colors.py +149 -0
  61. compas/colors/mpl_colormap.py +1064 -0
  62. compas/data/__init__.py +31 -0
  63. compas/data/coercion.py +71 -0
  64. compas/data/conftest.py +10 -0
  65. compas/data/data.py +342 -0
  66. compas/data/encoders.py +240 -0
  67. compas/data/exceptions.py +2 -0
  68. compas/data/json.py +240 -0
  69. compas/data/samples/boxes.obj +250 -0
  70. compas/data/samples/butt_model.obj +2829 -0
  71. compas/data/samples/cone.stl +0 -0
  72. compas/data/samples/cube.off +16 -0
  73. compas/data/samples/cube_ascii.stl +56114 -0
  74. compas/data/samples/cube_binary.stl +0 -0
  75. compas/data/samples/cube_binary_2.stl +0 -0
  76. compas/data/samples/doosabin.json +1 -0
  77. compas/data/samples/faces.obj +63 -0
  78. compas/data/samples/faces_big.obj +9663 -0
  79. compas/data/samples/faces_reversed.obj +63 -0
  80. compas/data/samples/fink.obj +135 -0
  81. compas/data/samples/grid_irregular.obj +303 -0
  82. compas/data/samples/hypar.obj +148 -0
  83. compas/data/samples/lines.json +1 -0
  84. compas/data/samples/lines.obj +282 -0
  85. compas/data/samples/lines_big.obj +40322 -0
  86. compas/data/samples/lines_bigger.obj +161282 -0
  87. compas/data/samples/lines_noleaves.obj +422 -0
  88. compas/data/samples/mesh.obj +874 -0
  89. compas/data/samples/mesh_100_faces.json +1893 -0
  90. compas/data/samples/mesh_110_faces.json +2081 -0
  91. compas/data/samples/open_edges.obj +424 -0
  92. compas/data/samples/point.json +1 -0
  93. compas/data/samples/quadmesh.obj +183 -0
  94. compas/data/samples/quadmesh_planar.obj +181 -0
  95. compas/data/samples/saddle.obj +314 -0
  96. compas/data/samples/spline.obj +72 -0
  97. compas/data/samples/tubemesh.json +1 -0
  98. compas/data/samples/tubemesh.obj +378 -0
  99. compas/data/samples/tubemesh.off +374 -0
  100. compas/data/samples/tubemesh.ply +551 -0
  101. compas/data/schema.py +137 -0
  102. compas/data/validators.py +243 -0
  103. compas/datastructures/__init__.py +75 -0
  104. compas/datastructures/_mutablemapping.py +148 -0
  105. compas/datastructures/assembly/__init__.py +0 -0
  106. compas/datastructures/assembly/assembly.py +234 -0
  107. compas/datastructures/assembly/exceptions.py +6 -0
  108. compas/datastructures/assembly/part.py +228 -0
  109. compas/datastructures/attributes.py +85 -0
  110. compas/datastructures/cell_network/__init__.py +0 -0
  111. compas/datastructures/cell_network/cell_network.py +4190 -0
  112. compas/datastructures/datastructure.py +309 -0
  113. compas/datastructures/graph/__init__.py +0 -0
  114. compas/datastructures/graph/duality.py +197 -0
  115. compas/datastructures/graph/graph.py +2478 -0
  116. compas/datastructures/graph/operations/__init__.py +0 -0
  117. compas/datastructures/graph/operations/join.py +124 -0
  118. compas/datastructures/graph/operations/split.py +63 -0
  119. compas/datastructures/graph/planarity.py +292 -0
  120. compas/datastructures/graph/smoothing.py +59 -0
  121. compas/datastructures/mesh/__init__.py +0 -0
  122. compas/datastructures/mesh/conway.py +553 -0
  123. compas/datastructures/mesh/duality.py +104 -0
  124. compas/datastructures/mesh/mesh.py +5103 -0
  125. compas/datastructures/mesh/operations/__init__.py +0 -0
  126. compas/datastructures/mesh/operations/collapse.py +350 -0
  127. compas/datastructures/mesh/operations/extrude.py +0 -0
  128. compas/datastructures/mesh/operations/insert.py +120 -0
  129. compas/datastructures/mesh/operations/merge.py +83 -0
  130. compas/datastructures/mesh/operations/split.py +263 -0
  131. compas/datastructures/mesh/operations/substitute.py +37 -0
  132. compas/datastructures/mesh/operations/swap.py +62 -0
  133. compas/datastructures/mesh/operations/weld.py +107 -0
  134. compas/datastructures/mesh/remesh.py +234 -0
  135. compas/datastructures/mesh/slice.py +170 -0
  136. compas/datastructures/mesh/smoothing.py +187 -0
  137. compas/datastructures/mesh/subdivision.py +754 -0
  138. compas/datastructures/tree/__init__.py +0 -0
  139. compas/datastructures/tree/tree.py +504 -0
  140. compas/datastructures/volmesh/__init__.py +0 -0
  141. compas/datastructures/volmesh/volmesh.py +4203 -0
  142. compas/files/__init__.py +27 -0
  143. compas/files/_xml/__init__.py +0 -0
  144. compas/files/_xml/xml_cli.py +213 -0
  145. compas/files/_xml/xml_cpython.py +32 -0
  146. compas/files/_xml/xml_pre_38.py +58 -0
  147. compas/files/_xml/xml_shared.py +40 -0
  148. compas/files/gltf/__init__.py +0 -0
  149. compas/files/gltf/constants.py +59 -0
  150. compas/files/gltf/data_classes.py +657 -0
  151. compas/files/gltf/extensions.py +317 -0
  152. compas/files/gltf/gltf.py +92 -0
  153. compas/files/gltf/gltf_children.py +64 -0
  154. compas/files/gltf/gltf_content.py +615 -0
  155. compas/files/gltf/gltf_exporter.py +465 -0
  156. compas/files/gltf/gltf_mesh.py +273 -0
  157. compas/files/gltf/gltf_node.py +348 -0
  158. compas/files/gltf/gltf_parser.py +115 -0
  159. compas/files/gltf/gltf_reader.py +310 -0
  160. compas/files/gltf/gltf_scene.py +125 -0
  161. compas/files/gltf/helpers.py +59 -0
  162. compas/files/obj.py +680 -0
  163. compas/files/off.py +296 -0
  164. compas/files/ply.py +697 -0
  165. compas/files/stl.py +436 -0
  166. compas/files/xml.py +328 -0
  167. compas/geometry/__init__.py +772 -0
  168. compas/geometry/_core/__init__.py +0 -0
  169. compas/geometry/_core/_algebra.py +2826 -0
  170. compas/geometry/_core/angles.py +408 -0
  171. compas/geometry/_core/centroids.py +573 -0
  172. compas/geometry/_core/distance.py +895 -0
  173. compas/geometry/_core/normals.py +149 -0
  174. compas/geometry/_core/nurbs.py +367 -0
  175. compas/geometry/_core/predicates_2.py +582 -0
  176. compas/geometry/_core/predicates_3.py +1111 -0
  177. compas/geometry/_core/quaternions.py +196 -0
  178. compas/geometry/_core/size.py +204 -0
  179. compas/geometry/_core/tangent.py +56 -0
  180. compas/geometry/_core/transformations.py +1121 -0
  181. compas/geometry/_core/transformations_numpy.py +279 -0
  182. compas/geometry/bbox.py +145 -0
  183. compas/geometry/bbox_numpy.py +306 -0
  184. compas/geometry/bestfit.py +77 -0
  185. compas/geometry/bestfit_numpy.py +259 -0
  186. compas/geometry/booleans.py +297 -0
  187. compas/geometry/booleans_shapely.py +147 -0
  188. compas/geometry/brep/__init__.py +112 -0
  189. compas/geometry/brep/brep.py +1131 -0
  190. compas/geometry/brep/edge.py +302 -0
  191. compas/geometry/brep/errors.py +22 -0
  192. compas/geometry/brep/face.py +329 -0
  193. compas/geometry/brep/loop.py +87 -0
  194. compas/geometry/brep/trim.py +46 -0
  195. compas/geometry/brep/vertex.py +46 -0
  196. compas/geometry/contours.py +32 -0
  197. compas/geometry/curves/__init__.py +0 -0
  198. compas/geometry/curves/arc.py +429 -0
  199. compas/geometry/curves/bezier.py +345 -0
  200. compas/geometry/curves/circle.py +500 -0
  201. compas/geometry/curves/conic.py +16 -0
  202. compas/geometry/curves/curve.py +614 -0
  203. compas/geometry/curves/ellipse.py +408 -0
  204. compas/geometry/curves/hyperbola.py +336 -0
  205. compas/geometry/curves/line.py +431 -0
  206. compas/geometry/curves/nurbs.py +412 -0
  207. compas/geometry/curves/parabola.py +256 -0
  208. compas/geometry/curves/polyline.py +724 -0
  209. compas/geometry/frame.py +769 -0
  210. compas/geometry/geometry.py +296 -0
  211. compas/geometry/hull.py +146 -0
  212. compas/geometry/hull_numpy.py +82 -0
  213. compas/geometry/icp_numpy.py +104 -0
  214. compas/geometry/interpolation_barycentric.py +38 -0
  215. compas/geometry/interpolation_coons.py +102 -0
  216. compas/geometry/interpolation_tweening.py +87 -0
  217. compas/geometry/intersection.py +121 -0
  218. compas/geometry/intersections.py +1105 -0
  219. compas/geometry/kdtree.py +153 -0
  220. compas/geometry/offset.py +208 -0
  221. compas/geometry/pca_numpy.py +87 -0
  222. compas/geometry/plane.py +657 -0
  223. compas/geometry/point.py +664 -0
  224. compas/geometry/pointcloud.py +409 -0
  225. compas/geometry/polygon.py +473 -0
  226. compas/geometry/polyhedron.py +650 -0
  227. compas/geometry/projection.py +155 -0
  228. compas/geometry/quadmesh_planarize.py +30 -0
  229. compas/geometry/quadmesh_planarize_none.py +114 -0
  230. compas/geometry/quaternion.py +544 -0
  231. compas/geometry/reflection.py +102 -0
  232. compas/geometry/rotation.py +354 -0
  233. compas/geometry/scale.py +100 -0
  234. compas/geometry/shapes/__init__.py +0 -0
  235. compas/geometry/shapes/box.py +747 -0
  236. compas/geometry/shapes/capsule.py +472 -0
  237. compas/geometry/shapes/cone.py +309 -0
  238. compas/geometry/shapes/cylinder.py +355 -0
  239. compas/geometry/shapes/shape.py +300 -0
  240. compas/geometry/shapes/sphere.py +362 -0
  241. compas/geometry/shapes/torus.py +294 -0
  242. compas/geometry/shear.py +115 -0
  243. compas/geometry/surfaces/__init__.py +0 -0
  244. compas/geometry/surfaces/conical.py +166 -0
  245. compas/geometry/surfaces/cylindrical.py +251 -0
  246. compas/geometry/surfaces/extrusion.py +0 -0
  247. compas/geometry/surfaces/nurbs.py +380 -0
  248. compas/geometry/surfaces/planar.py +223 -0
  249. compas/geometry/surfaces/revolution.py +0 -0
  250. compas/geometry/surfaces/spherical.py +259 -0
  251. compas/geometry/surfaces/surface.py +689 -0
  252. compas/geometry/surfaces/toroidal.py +198 -0
  253. compas/geometry/transformation.py +554 -0
  254. compas/geometry/translation.py +104 -0
  255. compas/geometry/triangulation_delaunay.py +102 -0
  256. compas/geometry/triangulation_earclip.py +300 -0
  257. compas/geometry/trimesh_curvature.py +113 -0
  258. compas/geometry/trimesh_descent_numpy.py +26 -0
  259. compas/geometry/trimesh_geodistance.py +35 -0
  260. compas/geometry/trimesh_gradient_numpy.py +74 -0
  261. compas/geometry/trimesh_isolines.py +41 -0
  262. compas/geometry/trimesh_matrices.py +31 -0
  263. compas/geometry/trimesh_matrices_numpy.py +191 -0
  264. compas/geometry/trimesh_parametrisation.py +55 -0
  265. compas/geometry/trimesh_pull_points_numpy.py +216 -0
  266. compas/geometry/trimesh_remeshing.py +97 -0
  267. compas/geometry/trimesh_samplepoints_numpy.py +108 -0
  268. compas/geometry/trimesh_slicing.py +28 -0
  269. compas/geometry/trimesh_smoothing_numpy.py +34 -0
  270. compas/geometry/vector.py +889 -0
  271. compas/itertools.py +441 -0
  272. compas/linalg.py +634 -0
  273. compas/matrices.py +314 -0
  274. compas/plugins.py +488 -0
  275. compas/rpc/__init__.py +20 -0
  276. compas/rpc/__main__.py +77 -0
  277. compas/rpc/dispatcher.py +181 -0
  278. compas/rpc/errors.py +11 -0
  279. compas/rpc/proxy.py +437 -0
  280. compas/rpc/server.py +79 -0
  281. compas/rpc/services/__init__.py +0 -0
  282. compas/rpc/services/default.py +87 -0
  283. compas/rpc/services/watcher.py +43 -0
  284. compas/scene/__init__.py +56 -0
  285. compas/scene/assemblyobject.py +3 -0
  286. compas/scene/context.py +154 -0
  287. compas/scene/descriptors/__init__.py +0 -0
  288. compas/scene/descriptors/attribute.py +30 -0
  289. compas/scene/descriptors/color.py +91 -0
  290. compas/scene/descriptors/colordict.py +101 -0
  291. compas/scene/descriptors/protocol.py +12 -0
  292. compas/scene/exceptions.py +7 -0
  293. compas/scene/geometryobject.py +58 -0
  294. compas/scene/graphobject.py +173 -0
  295. compas/scene/meshobject.py +238 -0
  296. compas/scene/scene.py +144 -0
  297. compas/scene/sceneobject.py +253 -0
  298. compas/scene/volmeshobject.py +252 -0
  299. compas/tolerance.py +879 -0
  300. compas/topology/__init__.py +45 -0
  301. compas/topology/combinatorics.py +108 -0
  302. compas/topology/connectivity.py +129 -0
  303. compas/topology/orientation.py +204 -0
  304. compas/topology/traversal.py +567 -0
  305. compas/utilities/__init__.py +25 -0
  306. compas/utilities/azync.py +155 -0
  307. compas/utilities/datetime.py +40 -0
  308. compas/utilities/decorators.py +136 -0
  309. compas/utilities/remote.py +54 -0
  310. compas/utilities/ssh.py +169 -0
  311. compas-2.1.1.dist-info/AUTHORS.md +42 -0
  312. compas-2.1.1.dist-info/LICENSE +21 -0
  313. compas-2.1.1.dist-info/METADATA +132 -0
  314. compas-2.1.1.dist-info/RECORD +468 -0
  315. compas-2.1.1.dist-info/WHEEL +5 -0
  316. compas-2.1.1.dist-info/entry_points.txt +2 -0
  317. compas-2.1.1.dist-info/top_level.txt +4 -0
  318. compas_blender/__init__.py +250 -0
  319. compas_blender/collections.py +130 -0
  320. compas_blender/conversions/__init__.py +48 -0
  321. compas_blender/conversions/breps.py +0 -0
  322. compas_blender/conversions/colors.py +23 -0
  323. compas_blender/conversions/curves.py +125 -0
  324. compas_blender/conversions/geometry.py +161 -0
  325. compas_blender/conversions/meshes.py +148 -0
  326. compas_blender/conversions/surfaces.py +48 -0
  327. compas_blender/conversions/transformations.py +46 -0
  328. compas_blender/data.py +30 -0
  329. compas_blender/geometry/__init__.py +14 -0
  330. compas_blender/geometry/booleans.py +100 -0
  331. compas_blender/install.py +338 -0
  332. compas_blender/objects.py +326 -0
  333. compas_blender/print_python_path.py +18 -0
  334. compas_blender/scene/__init__.py +116 -0
  335. compas_blender/scene/boxobject.py +64 -0
  336. compas_blender/scene/capsuleobject.py +73 -0
  337. compas_blender/scene/circleobject.py +53 -0
  338. compas_blender/scene/coneobject.py +70 -0
  339. compas_blender/scene/curveobject.py +58 -0
  340. compas_blender/scene/cylinderobject.py +70 -0
  341. compas_blender/scene/frameobject.py +105 -0
  342. compas_blender/scene/graphobject.py +257 -0
  343. compas_blender/scene/lineobject.py +60 -0
  344. compas_blender/scene/meshobject.py +508 -0
  345. compas_blender/scene/planeobject.py +81 -0
  346. compas_blender/scene/pointcloudobject.py +67 -0
  347. compas_blender/scene/pointobject.py +71 -0
  348. compas_blender/scene/polygonobject.py +57 -0
  349. compas_blender/scene/polyhedronobject.py +57 -0
  350. compas_blender/scene/polylineobject.py +54 -0
  351. compas_blender/scene/sceneobject.py +249 -0
  352. compas_blender/scene/sphereobject.py +72 -0
  353. compas_blender/scene/surfaceobject.py +54 -0
  354. compas_blender/scene/torusobject.py +73 -0
  355. compas_blender/scene/vectorobject.py +69 -0
  356. compas_blender/scene/volmeshobject.py +475 -0
  357. compas_blender/utilities/__init__.py +38 -0
  358. compas_blender/utilities/drawing.py +768 -0
  359. compas_ghpython/__init__.py +124 -0
  360. compas_ghpython/components/Compas_FromJson/code.py +18 -0
  361. compas_ghpython/components/Compas_Info/code.py +15 -0
  362. compas_ghpython/components/Compas_RpcCall/code.py +31 -0
  363. compas_ghpython/components/Compas_ToJson/code.py +19 -0
  364. compas_ghpython/components/Compas_ToRhinoGeometry/code.py +15 -0
  365. compas_ghpython/components/__init__.py +99 -0
  366. compas_ghpython/install.py +29 -0
  367. compas_ghpython/scene/__init__.py +115 -0
  368. compas_ghpython/scene/boxobject.py +40 -0
  369. compas_ghpython/scene/brepobject.py +40 -0
  370. compas_ghpython/scene/capsuleobject.py +41 -0
  371. compas_ghpython/scene/circleobject.py +40 -0
  372. compas_ghpython/scene/coneobject.py +40 -0
  373. compas_ghpython/scene/curveobject.py +42 -0
  374. compas_ghpython/scene/cylinderobject.py +38 -0
  375. compas_ghpython/scene/ellipseobject.py +40 -0
  376. compas_ghpython/scene/frameobject.py +67 -0
  377. compas_ghpython/scene/graphobject.py +77 -0
  378. compas_ghpython/scene/lineobject.py +39 -0
  379. compas_ghpython/scene/meshobject.py +137 -0
  380. compas_ghpython/scene/planeobject.py +61 -0
  381. compas_ghpython/scene/pointobject.py +38 -0
  382. compas_ghpython/scene/polygonobject.py +48 -0
  383. compas_ghpython/scene/polyhedronobject.py +48 -0
  384. compas_ghpython/scene/polylineobject.py +39 -0
  385. compas_ghpython/scene/sceneobject.py +12 -0
  386. compas_ghpython/scene/sphereobject.py +39 -0
  387. compas_ghpython/scene/surfaceobject.py +42 -0
  388. compas_ghpython/scene/torusobject.py +39 -0
  389. compas_ghpython/scene/vectorobject.py +51 -0
  390. compas_ghpython/scene/volmeshobject.py +154 -0
  391. compas_ghpython/sets.py +83 -0
  392. compas_ghpython/timer.py +36 -0
  393. compas_ghpython/uninstall.py +31 -0
  394. compas_ghpython/utilities/__init__.py +33 -0
  395. compas_ghpython/utilities/drawing.py +457 -0
  396. compas_rhino/__init__.py +607 -0
  397. compas_rhino/conduits/__init__.py +16 -0
  398. compas_rhino/conduits/base.py +121 -0
  399. compas_rhino/conduits/faces.py +91 -0
  400. compas_rhino/conduits/labels.py +102 -0
  401. compas_rhino/conduits/lines.py +109 -0
  402. compas_rhino/conduits/points.py +111 -0
  403. compas_rhino/conversions/__init__.py +168 -0
  404. compas_rhino/conversions/breps.py +122 -0
  405. compas_rhino/conversions/curves.py +453 -0
  406. compas_rhino/conversions/docobjects.py +0 -0
  407. compas_rhino/conversions/exceptions.py +7 -0
  408. compas_rhino/conversions/extrusions.py +80 -0
  409. compas_rhino/conversions/geometry.py +187 -0
  410. compas_rhino/conversions/meshes.py +281 -0
  411. compas_rhino/conversions/shapes.py +291 -0
  412. compas_rhino/conversions/surfaces.py +355 -0
  413. compas_rhino/conversions/transformations.py +45 -0
  414. compas_rhino/geometry/__init__.py +44 -0
  415. compas_rhino/geometry/booleans.py +118 -0
  416. compas_rhino/geometry/brep/__init__.py +40 -0
  417. compas_rhino/geometry/brep/brep.py +554 -0
  418. compas_rhino/geometry/brep/builder.py +184 -0
  419. compas_rhino/geometry/brep/edge.py +202 -0
  420. compas_rhino/geometry/brep/face.py +285 -0
  421. compas_rhino/geometry/brep/loop.py +129 -0
  422. compas_rhino/geometry/brep/trim.py +99 -0
  423. compas_rhino/geometry/brep/vertex.py +76 -0
  424. compas_rhino/geometry/curves/__init__.py +43 -0
  425. compas_rhino/geometry/curves/curve.py +382 -0
  426. compas_rhino/geometry/curves/nurbs.py +298 -0
  427. compas_rhino/geometry/surfaces/__init__.py +50 -0
  428. compas_rhino/geometry/surfaces/nurbs.py +370 -0
  429. compas_rhino/geometry/surfaces/surface.py +407 -0
  430. compas_rhino/geometry/trimesh_curvature.py +344 -0
  431. compas_rhino/geometry/trimesh_slicing.py +65 -0
  432. compas_rhino/install.py +382 -0
  433. compas_rhino/install_plugin.py +169 -0
  434. compas_rhino/install_with_pip.py +20 -0
  435. compas_rhino/layers.py +347 -0
  436. compas_rhino/objects.py +1141 -0
  437. compas_rhino/print_python_path.py +18 -0
  438. compas_rhino/scene/__init__.py +123 -0
  439. compas_rhino/scene/boxobject.py +44 -0
  440. compas_rhino/scene/brepobject.py +41 -0
  441. compas_rhino/scene/capsuleobject.py +45 -0
  442. compas_rhino/scene/circleobject.py +43 -0
  443. compas_rhino/scene/coneobject.py +43 -0
  444. compas_rhino/scene/curveobject.py +43 -0
  445. compas_rhino/scene/cylinderobject.py +43 -0
  446. compas_rhino/scene/ellipseobject.py +44 -0
  447. compas_rhino/scene/frameobject.py +99 -0
  448. compas_rhino/scene/graphobject.py +364 -0
  449. compas_rhino/scene/helpers.py +33 -0
  450. compas_rhino/scene/lineobject.py +43 -0
  451. compas_rhino/scene/meshobject.py +673 -0
  452. compas_rhino/scene/planeobject.py +71 -0
  453. compas_rhino/scene/pointobject.py +43 -0
  454. compas_rhino/scene/polygonobject.py +45 -0
  455. compas_rhino/scene/polyhedronobject.py +45 -0
  456. compas_rhino/scene/polylineobject.py +43 -0
  457. compas_rhino/scene/sceneobject.py +123 -0
  458. compas_rhino/scene/sphereobject.py +43 -0
  459. compas_rhino/scene/surfaceobject.py +42 -0
  460. compas_rhino/scene/torusobject.py +43 -0
  461. compas_rhino/scene/vectorobject.py +49 -0
  462. compas_rhino/scene/volmeshobject.py +518 -0
  463. compas_rhino/ui.py +114 -0
  464. compas_rhino/uninstall.py +243 -0
  465. compas_rhino/uninstall_plugin.py +91 -0
  466. compas_rhino/utilities/__init__.py +37 -0
  467. compas_rhino/utilities/constructors.py +71 -0
  468. compas_rhino/utilities/drawing.py +1081 -0
@@ -0,0 +1,2478 @@
1
+ from __future__ import absolute_import
2
+ from __future__ import division
3
+ from __future__ import print_function
4
+
5
+ from ast import literal_eval
6
+ from itertools import combinations
7
+ from random import sample
8
+
9
+ import compas
10
+
11
+ if compas.PY2:
12
+ from collections import Mapping
13
+ else:
14
+ from collections.abc import Mapping
15
+
16
+ from compas.datastructures.attributes import EdgeAttributeView
17
+ from compas.datastructures.attributes import NodeAttributeView
18
+ from compas.datastructures.datastructure import Datastructure
19
+ from compas.files import OBJ
20
+ from compas.geometry import Box
21
+ from compas.geometry import Line
22
+ from compas.geometry import Point
23
+ from compas.geometry import Vector
24
+ from compas.geometry import add_vectors
25
+ from compas.geometry import bounding_box
26
+ from compas.geometry import centroid_points
27
+ from compas.geometry import distance_point_point
28
+ from compas.geometry import midpoint_line
29
+ from compas.geometry import normalize_vector
30
+ from compas.geometry import oriented_bounding_box
31
+ from compas.geometry import scale_vector
32
+ from compas.geometry import subtract_vectors
33
+ from compas.geometry import transform_points
34
+ from compas.tolerance import TOL
35
+ from compas.topology import astar_shortest_path
36
+ from compas.topology import breadth_first_traverse
37
+ from compas.topology import connected_components
38
+
39
+ from .duality import graph_find_cycles
40
+ from .operations.join import graph_join_edges
41
+ from .operations.split import graph_split_edge
42
+ from .planarity import graph_count_crossings
43
+ from .planarity import graph_embed_in_plane
44
+ from .planarity import graph_find_crossings
45
+ from .planarity import graph_is_crossed
46
+ from .planarity import graph_is_planar
47
+ from .planarity import graph_is_planar_embedding
48
+ from .planarity import graph_is_xy
49
+ from .smoothing import graph_smooth_centroid
50
+
51
+
52
+ class Graph(Datastructure):
53
+ """Data structure for describing the relationships between nodes connected by edges.
54
+
55
+ Parameters
56
+ ----------
57
+ default_node_attributes : dict, optional
58
+ Default values for node attributes.
59
+ default_edge_attributes : dict, optional
60
+ Default values for edge attributes.
61
+ name : str, optional
62
+ The name of the graph.
63
+ **kwargs : dict, optional
64
+ Additional keyword arguments, which are stored in the attributes dict.
65
+
66
+ Attributes
67
+ ----------
68
+ default_node_attributes : dict[str, Any]
69
+ dictionary containing default values for the attributes of nodes.
70
+ It is recommended to add a default to this dictionary using :meth:`update_default_node_attributes`
71
+ for every node attribute used in the data structure.
72
+ default_edge_attributes : dict[str, Any]
73
+ dictionary containing default values for the attributes of edges.
74
+ It is recommended to add a default to this dictionary using :meth:`update_default_edge_attributes`
75
+ for every edge attribute used in the data structure.
76
+
77
+ """
78
+
79
+ split_edge = graph_split_edge
80
+ join_edges = graph_join_edges
81
+ smooth = graph_smooth_centroid
82
+ is_crossed = graph_is_crossed
83
+ is_planar = graph_is_planar
84
+ is_planar_embedding = graph_is_planar_embedding
85
+ is_xy = graph_is_xy
86
+ count_crossings = graph_count_crossings
87
+ find_crossings = graph_find_crossings
88
+ embed_in_plane = graph_embed_in_plane
89
+ find_cycles = graph_find_cycles
90
+
91
+ DATASCHEMA = {
92
+ "type": "object",
93
+ "properties": {
94
+ "attributes": {"type": "object"},
95
+ "default_node_attributes": {"type": "object"},
96
+ "default_edge_attributes": {"type": "object"},
97
+ "node": {
98
+ "type": "object",
99
+ "additionalProperties": {"type": "object"},
100
+ },
101
+ "edge": {
102
+ "type": "object",
103
+ "additionalProperties": {
104
+ "type": "object",
105
+ "additionalProperties": {"type": "object"},
106
+ },
107
+ },
108
+ "max_node": {"type": "integer", "minimum": -1},
109
+ },
110
+ "required": [
111
+ "attributes",
112
+ "default_node_attributes",
113
+ "default_edge_attributes",
114
+ "node",
115
+ "edge",
116
+ "max_node",
117
+ ],
118
+ }
119
+
120
+ @property
121
+ def __data__(self):
122
+ return self.__before_json_dump__(
123
+ {
124
+ "attributes": self.attributes,
125
+ "default_node_attributes": self.default_node_attributes,
126
+ "default_edge_attributes": self.default_edge_attributes,
127
+ "node": self.node,
128
+ "edge": self.edge,
129
+ "max_node": self._max_node,
130
+ }
131
+ )
132
+
133
+ def __before_json_dump__(self, data):
134
+ data["node"] = {repr(key): attr for key, attr in data["node"].items()}
135
+ data["edge"] = {repr(u): {repr(v): attr for v, attr in nbrs.items()} for u, nbrs in data["edge"].items()}
136
+ return data
137
+
138
+ def __after_json_load__(self, data):
139
+ l_e = literal_eval
140
+ nodes = data["node"] or {}
141
+ edges = data["edge"] or {}
142
+ data["node"] = {l_e(node): attr for node, attr in nodes.items()}
143
+ data["edge"] = {l_e(u): {l_e(v): attr for v, attr in nbrs.items()} for u, nbrs in edges.items()}
144
+ return data
145
+
146
+ @classmethod
147
+ def __from_data__(cls, data):
148
+ graph = cls(
149
+ default_node_attributes=data.get("default_node_attributes"),
150
+ default_edge_attributes=data.get("default_edge_attributes"),
151
+ )
152
+ graph.attributes.update(data["attributes"] or {})
153
+ data = graph.__after_json_load__(data)
154
+ for node, attr in iter(data["node"].items()):
155
+ graph.add_node(key=node, attr_dict=attr)
156
+ for u, nbrs in iter(data["edge"].items()):
157
+ for v, attr in iter(nbrs.items()):
158
+ graph.add_edge(u, v, attr_dict=attr)
159
+ graph._max_node = data.get("max_node", graph._max_node)
160
+ return graph
161
+
162
+ def __init__(self, default_node_attributes=None, default_edge_attributes=None, name=None, **kwargs):
163
+ super(Graph, self).__init__(kwargs, name=name)
164
+ self._max_node = -1
165
+ self.node = {}
166
+ self.edge = {}
167
+ self.adjacency = {}
168
+ self.default_node_attributes = {"x": 0.0, "y": 0.0, "z": 0.0}
169
+ self.default_edge_attributes = {}
170
+ if default_node_attributes:
171
+ self.default_node_attributes.update(default_node_attributes)
172
+ if default_edge_attributes:
173
+ self.default_edge_attributes.update(default_edge_attributes)
174
+
175
+ def __str__(self):
176
+ tpl = "<Graph with {} nodes, {} edges>"
177
+ return tpl.format(self.number_of_nodes(), self.number_of_edges())
178
+
179
+ # --------------------------------------------------------------------------
180
+ # Constructors
181
+ # --------------------------------------------------------------------------
182
+
183
+ @classmethod
184
+ def from_edges(cls, edges):
185
+ """Create a new graph instance from information about the edges.
186
+
187
+ Parameters
188
+ ----------
189
+ edges : list[tuple[hashable, hashable]]
190
+ The edges of the graph as pairs of node identifiers.
191
+
192
+ Returns
193
+ -------
194
+ :class:`compas.datastructures.Graph`
195
+
196
+ See Also
197
+ --------
198
+ :meth:`from_networkx`
199
+
200
+ """
201
+ graph = cls()
202
+ for u, v in edges:
203
+ if u not in graph.node:
204
+ graph.add_node(u)
205
+ if v not in graph.node:
206
+ graph.add_node(v)
207
+ graph.add_edge(u, v)
208
+
209
+ @classmethod
210
+ def from_networkx(cls, graph):
211
+ """Create a new graph instance from a NetworkX DiGraph instance.
212
+
213
+ Parameters
214
+ ----------
215
+ graph : networkx.DiGraph
216
+ NetworkX instance of a directed graph.
217
+
218
+ Returns
219
+ -------
220
+ :class:`compas.datastructures.Graph`
221
+
222
+ See Also
223
+ --------
224
+ :meth:`to_networkx`
225
+ :meth:`from_edges`
226
+
227
+ """
228
+ g = cls()
229
+ g.name = graph.graph.get("name")
230
+
231
+ for node in graph.nodes():
232
+ g.add_node(node, **graph.nodes[node])
233
+
234
+ for edge in graph.edges():
235
+ g.add_edge(*edge, **graph.edges[edge])
236
+
237
+ return g
238
+
239
+ @classmethod
240
+ def from_obj(cls, filepath, precision=None):
241
+ """Construct a graph from the data contained in an OBJ file.
242
+
243
+ Parameters
244
+ ----------
245
+ filepath : path string | file-like object | URL string
246
+ A path, a file-like object or a URL pointing to a file.
247
+ precision: str, optional
248
+ The precision of the geometric map that is used to connect the lines.
249
+
250
+ Returns
251
+ -------
252
+ :class:`compas.datastructures.Graph`
253
+ A graph object.
254
+
255
+ See Also
256
+ --------
257
+ :meth:`to_obj`
258
+ :meth:`from_lines`, :meth:`from_nodes_and_edges`, :meth:`from_pointcloud`
259
+ :class:`compas.files.OBJ`
260
+
261
+ """
262
+ graph = cls()
263
+ obj = OBJ(filepath, precision)
264
+ obj.read()
265
+ nodes = obj.vertices
266
+ edges = obj.lines
267
+ for i, (x, y, z) in enumerate(nodes): # type: ignore
268
+ graph.add_node(i, x=x, y=y, z=z)
269
+ for edge in edges: # type: ignore
270
+ graph.add_edge(*edge)
271
+ return graph
272
+
273
+ @classmethod
274
+ def from_lines(cls, lines, precision=None):
275
+ """Construct a graph from a set of lines represented by their start and end point coordinates.
276
+
277
+ Parameters
278
+ ----------
279
+ lines : list[tuple[list[float, list[float]]]]
280
+ A list of pairs of point coordinates.
281
+ precision : int, optional
282
+ Precision for converting numbers to strings.
283
+ Default is :attr:`TOL.precision`.
284
+
285
+ Returns
286
+ -------
287
+ :class:`compas.datastructures.Graph`
288
+ A graph object.
289
+
290
+ See Also
291
+ --------
292
+ :meth:`to_lines`
293
+ :meth:`from_obj`, :meth:`from_nodes_and_edges`, :meth:`from_pointcloud`
294
+
295
+ """
296
+ graph = cls()
297
+ edges = []
298
+ node = {}
299
+ for line in lines:
300
+ sp = line[0]
301
+ ep = line[1]
302
+ a = TOL.geometric_key(sp, precision)
303
+ b = TOL.geometric_key(ep, precision)
304
+ node[a] = sp
305
+ node[b] = ep
306
+ edges.append((a, b))
307
+ key_index = dict((k, i) for i, k in enumerate(iter(node)))
308
+ for key, xyz in iter(node.items()):
309
+ i = key_index[key]
310
+ graph.add_node(i, x=xyz[0], y=xyz[1], z=xyz[2])
311
+ for u, v in edges:
312
+ i = key_index[u]
313
+ j = key_index[v]
314
+ graph.add_edge(i, j)
315
+ return graph
316
+
317
+ @classmethod
318
+ def from_nodes_and_edges(cls, nodes, edges):
319
+ """Construct a graph from nodes and edges.
320
+
321
+ Parameters
322
+ ----------
323
+ nodes : list[list[float]] | dict[hashable, list[float]]
324
+ A list of node coordinates or a dictionary of keys pointing to node coordinates to specify keys.
325
+ edges : list[tuple[hashable, hshable]]
326
+
327
+ Returns
328
+ -------
329
+ :class:`compas.datastructures.Graph`
330
+ A graph object.
331
+
332
+ See Also
333
+ --------
334
+ :meth:`to_nodes_and_edges`
335
+ :meth:`from_obj`, :meth:`from_lines`, :meth:`from_pointcloud`
336
+
337
+ """
338
+ graph = cls()
339
+
340
+ if isinstance(nodes, Mapping):
341
+ for key, (x, y, z) in nodes.items():
342
+ graph.add_node(key, x=x, y=y, z=z)
343
+ else:
344
+ for i, (x, y, z) in enumerate(nodes):
345
+ graph.add_node(i, x=x, y=y, z=z)
346
+
347
+ for u, v in edges:
348
+ graph.add_edge(u, v)
349
+
350
+ return graph
351
+
352
+ @classmethod
353
+ def from_pointcloud(cls, cloud, degree=3):
354
+ """Construct a graph from random connections between the points of a pointcloud.
355
+
356
+ Parameters
357
+ ----------
358
+ cloud : :class:`compas.geometry.Pointcloud`
359
+ A pointcloud object.
360
+ degree : int, optional
361
+ The number of connections per node.
362
+
363
+ Returns
364
+ -------
365
+ :class:`compas.datastructures.Graph`
366
+ A graph object.
367
+
368
+ See Also
369
+ --------
370
+ :meth:`to_points`
371
+ :meth:`from_obj`, :meth:`from_lines`, :meth:`from_nodes_and_edges`
372
+
373
+ """
374
+ graph = cls()
375
+ for x, y, z in cloud:
376
+ graph.add_node(x=x, y=y, z=z)
377
+ for u in graph.nodes():
378
+ for v in graph.node_sample(size=degree):
379
+ graph.add_edge(u, v)
380
+ return graph
381
+
382
+ # --------------------------------------------------------------------------
383
+ # Converters
384
+ # --------------------------------------------------------------------------
385
+
386
+ def to_obj(self):
387
+ """Write the graph to an OBJ file.
388
+
389
+ Parameters
390
+ ----------
391
+ filepath : path string | file-like object
392
+ A path or a file-like object pointing to a file.
393
+
394
+ Returns
395
+ -------
396
+ None
397
+
398
+ See Also
399
+ --------
400
+ :meth:`from_obj`
401
+ :meth:`to_lines`, :meth:`to_nodes_and_edges`, :meth:`to_points`
402
+
403
+ """
404
+ raise NotImplementedError
405
+
406
+ def to_points(self):
407
+ """Return the coordinates of the graph.
408
+
409
+ Returns
410
+ -------
411
+ list[list[float]]
412
+ A list with the coordinates of the vertices of the graph.
413
+
414
+ See Also
415
+ --------
416
+ :meth:`from_pointcloud`
417
+ :meth:`to_lines`, :meth:`to_nodes_and_edges`, :meth:`to_obj`
418
+
419
+ """
420
+ return [self.node_coordinates(key) for key in self.nodes()]
421
+
422
+ def to_lines(self):
423
+ """Return the lines of the graph as pairs of start and end point coordinates.
424
+
425
+ Returns
426
+ -------
427
+ list[tuple[list[float], list[float]]]
428
+ A list of lines each defined by a pair of point coordinates.
429
+
430
+ See Also
431
+ --------
432
+ :meth:`from_lines`
433
+ :meth:`to_nodes_and_edges`, :meth:`to_obj`, :meth:`to_points`
434
+
435
+ """
436
+ return [self.edge_coordinates(edge) for edge in self.edges()]
437
+
438
+ def to_nodes_and_edges(self):
439
+ """Return the nodes and edges of a graph.
440
+
441
+ Returns
442
+ -------
443
+ list[list[float]]
444
+ A list of nodes, represented by their XYZ coordinates.
445
+ list[tuple[hashable, hashable]]
446
+ A list of edges, with each edge represented by a pair of indices in the node list.
447
+
448
+ See Also
449
+ --------
450
+ :meth:`from_nodes_and_edges`
451
+ :meth:`to_lines`, :meth:`to_obj`, :meth:`to_points`
452
+
453
+ """
454
+ key_index = dict((key, index) for index, key in enumerate(self.nodes()))
455
+ nodes = [self.node_coordinates(key) for key in self.nodes()]
456
+ edges = [(key_index[u], key_index[v]) for u, v in self.edges()]
457
+ return nodes, edges
458
+
459
+ def to_networkx(self):
460
+ """Create a new NetworkX graph instance from a graph.
461
+
462
+ Returns
463
+ -------
464
+ networkx.DiGraph
465
+ A newly created NetworkX DiGraph.
466
+
467
+ See Also
468
+ --------
469
+ :meth:`from_networkx`
470
+
471
+ """
472
+ import networkx as nx
473
+
474
+ G = nx.DiGraph()
475
+ G.graph["name"] = self.name # type: ignore
476
+
477
+ for node, attr in self.nodes(data=True):
478
+ G.add_node(node, **attr) # type: ignore
479
+
480
+ for edge, attr in self.edges(data=True):
481
+ G.add_edge(*edge, **attr)
482
+
483
+ return G
484
+
485
+ # --------------------------------------------------------------------------
486
+ # Helpers
487
+ # --------------------------------------------------------------------------
488
+
489
+ def clear(self):
490
+ """Clear all the graph data.
491
+
492
+ Returns
493
+ -------
494
+ None
495
+
496
+ """
497
+ del self.node
498
+ del self.edge
499
+ del self.adjacency
500
+ self.node = {}
501
+ self.edge = {}
502
+ self.adjacency = {}
503
+
504
+ def node_sample(self, size=1):
505
+ """Get a list of identifiers of a random set of n nodes.
506
+
507
+ Parameters
508
+ ----------
509
+ size : int, optional
510
+ The size of the sample.
511
+
512
+ Returns
513
+ -------
514
+ list[hashable]
515
+ The identifiers of the nodes.
516
+
517
+ See Also
518
+ --------
519
+ :meth:`edge_sample`
520
+
521
+ """
522
+ return sample(list(self.nodes()), size)
523
+
524
+ def edge_sample(self, size=1):
525
+ """Get the identifiers of a set of random edges.
526
+
527
+ Parameters
528
+ ----------
529
+ size : int, optional
530
+ The size of the sample.
531
+
532
+ Returns
533
+ -------
534
+ list[tuple[hashable, hashable]]
535
+ The identifiers of the random edges.
536
+
537
+ See Also
538
+ --------
539
+ :meth:`node_sample`
540
+
541
+ """
542
+ return sample(list(self.edges()), size)
543
+
544
+ def node_index(self):
545
+ """Returns a dictionary that maps node identifiers to their corresponding index in a node list or array.
546
+
547
+ Returns
548
+ -------
549
+ dict[hashable, int]
550
+ A dictionary of node-index pairs.
551
+
552
+ See Also
553
+ --------
554
+ :meth:`index_node`
555
+ :meth:`edge_index`
556
+
557
+ """
558
+ return {key: index for index, key in enumerate(self.nodes())}
559
+
560
+ def index_node(self):
561
+ """Returns a dictionary that maps the indices of a node list to keys in a node dictionary.
562
+
563
+ Returns
564
+ -------
565
+ dict[int, hashable]
566
+ A dictionary of index-node pairs.
567
+
568
+ See Also
569
+ --------
570
+ :meth:`node_index`
571
+ :meth:`index_edge`
572
+
573
+ """
574
+ return dict(enumerate(self.nodes()))
575
+
576
+ def edge_index(self):
577
+ """Returns a dictionary that maps edge identifiers (i.e. pairs of vertex identifiers)
578
+ to the corresponding edge index in a list or array of edges.
579
+
580
+ Returns
581
+ -------
582
+ dict[tuple[hashable, hashable], int]
583
+ A dictionary of uv-index pairs.
584
+
585
+ See Also
586
+ --------
587
+ :meth:`index_edge`
588
+ :meth:`node_index`
589
+
590
+ """
591
+ return {(u, v): index for index, (u, v) in enumerate(self.edges())}
592
+
593
+ def index_edge(self):
594
+ """Returns a dictionary that maps edges in a list to the corresponding
595
+ vertex identifier pairs.
596
+
597
+ Returns
598
+ -------
599
+ dict[int, tuple[hashable, hashable]]
600
+ A dictionary of index-uv pairs.
601
+
602
+ See Also
603
+ --------
604
+ :meth:`edge_index`
605
+ :meth:`index_node`
606
+
607
+ """
608
+ return dict(enumerate(self.edges()))
609
+
610
+ def node_gkey(self, precision=None):
611
+ """Returns a dictionary that maps node identifiers to the corresponding
612
+ *geometric key* up to a certain precision.
613
+
614
+ Parameters
615
+ ----------
616
+ precision : int, optional
617
+ Precision for converting numbers to strings.
618
+ Default is :attr:`TOL.precision`.
619
+
620
+ Returns
621
+ -------
622
+ dict[hashable, str]
623
+ A dictionary of (node, geometric key) pairs.
624
+
625
+ See Also
626
+ --------
627
+ :meth:`gkey_node`
628
+ :meth:`compas.Tolerance.geometric_key`
629
+
630
+ """
631
+ gkey = TOL.geometric_key
632
+ xyz = self.node_coordinates
633
+ return {key: gkey(xyz(key), precision) for key in self.nodes()}
634
+
635
+ def gkey_node(self, precision=None):
636
+ """Returns a dictionary that maps *geometric keys* of a certain precision
637
+ to the identifiers of the corresponding nodes.
638
+
639
+ Parameters
640
+ ----------
641
+ precision : int, optional
642
+ Precision for converting numbers to strings.
643
+ Default is :attr:`TOL.precision`.
644
+
645
+ Returns
646
+ -------
647
+ dict[str, hashable]
648
+ A dictionary of (geometric key, node) pairs.
649
+
650
+ See Also
651
+ --------
652
+ :meth:`node_gkey`
653
+ :meth:`compas.Tolerance.geometric_key`
654
+
655
+ """
656
+ gkey = TOL.geometric_key
657
+ xyz = self.node_coordinates
658
+ return {gkey(xyz(key), precision): key for key in self.nodes()}
659
+
660
+ # --------------------------------------------------------------------------
661
+ # Builders
662
+ # --------------------------------------------------------------------------
663
+
664
+ def add_node(self, key=None, attr_dict=None, **kwattr):
665
+ """Add a node and specify its attributes (optional).
666
+
667
+ Parameters
668
+ ----------
669
+ key : hashable, optional
670
+ An identifier for the node.
671
+ Defaults to None, in which case an identifier of type int is automatically generated.
672
+ attr_dict : dict[str, Any], optional
673
+ A dictionary of vertex attributes.
674
+ **kwattr : dict[str, Any], optional
675
+ A dictionary of additional attributes compiled of remaining named arguments.
676
+
677
+ Returns
678
+ -------
679
+ hashable
680
+ The identifier of the node.
681
+
682
+ See Also
683
+ --------
684
+ :meth:`add_edge`
685
+ :meth:`delete_node`
686
+
687
+ Notes
688
+ -----
689
+ If no key is provided for the node, one is generated
690
+ automatically. An automatically generated key increments the highest
691
+ integer key in use by 1.
692
+
693
+ Examples
694
+ --------
695
+ >>> graph = Graph()
696
+ >>> node = graph.add_node()
697
+ >>> node
698
+ 0
699
+
700
+ """
701
+ if key is None:
702
+ key = self._max_node = self._max_node + 1
703
+ try:
704
+ if key > self._max_node:
705
+ self._max_node = key
706
+ except (ValueError, TypeError):
707
+ pass
708
+
709
+ if key not in self.node:
710
+ self.node[key] = {}
711
+ self.edge[key] = {}
712
+ self.adjacency[key] = {}
713
+ attr = attr_dict or {}
714
+ attr.update(kwattr)
715
+ self.node[key].update(attr)
716
+ return key
717
+
718
+ def add_edge(self, u, v, attr_dict=None, **kwattr):
719
+ """Add an edge and specify its attributes.
720
+
721
+ Parameters
722
+ ----------
723
+ u : hashable
724
+ The identifier of the first node of the edge.
725
+ v : hashable
726
+ The identifier of the second node of the edge.
727
+ attr_dict : dict[str, Any], optional
728
+ A dictionary of edge attributes.
729
+ **kwattr : dict[str, Any], optional
730
+ A dictionary of additional attributes compiled of remaining named arguments.
731
+
732
+ Returns
733
+ -------
734
+ tuple[hashable, hashable]
735
+ The identifier of the edge.
736
+
737
+ See Also
738
+ --------
739
+ :meth:`add_node`
740
+ :meth:`delete_edge`
741
+
742
+ Examples
743
+ --------
744
+ >>>
745
+
746
+ """
747
+ attr = attr_dict or {}
748
+ attr.update(kwattr)
749
+ if u not in self.node:
750
+ u = self.add_node(u)
751
+ if v not in self.node:
752
+ v = self.add_node(v)
753
+ data = self.edge[u].get(v, {})
754
+ data.update(attr)
755
+ self.edge[u][v] = data
756
+ if v not in self.adjacency[u]:
757
+ self.adjacency[u][v] = None
758
+ if u not in self.adjacency[v]:
759
+ self.adjacency[v][u] = None
760
+ return u, v
761
+
762
+ # --------------------------------------------------------------------------
763
+ # Modifiers
764
+ # --------------------------------------------------------------------------
765
+
766
+ def delete_node(self, key):
767
+ """Delete a node from the graph.
768
+
769
+ Parameters
770
+ ----------
771
+ key : hashable
772
+ The identifier of the node.
773
+
774
+ Returns
775
+ -------
776
+ None
777
+
778
+ See Also
779
+ --------
780
+ :meth:`delete_edge`
781
+ :meth:`add_node`
782
+
783
+ Examples
784
+ --------
785
+ >>>
786
+
787
+ """
788
+ if key in self.edge:
789
+ del self.edge[key]
790
+ if key in self.adjacency:
791
+ del self.adjacency[key]
792
+ if key in self.node:
793
+ del self.node[key]
794
+ for u in list(self.edge):
795
+ for v in list(self.edge[u]):
796
+ if v == key:
797
+ del self.edge[u][v]
798
+ for u in self.adjacency:
799
+ for v in list(self.adjacency[u]):
800
+ if v == key:
801
+ del self.adjacency[u][v]
802
+
803
+ def delete_edge(self, edge):
804
+ """Delete an edge from the graph.
805
+
806
+ Parameters
807
+ ----------
808
+ edge : tuple[hashable, hashable]
809
+ The identifier of the edge as a pair of node identifiers.
810
+
811
+ Returns
812
+ -------
813
+ None
814
+
815
+ See Also
816
+ --------
817
+ :meth:`delete_node`
818
+ :meth:`add_edge`
819
+
820
+ Examples
821
+ --------
822
+ >>>
823
+
824
+ """
825
+ u, v = edge
826
+
827
+ if u in self.edge and v in self.edge[u]:
828
+ del self.edge[u][v]
829
+
830
+ if u == v: # invalid edge
831
+ del self.adjacency[u][v]
832
+ elif v not in self.edge or u not in self.edge[v]:
833
+ del self.adjacency[u][v]
834
+ del self.adjacency[v][u]
835
+ # else: an edge in an opposite direction exists, we don't want to delete the adjacency
836
+
837
+ # --------------------------------------------------------------------------
838
+ # Info
839
+ # --------------------------------------------------------------------------
840
+
841
+ def summary(self):
842
+ """Return a summary of the graph.
843
+
844
+ Returns
845
+ -------
846
+ str
847
+ The formatted summary.
848
+
849
+ """
850
+ tpl = "\n".join(
851
+ [
852
+ "{} summary",
853
+ "=" * (len(self.name) + len(" summary")),
854
+ "- nodes: {}",
855
+ "- edges: {}",
856
+ ]
857
+ )
858
+ return tpl.format(self.name, self.number_of_nodes(), self.number_of_edges())
859
+
860
+ def number_of_nodes(self):
861
+ """Compute the number of nodes of the graph.
862
+
863
+ Returns
864
+ -------
865
+ int
866
+ The number of nodes.
867
+
868
+ See Also
869
+ --------
870
+ :meth:`number_of_edges`
871
+
872
+ """
873
+ return len(list(self.nodes()))
874
+
875
+ def number_of_edges(self):
876
+ """Compute the number of edges of the graph.
877
+
878
+ Returns
879
+ -------
880
+ int
881
+ The number of edges.
882
+
883
+ See Also
884
+ --------
885
+ :meth:`number_of_nodes`
886
+
887
+ """
888
+ return len(list(self.edges()))
889
+
890
+ def is_connected(self):
891
+ """Verify that the graph is connected.
892
+
893
+
894
+ Returns
895
+ -------
896
+ bool
897
+ True, if the graph is connected.
898
+ False, otherwise.
899
+
900
+ Notes
901
+ -----
902
+ A graph is connected if for every two vertices a path exists connecting them.
903
+
904
+ Examples
905
+ --------
906
+ >>> import compas
907
+ >>> from compas.datastructures import Graph
908
+ >>> graph = Graph.from_obj(compas.get("lines.obj"))
909
+ >>> graph.is_connected()
910
+ True
911
+
912
+ """
913
+ if self.number_of_nodes() == 0:
914
+ return False
915
+ nodes = breadth_first_traverse(self.adjacency, self.node_sample(size=1)[0])
916
+ return len(nodes) == self.number_of_nodes()
917
+
918
+ # --------------------------------------------------------------------------
919
+ # Accessors
920
+ # --------------------------------------------------------------------------
921
+
922
+ def nodes(self, data=False):
923
+ """Iterate over the nodes of the graph.
924
+
925
+ Parameters
926
+ ----------
927
+ data : bool, optional
928
+ If True, yield the node attributes in addition to the node identifiers.
929
+
930
+ Yields
931
+ ------
932
+ hashable | tuple[hashable, dict[str, Any]]
933
+ If `data` is False, the next node identifier.
934
+ If `data` is True, the next node as a (key, attr) tuple.
935
+
936
+ See Also
937
+ --------
938
+ :meth:`nodes_where`, :meth:`nodes_where_predicate`
939
+ :meth:`edges`, :meth:`edges_where`, :meth:`edges_where_predicate`
940
+
941
+ """
942
+ for key in self.node:
943
+ if not data:
944
+ yield key
945
+ else:
946
+ yield key, self.node_attributes(key)
947
+
948
+ def nodes_where(self, conditions=None, data=False, **kwargs):
949
+ """Get nodes for which a certain condition or set of conditions is true.
950
+
951
+ Parameters
952
+ ----------
953
+ conditions : dict, optional
954
+ A set of conditions in the form of key-value pairs.
955
+ The keys should be attribute names. The values can be attribute
956
+ values or ranges of attribute values in the form of min/max pairs.
957
+ data : bool, optional
958
+ If True, yield the node attributes in addition to the node identifiers.
959
+
960
+ Yields
961
+ ------
962
+ hashable | tuple[hashable, dict[str, Any]]
963
+ If `data` is False, the next node that matches the condition.
964
+ If `data` is True, the next node and its attributes.
965
+
966
+ See Also
967
+ --------
968
+ :meth:`nodes`, :meth:`nodes_where_predicate`
969
+ :meth:`edges`, :meth:`edges_where`, :meth:`edges_where_predicate`
970
+
971
+ """
972
+ conditions = conditions or {}
973
+ conditions.update(kwargs)
974
+
975
+ for key, attr in self.nodes(True):
976
+ is_match = True
977
+ attr = attr or {}
978
+
979
+ for name, value in conditions.items():
980
+ method = getattr(self, name, None)
981
+
982
+ if callable(method):
983
+ val = method(key)
984
+ if isinstance(val, list):
985
+ if value not in val:
986
+ is_match = False
987
+ break
988
+ break
989
+ if isinstance(value, (tuple, list)):
990
+ minval, maxval = value
991
+ if val < minval or val > maxval:
992
+ is_match = False
993
+ break
994
+ else:
995
+ if value != val:
996
+ is_match = False
997
+ break
998
+
999
+ else:
1000
+ if name not in attr:
1001
+ is_match = False
1002
+ break
1003
+ if isinstance(attr[name], list):
1004
+ if value not in attr[name]:
1005
+ is_match = False
1006
+ break
1007
+ break
1008
+ if isinstance(value, (tuple, list)):
1009
+ minval, maxval = value
1010
+ if attr[name] < minval or attr[name] > maxval:
1011
+ is_match = False
1012
+ break
1013
+ else:
1014
+ if value != attr[name]:
1015
+ is_match = False
1016
+ break
1017
+
1018
+ if is_match:
1019
+ if data:
1020
+ yield key, attr
1021
+ else:
1022
+ yield key
1023
+
1024
+ def nodes_where_predicate(self, predicate, data=False):
1025
+ """Get nodes for which a certain condition or set of conditions is true using a lambda function.
1026
+
1027
+ Parameters
1028
+ ----------
1029
+ predicate : callable
1030
+ The condition you want to evaluate.
1031
+ The callable takes 2 parameters: the node identifier and the node attributes, and should return True or False.
1032
+ data : bool, optional
1033
+ If True, yield the node attributes in addition to the node identifiers.
1034
+
1035
+ Yields
1036
+ ------
1037
+ hashable | tuple[hashable, dict[str, Any]]
1038
+ If `data` is False, the next node that matches the condition.
1039
+ If `data` is True, the next node and its attributes.
1040
+
1041
+ See Also
1042
+ --------
1043
+ :meth:`nodes`, :meth:`nodes_where`
1044
+ :meth:`edges`, :meth:`edges_where`, :meth:`edges_where_predicate`
1045
+
1046
+ Examples
1047
+ --------
1048
+ >>>
1049
+
1050
+ """
1051
+ for key, attr in self.nodes(True):
1052
+ if predicate(key, attr):
1053
+ if data:
1054
+ yield key, attr
1055
+ else:
1056
+ yield key
1057
+
1058
+ def edges(self, data=False):
1059
+ """Iterate over the edges of the graph.
1060
+
1061
+ Parameters
1062
+ ----------
1063
+ data : bool, optional
1064
+ If True, yield the edge attributes in addition to the edge identifiers.
1065
+
1066
+ Yields
1067
+ ------
1068
+ tuple[hashable, hashable] | tuple[tuple[hashable, hashable], dict[str, Any]]
1069
+ If `data` is False, the next edge identifier (u, v).
1070
+ If `data` is True, the next edge identifier and its attributes as a ((u, v), attr) tuple.
1071
+
1072
+ See Also
1073
+ --------
1074
+ :meth:`edges_where`, :meth:`edges_where_predicate`
1075
+ :meth:`nodes`, :meth:`nodes_where`, :meth:`nodes_where_predicate`
1076
+
1077
+ """
1078
+ for u, nbrs in iter(self.edge.items()):
1079
+ for v, attr in iter(nbrs.items()):
1080
+ if data:
1081
+ yield (u, v), attr
1082
+ else:
1083
+ yield u, v
1084
+
1085
+ def edges_where(self, conditions=None, data=False, **kwargs):
1086
+ """Get edges for which a certain condition or set of conditions is true.
1087
+
1088
+ Parameters
1089
+ ----------
1090
+ conditions : dict, optional
1091
+ A set of conditions in the form of key-value pairs.
1092
+ The keys should be attribute names. The values can be attribute
1093
+ values or ranges of attribute values in the form of min/max pairs.
1094
+ data : bool, optional
1095
+ If True, yield the edge attributes in addition to the edge identifiers.
1096
+ **kwargs : dict[str, Any], optional
1097
+ Additional conditions provided as named function arguments.
1098
+
1099
+ Yields
1100
+ ------
1101
+ tuple[hashable, hashable] | tuple[tuple[hashable, hashable], dict[str, Any]]
1102
+ If `data` is False, the next edge identifier (u, v).
1103
+ If `data` is True, the next edge identifier and its attributes as a ((u, v), attr) tuple.
1104
+
1105
+ See Also
1106
+ --------
1107
+ :meth:`edges`, :meth:`edges_where_predicate`
1108
+ :meth:`nodes`, :meth:`nodes_where`, :meth:`nodes_where_predicate`
1109
+
1110
+ """
1111
+ conditions = conditions or {}
1112
+ conditions.update(kwargs)
1113
+
1114
+ for key in self.edges():
1115
+ is_match = True
1116
+
1117
+ attr = self.edge_attributes(key) or {}
1118
+
1119
+ for name, value in conditions.items():
1120
+ method = getattr(self, name, None)
1121
+
1122
+ if method and callable(method):
1123
+ val = method(key)
1124
+ elif name in attr:
1125
+ val = attr[name]
1126
+ else:
1127
+ is_match = False
1128
+ break
1129
+
1130
+ if isinstance(val, list):
1131
+ if value not in val:
1132
+ is_match = False
1133
+ break
1134
+ elif isinstance(value, (tuple, list)):
1135
+ minval, maxval = value
1136
+ if val < minval or val > maxval:
1137
+ is_match = False
1138
+ break
1139
+ else:
1140
+ if value != val:
1141
+ is_match = False
1142
+ break
1143
+
1144
+ if is_match:
1145
+ if data:
1146
+ yield key, attr
1147
+ else:
1148
+ yield key
1149
+
1150
+ def edges_where_predicate(self, predicate, data=False):
1151
+ """Get edges for which a certain condition or set of conditions is true using a lambda function.
1152
+
1153
+ Parameters
1154
+ ----------
1155
+ predicate : callable
1156
+ The condition you want to evaluate.
1157
+ The callable takes 2 parameters:
1158
+ an edge identifier (tuple of node identifiers) and edge attributes,
1159
+ and should return True or False.
1160
+ data : bool, optional
1161
+ If True, yield the edge attributes in addition to the edge attributes.
1162
+
1163
+ Yields
1164
+ ------
1165
+ tuple[hashable, hashable] | tuple[tuple[hashable, hashable], dict[str, Any]]
1166
+ If `data` is False, the next edge identifier (u, v).
1167
+ If `data` is True, the next edge identifier and its attributes as a ((u, v), attr) tuple.
1168
+
1169
+ See Also
1170
+ --------
1171
+ :meth:`edges`, :meth:`edges_where`
1172
+ :meth:`nodes`, :meth:`nodes_where`, :meth:`nodes_where_predicate`
1173
+
1174
+ Examples
1175
+ --------
1176
+ >>>
1177
+
1178
+ """
1179
+ for key, attr in self.edges(True):
1180
+ if predicate(key, attr):
1181
+ if data:
1182
+ yield key, attr
1183
+ else:
1184
+ yield key
1185
+
1186
+ def shortest_path(self, u, v):
1187
+ """Find the shortest path between two nodes using the A* algorithm.
1188
+
1189
+ Parameters
1190
+ ----------
1191
+ u : hashable
1192
+ The identifier of the start node.
1193
+ v : hashable
1194
+ The identifier of the end node.
1195
+
1196
+ Returns
1197
+ -------
1198
+ list[hashable] | None
1199
+ The path from root to goal, or None, if no path exists between the vertices.
1200
+
1201
+ See Also
1202
+ --------
1203
+ :meth:`compas.topology.astar_shortest_path`
1204
+
1205
+ """
1206
+ return astar_shortest_path(self.adjacency, u, v)
1207
+
1208
+ # --------------------------------------------------------------------------
1209
+ # Default attributes
1210
+ # --------------------------------------------------------------------------
1211
+
1212
+ def update_default_node_attributes(self, attr_dict=None, **kwattr):
1213
+ """Update the default node attributes.
1214
+
1215
+ Parameters
1216
+ ----------
1217
+ attr_dict : dict[str, Any], optional
1218
+ A dictionary of attributes with their default values.
1219
+ **kwattr : dict[str, Any], optional
1220
+ A dictionary of additional attributes compiled of remaining named arguments.
1221
+
1222
+ Returns
1223
+ -------
1224
+ None
1225
+
1226
+ See Also
1227
+ --------
1228
+ :meth:`update_default_edge_attributes`
1229
+
1230
+ """
1231
+ if not attr_dict:
1232
+ attr_dict = {}
1233
+ attr_dict.update(kwattr)
1234
+ self.default_node_attributes.update(attr_dict)
1235
+
1236
+ def update_default_edge_attributes(self, attr_dict=None, **kwattr):
1237
+ """Update the default edge attributes.
1238
+
1239
+ Parameters
1240
+ ----------
1241
+ attr_dict : dict[str, Any], optional
1242
+ A dictionary of attributes with their default values.
1243
+ **kwattr : dict[str, Any], optional
1244
+ A dictionary of additional attributes compiled of remaining named arguments.
1245
+
1246
+ Returns
1247
+ -------
1248
+ None
1249
+
1250
+ See Also
1251
+ --------
1252
+ :meth:`update_default_node_attributes`
1253
+
1254
+ """
1255
+ if not attr_dict:
1256
+ attr_dict = {}
1257
+ attr_dict.update(kwattr)
1258
+ self.default_edge_attributes.update(attr_dict)
1259
+
1260
+ # --------------------------------------------------------------------------
1261
+ # Node attributes
1262
+ # --------------------------------------------------------------------------
1263
+
1264
+ def node_attribute(self, key, name, value=None):
1265
+ """Get or set an attribute of a node.
1266
+
1267
+ Parameters
1268
+ ----------
1269
+ key : hashable
1270
+ The node identifier.
1271
+ name : str
1272
+ The name of the attribute
1273
+ value : obj, optional
1274
+ The value of the attribute.
1275
+
1276
+ Returns
1277
+ -------
1278
+ obj or None
1279
+ The value of the attribute,
1280
+ or None when the function is used as a "setter".
1281
+
1282
+ Raises
1283
+ ------
1284
+ KeyError
1285
+ If the node does not exist.
1286
+
1287
+ See Also
1288
+ --------
1289
+ :meth:`unset_node_attribute`
1290
+ :meth:`node_attributes`, :meth:`nodes_attribute`, :meth:`nodes_attributes`
1291
+ :meth:`edge_attribute`, :meth:`edge_attributes`, :meth:`edges_attribute`, :meth:`edges_attributes`
1292
+
1293
+ """
1294
+ if key not in self.node:
1295
+ raise KeyError(key)
1296
+ if value is not None:
1297
+ self.node[key][name] = value
1298
+ return
1299
+ if name in self.node[key]:
1300
+ return self.node[key][name]
1301
+ else:
1302
+ if name in self.default_node_attributes:
1303
+ return self.default_node_attributes[name]
1304
+
1305
+ def unset_node_attribute(self, key, name):
1306
+ """Unset the attribute of a node.
1307
+
1308
+ Parameters
1309
+ ----------
1310
+ key : int
1311
+ The node identifier.
1312
+ name : str
1313
+ The name of the attribute.
1314
+
1315
+ Raises
1316
+ ------
1317
+ KeyError
1318
+ If the node does not exist.
1319
+
1320
+ See Also
1321
+ --------
1322
+ :meth:`node_attribute`
1323
+
1324
+ Notes
1325
+ -----
1326
+ Unsetting the value of a node attribute implicitly sets it back to the value
1327
+ stored in the default node attribute dict.
1328
+
1329
+ """
1330
+ if name in self.node[key]:
1331
+ del self.node[key][name]
1332
+
1333
+ def node_attributes(self, key, names=None, values=None):
1334
+ """Get or set multiple attributes of a node.
1335
+
1336
+ Parameters
1337
+ ----------
1338
+ key : hashable
1339
+ The identifier of the node.
1340
+ names : list[str], optional
1341
+ A list of attribute names.
1342
+ values : list[Any], optional
1343
+ A list of attribute values.
1344
+
1345
+ Returns
1346
+ -------
1347
+ dict[str, Any] | list[Any] | None
1348
+ If the parameter `names` is empty,
1349
+ the function returns a dictionary of all attribute name-value pairs of the node.
1350
+ If the parameter `names` is not empty,
1351
+ the function returns a list of the values corresponding to the requested attribute names.
1352
+ The function returns None if it is used as a "setter".
1353
+
1354
+ Raises
1355
+ ------
1356
+ KeyError
1357
+ If the node does not exist.
1358
+
1359
+ See Also
1360
+ --------
1361
+ :meth:`node_attribute`, :meth:`nodes_attribute`, :meth:`nodes_attributes`
1362
+ :meth:`edge_attribute`, :meth:`edge_attributes`, :meth:`edges_attribute`, :meth:`edges_attributes`
1363
+
1364
+ """
1365
+ if key not in self.node:
1366
+ raise KeyError(key)
1367
+ if names and values is not None:
1368
+ # use it as a setter
1369
+ for name, value in zip(names, values):
1370
+ self.node[key][name] = value
1371
+ return
1372
+ # use it as a getter
1373
+ if not names:
1374
+ # return all node attributes as a dict
1375
+ return NodeAttributeView(self.default_node_attributes, self.node[key])
1376
+ values = []
1377
+ for name in names:
1378
+ if name in self.node[key]:
1379
+ values.append(self.node[key][name])
1380
+ elif name in self.default_node_attributes:
1381
+ values.append(self.default_node_attributes[name])
1382
+ else:
1383
+ values.append(None)
1384
+ return values
1385
+
1386
+ def nodes_attribute(self, name, value=None, keys=None):
1387
+ """Get or set an attribute of multiple nodes.
1388
+
1389
+ Parameters
1390
+ ----------
1391
+ name : str
1392
+ The name of the attribute.
1393
+ value : obj, optional
1394
+ The value of the attribute.
1395
+ keys : list[hashable], optional
1396
+ A list of node identifiers.
1397
+
1398
+ Returns
1399
+ -------
1400
+ list[Any] | None
1401
+ The value of the attribute for each node,
1402
+ or None if the function is used as a "setter".
1403
+
1404
+ Raises
1405
+ ------
1406
+ KeyError
1407
+ If any of the nodes does not exist.
1408
+
1409
+ See Also
1410
+ --------
1411
+ :meth:`node_attribute`, :meth:`node_attributes`, :meth:`nodes_attributes`
1412
+ :meth:`edge_attribute`, :meth:`edge_attributes`, :meth:`edges_attribute`, :meth:`edges_attributes`
1413
+
1414
+ """
1415
+ if not keys:
1416
+ keys = self.nodes()
1417
+ if value is not None:
1418
+ for key in keys:
1419
+ self.node_attribute(key, name, value)
1420
+ return
1421
+ return [self.node_attribute(key, name) for key in keys]
1422
+
1423
+ def nodes_attributes(self, names=None, values=None, keys=None):
1424
+ """Get or set multiple attributes of multiple nodes.
1425
+
1426
+ Parameters
1427
+ ----------
1428
+ names : list[str], optional
1429
+ The names of the attribute.
1430
+ values : list[Any], optional
1431
+ The values of the attributes.
1432
+ keys : list[hashable], optional
1433
+ A list of node identifiers.
1434
+
1435
+ Returns
1436
+ -------
1437
+ list[dict[str, Any]] | list[list[Any]] | None
1438
+ If the parameter `names` is None,
1439
+ the function returns a list containing an attribute dict per node.
1440
+ If the parameter `names` is not None,
1441
+ the function returns a list containing a list of attribute values per node corresponding to the provided attribute names.
1442
+ The function returns None if it is used as a "setter".
1443
+
1444
+ Raises
1445
+ ------
1446
+ KeyError
1447
+ If any of the nodes does not exist.
1448
+
1449
+ See Also
1450
+ --------
1451
+ :meth:`node_attribute`, :meth:`node_attributes`, :meth:`nodes_attribute`
1452
+ :meth:`edge_attribute`, :meth:`edge_attributes`, :meth:`edges_attribute`, :meth:`edges_attributes`
1453
+
1454
+ """
1455
+ if not keys:
1456
+ keys = self.nodes()
1457
+ if values:
1458
+ for key in keys:
1459
+ self.node_attributes(key, names, values)
1460
+ return
1461
+ return [self.node_attributes(key, names) for key in keys]
1462
+
1463
+ # --------------------------------------------------------------------------
1464
+ # Edge attributes
1465
+ # --------------------------------------------------------------------------
1466
+
1467
+ def edge_attribute(self, key, name, value=None):
1468
+ """Get or set an attribute of an edge.
1469
+
1470
+ Parameters
1471
+ ----------
1472
+ key : tuple[hashable, hashable]
1473
+ The identifier of the edge as a pair of node identifiers.
1474
+ name : str
1475
+ The name of the attribute.
1476
+ value : obj, optional
1477
+ The value of the attribute.
1478
+
1479
+ Returns
1480
+ -------
1481
+ object | None
1482
+ The value of the attribute, or None when the function is used as a "setter".
1483
+
1484
+ Raises
1485
+ ------
1486
+ KeyError
1487
+ If the edge does not exist.
1488
+
1489
+ See Also
1490
+ --------
1491
+ :meth:`unset_edge_attribute`
1492
+ :meth:`edge_attributes`, :meth:`edges_attribute`, :meth:`edges_attributes`
1493
+ :meth:`node_attribute`, :meth:`node_attributes`, :meth:`nodes_attribute`, :meth:`nodes_attributes`
1494
+
1495
+ """
1496
+ u, v = key
1497
+ if u not in self.edge or v not in self.edge[u]:
1498
+ raise KeyError(key)
1499
+ attr = self.edge[u][v]
1500
+ if value is not None:
1501
+ attr[name] = value
1502
+ return
1503
+ if name in attr:
1504
+ return attr[name]
1505
+ if name in self.default_edge_attributes:
1506
+ return self.default_edge_attributes[name]
1507
+
1508
+ def unset_edge_attribute(self, key, name):
1509
+ """Unset the attribute of an edge.
1510
+
1511
+ Parameters
1512
+ ----------
1513
+ key : tuple[hashable, hashable]
1514
+ The edge identifier.
1515
+ name : str
1516
+ The name of the attribute.
1517
+
1518
+ Returns
1519
+ -------
1520
+ None
1521
+
1522
+ Raises
1523
+ ------
1524
+ KeyError
1525
+ If the edge does not exist.
1526
+
1527
+ See Also
1528
+ --------
1529
+ :meth:`edge_attribute`
1530
+
1531
+ Notes
1532
+ -----
1533
+ Unsetting the value of an edge attribute implicitly sets it back to the value
1534
+ stored in the default edge attribute dict.
1535
+
1536
+ """
1537
+ u, v = key
1538
+ if u not in self.edge or v not in self.edge[u]:
1539
+ raise KeyError(key)
1540
+ attr = self.edge[u][v]
1541
+ if name in attr:
1542
+ del attr[name]
1543
+
1544
+ def edge_attributes(self, key, names=None, values=None):
1545
+ """Get or set multiple attributes of an edge.
1546
+
1547
+ Parameters
1548
+ ----------
1549
+ key : tuple[hashable, hashable]
1550
+ The identifier of the edge.
1551
+ names : list[str], optional
1552
+ A list of attribute names.
1553
+ values : list[Any], optional
1554
+ A list of attribute values.
1555
+
1556
+ Returns
1557
+ -------
1558
+ dict[str, Any] | list[Any] | None
1559
+ If the parameter `names` is empty, a dictionary of all attribute name-value pairs of the edge.
1560
+ If the parameter `names` is not empty, a list of the values corresponding to the provided names.
1561
+ None if the function is used as a "setter".
1562
+
1563
+ Raises
1564
+ ------
1565
+ KeyError
1566
+ If the edge does not exist.
1567
+
1568
+ See Also
1569
+ --------
1570
+ :meth:`edge_attribute`, :meth:`edges_attribute`, :meth:`edges_attributes`
1571
+ :meth:`node_attribute`, :meth:`node_attributes`, :meth:`nodes_attribute`, :meth:`nodes_attributes`
1572
+
1573
+ """
1574
+ u, v = key
1575
+ if u not in self.edge or v not in self.edge[u]:
1576
+ raise KeyError(key)
1577
+ if names and values:
1578
+ # use it as a setter
1579
+ for name, value in zip(names, values):
1580
+ self.edge_attribute(key, name, value)
1581
+ return
1582
+ # use it as a getter
1583
+ if not names:
1584
+ # get the entire attribute dict
1585
+ return EdgeAttributeView(self.default_edge_attributes, self.edge[u][v])
1586
+ # get only the values of the named attributes
1587
+ values = []
1588
+ for name in names:
1589
+ value = self.edge_attribute(key, name)
1590
+ values.append(value)
1591
+ return values
1592
+
1593
+ def edges_attribute(self, name, value=None, keys=None):
1594
+ """Get or set an attribute of multiple edges.
1595
+
1596
+ Parameters
1597
+ ----------
1598
+ name : str
1599
+ The name of the attribute.
1600
+ value : obj, optional
1601
+ The value of the attribute.
1602
+ keys : list[tuple[hashable, hashable]], optional
1603
+ A list of edge identifiers.
1604
+
1605
+ Returns
1606
+ -------
1607
+ list[Any] | None
1608
+ A list containing the value per edge of the requested attribute,
1609
+ or None if the function is used as a "setter".
1610
+
1611
+ Raises
1612
+ ------
1613
+ KeyError
1614
+ If any of the edges does not exist.
1615
+
1616
+ See Also
1617
+ --------
1618
+ :meth:`edge_attribute`, :meth:`edge_attributes`, :meth:`edges_attributes`
1619
+ :meth:`node_attribute`, :meth:`node_attributes`, :meth:`nodes_attribute`, :meth:`nodes_attributes`
1620
+
1621
+ """
1622
+ if not keys:
1623
+ keys = self.edges()
1624
+ if value is not None:
1625
+ for key in keys:
1626
+ self.edge_attribute(key, name, value)
1627
+ return
1628
+ return [self.edge_attribute(key, name) for key in keys]
1629
+
1630
+ def edges_attributes(self, names=None, values=None, keys=None):
1631
+ """Get or set multiple attributes of multiple edges.
1632
+
1633
+ Parameters
1634
+ ----------
1635
+ names : list[str], optional
1636
+ The names of the attribute.
1637
+ values : list[Any], optional
1638
+ The values of the attributes.
1639
+ keys : list[tuple[hashable, hashable]], optional
1640
+ A list of edge identifiers.
1641
+
1642
+ Returns
1643
+ -------
1644
+ list[dict[str, Any]] | list[list[Any]] | None
1645
+ If `names` is empty,
1646
+ a list containing per edge an attribute dict with all attributes of the edge.
1647
+ If `names` is not empty,
1648
+ a list containing per edge a list of attribute values corresponding to the requested names.
1649
+ None if the function is used as a "setter".
1650
+
1651
+ Raises
1652
+ ------
1653
+ KeyError
1654
+ If any of the edges does not exist.
1655
+
1656
+ See Also
1657
+ --------
1658
+ :meth:`edge_attribute`, :meth:`edge_attributes`, :meth:`edges_attribute`
1659
+ :meth:`node_attribute`, :meth:`node_attributes`, :meth:`nodes_attribute`, :meth:`nodes_attributes`
1660
+
1661
+ """
1662
+ if not keys:
1663
+ keys = self.edges()
1664
+ if values:
1665
+ for key in keys:
1666
+ self.edge_attributes(key, names, values)
1667
+ return
1668
+ return [self.edge_attributes(key, names) for key in keys]
1669
+
1670
+ # --------------------------------------------------------------------------
1671
+ # Node topology
1672
+ # --------------------------------------------------------------------------
1673
+
1674
+ def has_node(self, key):
1675
+ """Verify if a specific node is present in the graph.
1676
+
1677
+ Parameters
1678
+ ----------
1679
+ key : hashable
1680
+ The identifier of the node.
1681
+
1682
+ Returns
1683
+ -------
1684
+ bool
1685
+ True or False.
1686
+
1687
+ See Also
1688
+ --------
1689
+ :meth:`has_edge`
1690
+
1691
+ """
1692
+ return key in self.node
1693
+
1694
+ def is_leaf(self, key):
1695
+ """Verify if a node is a leaf.
1696
+
1697
+ Parameters
1698
+ ----------
1699
+ key : hashable
1700
+ The identifier of the node.
1701
+
1702
+ Returns
1703
+ -------
1704
+ bool
1705
+ True or False.
1706
+
1707
+ See Also
1708
+ --------
1709
+ :meth:`leaves`
1710
+ :meth:`is_node_connected`
1711
+
1712
+ Notes
1713
+ -----
1714
+ A node is a *leaf* if it has only one neighbor.
1715
+
1716
+ """
1717
+ return self.degree(key) == 1
1718
+
1719
+ def leaves(self):
1720
+ """Return all leaves of the graph.
1721
+
1722
+ Returns
1723
+ -------
1724
+ list[hashable]
1725
+ A list of node identifiers.
1726
+
1727
+ """
1728
+ return [key for key in self.nodes() if self.is_leaf(key)]
1729
+
1730
+ def is_node_connected(self, key):
1731
+ """Verify if a specific node is connected.
1732
+
1733
+ Parameters
1734
+ ----------
1735
+ key : hashable
1736
+ The identifier of the node.
1737
+
1738
+ Returns
1739
+ -------
1740
+ bool
1741
+ True or False.
1742
+
1743
+ See Also
1744
+ --------
1745
+ :meth:`is_leaf`
1746
+
1747
+ """
1748
+ return self.degree(key) > 0
1749
+
1750
+ def neighbors(self, key):
1751
+ """Return the neighbors of a node.
1752
+
1753
+ Parameters
1754
+ ----------
1755
+ key : hashable
1756
+ The identifier of the node.
1757
+
1758
+ Returns
1759
+ -------
1760
+ list[hashable]
1761
+ A list of node identifiers.
1762
+
1763
+ See Also
1764
+ --------
1765
+ :meth:`neighbors_out`, :meth:`neighbors_in`
1766
+ :meth:`neighborhood`
1767
+
1768
+ """
1769
+ return list(self.adjacency[key])
1770
+
1771
+ def neighborhood(self, key, ring=1):
1772
+ """Return the nodes in the neighborhood of a node.
1773
+
1774
+ Parameters
1775
+ ----------
1776
+ key : hashable
1777
+ The identifier of the node.
1778
+ ring : int, optional
1779
+ The size of the neighborhood.
1780
+
1781
+ Returns
1782
+ -------
1783
+ list[hashable]
1784
+ A list of node identifiers.
1785
+
1786
+ See Also
1787
+ --------
1788
+ :meth:`neighbors`
1789
+
1790
+ """
1791
+ nbrs = set(self.neighbors(key))
1792
+ i = 1
1793
+ while True:
1794
+ if i == ring:
1795
+ break
1796
+ temp = []
1797
+ for nbr in nbrs:
1798
+ temp += self.neighbors(nbr)
1799
+ nbrs.update(temp)
1800
+ i += 1
1801
+ if key in nbrs:
1802
+ nbrs.remove(key)
1803
+ return list(nbrs)
1804
+
1805
+ def neighbors_out(self, key):
1806
+ """Return the outgoing neighbors of a node.
1807
+
1808
+ Parameters
1809
+ ----------
1810
+ key : hashable
1811
+ The identifier of the node.
1812
+
1813
+ Returns
1814
+ -------
1815
+ list[hashable]
1816
+ A list of node identifiers.
1817
+
1818
+ See Also
1819
+ --------
1820
+ :meth:`neighbors`, :meth:`neighbors_in`
1821
+
1822
+ """
1823
+ return list(self.edge[key])
1824
+
1825
+ def neighbors_in(self, key):
1826
+ """Return the incoming neighbors of a node.
1827
+
1828
+ Parameters
1829
+ ----------
1830
+ key : hashable
1831
+ The identifier of the node.
1832
+
1833
+ Returns
1834
+ -------
1835
+ list[hashable]
1836
+ A list of node identifiers.
1837
+
1838
+ See Also
1839
+ --------
1840
+ :meth:`neighbors`, :meth:`neighbors_out`
1841
+
1842
+ """
1843
+ return list(set(self.adjacency[key]) - set(self.edge[key]))
1844
+
1845
+ def degree(self, key):
1846
+ """Return the number of neighbors of a node.
1847
+
1848
+ Parameters
1849
+ ----------
1850
+ key : hashable
1851
+ The identifier of the node.
1852
+
1853
+ Returns
1854
+ -------
1855
+ int
1856
+ The number of neighbors of the node.
1857
+
1858
+ See Also
1859
+ --------
1860
+ :meth:`degree_out`, :meth:`degree_in`
1861
+
1862
+ """
1863
+ return len(self.neighbors(key))
1864
+
1865
+ def degree_out(self, key):
1866
+ """Return the number of outgoing neighbors of a node.
1867
+
1868
+ Parameters
1869
+ ----------
1870
+ key : hashable
1871
+ The identifier of the node.
1872
+
1873
+ Returns
1874
+ -------
1875
+ int
1876
+ The number of outgoing neighbors of the node.
1877
+
1878
+ See Also
1879
+ --------
1880
+ :meth:`degree`, :meth:`degree_in`
1881
+
1882
+ """
1883
+ return len(self.neighbors_out(key))
1884
+
1885
+ def degree_in(self, key):
1886
+ """Return the numer of incoming neighbors of a node.
1887
+
1888
+ Parameters
1889
+ ----------
1890
+ key : hashable
1891
+ The identifier of the node.
1892
+
1893
+ Returns
1894
+ -------
1895
+ int
1896
+ The number of incoming neighbors of the node.
1897
+
1898
+ See Also
1899
+ --------
1900
+ :meth:`degree`, :meth:`degree_out`
1901
+
1902
+ """
1903
+ return len(self.neighbors_in(key))
1904
+
1905
+ def node_edges(self, key):
1906
+ """Return the edges connected to a node.
1907
+
1908
+ Parameters
1909
+ ----------
1910
+ key : hashable
1911
+ The identifier of the node.
1912
+
1913
+ Returns
1914
+ -------
1915
+ list[tuple[hashable, hashable]]
1916
+ The edges connected to the node.
1917
+
1918
+ """
1919
+ edges = []
1920
+ for nbr in self.neighbors(key):
1921
+ if nbr in self.edge[key]:
1922
+ edges.append((key, nbr))
1923
+ else:
1924
+ edges.append((nbr, key))
1925
+ return edges
1926
+
1927
+ # --------------------------------------------------------------------------
1928
+ # Edge topology
1929
+ # --------------------------------------------------------------------------
1930
+
1931
+ def has_edge(self, edge, directed=True):
1932
+ """Verify if the graph contains a specific edge.
1933
+
1934
+ Parameters
1935
+ ----------
1936
+ edge : tuple[hashable, hashable]
1937
+ The identifier of the edge as a pair of node identifiers.
1938
+ directed : bool, optional
1939
+ If True, the direction of the edge is taken into account.
1940
+
1941
+ Returns
1942
+ -------
1943
+ bool
1944
+ True if the edge is present, False otherwise.
1945
+
1946
+ See Also
1947
+ --------
1948
+ :meth:`has_node`
1949
+
1950
+ """
1951
+ u, v = edge
1952
+ if directed:
1953
+ return u in self.edge and v in self.edge[u]
1954
+ return (u in self.edge and v in self.edge[u]) or (v in self.edge and u in self.edge[v])
1955
+
1956
+ # --------------------------------------------------------------------------
1957
+ # Node geometry
1958
+ # --------------------------------------------------------------------------
1959
+
1960
+ def node_coordinates(self, key, axes="xyz"):
1961
+ """Return the coordinates of a node.
1962
+
1963
+ Parameters
1964
+ ----------
1965
+ key : hashable
1966
+ The identifier of the node.
1967
+ axes : str, optional
1968
+ The components of the node coordinates to return.
1969
+
1970
+ Returns
1971
+ -------
1972
+ list[float]
1973
+ The coordinates of the node.
1974
+
1975
+ See Also
1976
+ --------
1977
+ :meth:`node_point`, :meth:`node_laplacian`, :meth:`node_neighborhood_centroid`
1978
+
1979
+ """
1980
+ return [self.node[key][axis] for axis in axes]
1981
+
1982
+ def node_point(self, node):
1983
+ """Return the point of a node.
1984
+
1985
+ Parameters
1986
+ ----------
1987
+ node : hashable
1988
+ The identifier of the node.
1989
+
1990
+ Returns
1991
+ -------
1992
+ :class:`compas.geometry.Point`
1993
+ The point of the node.
1994
+
1995
+ See Also
1996
+ --------
1997
+ :meth:`node_coordinates`, :meth:`node_laplacian`, :meth:`node_neighborhood_centroid`
1998
+
1999
+ """
2000
+ return Point(*self.node_coordinates(node))
2001
+
2002
+ def node_laplacian(self, key):
2003
+ """Return the vector from the node to the centroid of its 1-ring neighborhood.
2004
+
2005
+ Parameters
2006
+ ----------
2007
+ key : hashable
2008
+ The identifier of the node.
2009
+
2010
+ Returns
2011
+ -------
2012
+ :class:`compas.geometry.Vector`
2013
+ The laplacian vector.
2014
+
2015
+ See Also
2016
+ --------
2017
+ :meth:`node_coordinates`, :meth:`node_point`, :meth:`node_neighborhood_centroid`
2018
+
2019
+ """
2020
+ c = centroid_points([self.node_coordinates(nbr) for nbr in self.neighbors(key)])
2021
+ p = self.node_coordinates(key)
2022
+ return Vector(*subtract_vectors(c, p))
2023
+
2024
+ def node_neighborhood_centroid(self, key):
2025
+ """Return the computed centroid of the neighboring nodes.
2026
+
2027
+ Parameters
2028
+ ----------
2029
+ key : hashable
2030
+ The identifier of the node.
2031
+
2032
+ Returns
2033
+ -------
2034
+ :class:`compas.geometry.Point`
2035
+ The point at the centroid.
2036
+
2037
+ See Also
2038
+ --------
2039
+ :meth:`node_coordinates`, :meth:`node_point`, :meth:`node_laplacian`
2040
+
2041
+ """
2042
+ return Point(*centroid_points([self.node_coordinates(nbr) for nbr in self.neighbors(key)]))
2043
+
2044
+ # --------------------------------------------------------------------------
2045
+ # Edge geometry
2046
+ # --------------------------------------------------------------------------
2047
+
2048
+ def edge_coordinates(self, edge, axes="xyz"):
2049
+ """Return the coordinates of the start and end point of an edge.
2050
+
2051
+ Parameters
2052
+ ----------
2053
+ edge : tuple[hashable, hashable]
2054
+ The identifier of the edge.
2055
+ axes : str, optional
2056
+ The axes along which the coordinates should be included.
2057
+
2058
+ Returns
2059
+ -------
2060
+ tuple[list[float], list[float]]
2061
+ The coordinates of the start point.
2062
+ The coordinates of the end point.
2063
+
2064
+ See Also
2065
+ --------
2066
+ :meth:`edge_point`, :meth:`edge_start`, :meth:`edge_end`, :meth:`edge_midpoint`
2067
+
2068
+ """
2069
+ u, v = edge
2070
+ return self.node_coordinates(u, axes=axes), self.node_coordinates(v, axes=axes)
2071
+
2072
+ def edge_start(self, edge):
2073
+ """Return the start point of an edge.
2074
+
2075
+ Parameters
2076
+ ----------
2077
+ edge : tuple[hashable, hashable]
2078
+ The identifier of the edge.
2079
+
2080
+ Returns
2081
+ -------
2082
+ :class:`compas.geometry.Point`
2083
+ The start point of the edge.
2084
+
2085
+ See Also
2086
+ --------
2087
+ :meth:`edge_point`, :meth:`edge_end`, :meth:`edge_midpoint`
2088
+
2089
+ """
2090
+ return self.node_point(edge[0])
2091
+
2092
+ def edge_end(self, edge):
2093
+ """Return the end point of an edge.
2094
+
2095
+ Parameters
2096
+ ----------
2097
+ edge : tuple[hashable, hashable]
2098
+ The identifier of the edge.
2099
+
2100
+ Returns
2101
+ -------
2102
+ :class:`compas.geometry.Point`
2103
+ The end point of the edge.
2104
+
2105
+ See Also
2106
+ --------
2107
+ :meth:`edge_point`, :meth:`edge_start`, :meth:`edge_midpoint`
2108
+
2109
+ """
2110
+ return self.node_point(edge[1])
2111
+
2112
+ def edge_point(self, edge, t=0.5):
2113
+ """Return the point at a parametric location along an edge.
2114
+
2115
+ Parameters
2116
+ ----------
2117
+ edge : tuple[hashable, hashable]
2118
+ The identifier of the edge.
2119
+ t : float, optional
2120
+ The location of the point on the edge.
2121
+ If the value of `t` is outside the range 0-1, the point will
2122
+ lie in the direction of the edge, but not on the edge vector.
2123
+
2124
+ Returns
2125
+ -------
2126
+ :class:`compas.geometry.Point`
2127
+ The point at the specified location.
2128
+
2129
+ See Also
2130
+ --------
2131
+ :meth:`edge_start`, :meth:`edge_end`, :meth:`edge_midpoint`
2132
+
2133
+ """
2134
+ if t == 0.0:
2135
+ return self.edge_start(edge)
2136
+ if t == 1.0:
2137
+ return self.edge_end(edge)
2138
+ if t == 0.5:
2139
+ return self.edge_midpoint(edge)
2140
+
2141
+ a, b = self.edge_coordinates(edge)
2142
+ ab = subtract_vectors(b, a)
2143
+ return Point(*add_vectors(a, scale_vector(ab, t)))
2144
+
2145
+ def edge_midpoint(self, edge):
2146
+ """Return the location of the midpoint of an edge.
2147
+
2148
+ Parameters
2149
+ ----------
2150
+ edge : tuple[hashable, hashable]
2151
+ The identifier of the edge.
2152
+
2153
+ Returns
2154
+ -------
2155
+ :class:`compas.geometry.Point`
2156
+ The midpoint of the edge.
2157
+
2158
+ See Also
2159
+ --------
2160
+ :meth:`edge_start`, :meth:`edge_end`, :meth:`edge_point`
2161
+
2162
+ """
2163
+ a, b = self.edge_coordinates(edge)
2164
+ return Point(*midpoint_line((a, b)))
2165
+
2166
+ def edge_vector(self, edge):
2167
+ """Return the vector of an edge.
2168
+
2169
+ Parameters
2170
+ ----------
2171
+ edge : tuple[hashable, hashable]
2172
+ The identifier of the edge.
2173
+
2174
+ Returns
2175
+ -------
2176
+ :class:`compas.geometry.Vector`
2177
+ The vector from start to end.
2178
+
2179
+ See Also
2180
+ --------
2181
+ :meth:`edge_direction`, :meth:`edge_line`, :meth:`edge_length`
2182
+
2183
+ """
2184
+ a, b = self.edge_coordinates(edge)
2185
+ return Vector.from_start_end(a, b)
2186
+
2187
+ def edge_direction(self, edge):
2188
+ """Return the direction vector of an edge.
2189
+
2190
+ Parameters
2191
+ ----------
2192
+ edge : tuple[hashable, hashable]
2193
+ The identifier of the edge.
2194
+
2195
+ Returns
2196
+ -------
2197
+ :class:`compas.geometry.Vector`
2198
+ The direction vector of the edge.
2199
+
2200
+ See Also
2201
+ --------
2202
+ :meth:`edge_vector`, :meth:`edge_line`, :meth:`edge_length`
2203
+
2204
+ """
2205
+ return Vector(*normalize_vector(self.edge_vector(edge)))
2206
+
2207
+ def edge_line(self, edge):
2208
+ """Return the line of an edge.
2209
+
2210
+ Parameters
2211
+ ----------
2212
+ edge : tuple[hashable, hashable]
2213
+ The identifier of the edge.
2214
+
2215
+ Returns
2216
+ -------
2217
+ :class:`compas.geometry.Line`
2218
+ The line of the edge.
2219
+
2220
+ See Also
2221
+ --------
2222
+ :meth:`edge_vector`, :meth:`edge_direction`, :meth:`edge_length`
2223
+
2224
+ """
2225
+ return Line(*self.edge_coordinates(edge))
2226
+
2227
+ def edge_length(self, edge):
2228
+ """Return the length of an edge.
2229
+
2230
+ Parameters
2231
+ ----------
2232
+ edge : tuple[hashable, hashable]
2233
+ The identifier of the edge.
2234
+
2235
+ Returns
2236
+ -------
2237
+ float
2238
+ The length of the edge.
2239
+
2240
+ See Also
2241
+ --------
2242
+ :meth:`edge_vector`, :meth:`edge_direction`, :meth:`edge_line`
2243
+
2244
+ """
2245
+ a, b = self.edge_coordinates(edge)
2246
+ return distance_point_point(a, b)
2247
+
2248
+ # --------------------------------------------------------------------------
2249
+ # Transformations and BBox
2250
+ # --------------------------------------------------------------------------
2251
+
2252
+ def transform(self, transformation):
2253
+ """Transform all nodes of the graph.
2254
+
2255
+ Parameters
2256
+ ----------
2257
+ transformation : :class:`Transformation`
2258
+ The transformation used to transform the nodes.
2259
+
2260
+ Returns
2261
+ -------
2262
+ None
2263
+
2264
+ """
2265
+ nodes = self.nodes_attributes("xyz")
2266
+ points = transform_points(nodes, transformation)
2267
+ for point, node in zip(points, self.nodes()):
2268
+ self.node_attributes(node, "xyz", point)
2269
+
2270
+ def aabb(self):
2271
+ """Calculate the axis aligned bounding box of the graph.
2272
+
2273
+ Returns
2274
+ -------
2275
+ :class:`compas.geometry.Box`
2276
+
2277
+ """
2278
+ nodes = self.nodes_attributes("xyz")
2279
+ return Box.from_bounding_box(bounding_box(nodes))
2280
+
2281
+ def obb(self):
2282
+ """Calculate the oriented bounding box of the graph.
2283
+
2284
+ Returns
2285
+ -------
2286
+ :class:`compas.geometry.Box`
2287
+
2288
+ """
2289
+ nodes = self.nodes_attributes("xyz")
2290
+ return Box.from_bounding_box(oriented_bounding_box(nodes))
2291
+
2292
+ # --------------------------------------------------------------------------
2293
+ # Other Methods
2294
+ # --------------------------------------------------------------------------
2295
+
2296
+ def connected_nodes(self):
2297
+ """Get groups of connected nodes.
2298
+
2299
+ Returns
2300
+ -------
2301
+ list[list[hashable]]
2302
+
2303
+ See Also
2304
+ --------
2305
+ :meth:`connected_edges`
2306
+
2307
+ """
2308
+ return connected_components(self.adjacency)
2309
+
2310
+ def connected_edges(self):
2311
+ """Get groups of connected edges.
2312
+
2313
+ Returns
2314
+ -------
2315
+ list[list[tuple[hashable, hashable]]]
2316
+
2317
+ See Also
2318
+ --------
2319
+ :meth:`connected_nodes`
2320
+
2321
+ """
2322
+ return [[(u, v) for u in nodes for v in self.neighbors(u) if u < v] for nodes in self.connected_nodes()]
2323
+
2324
+ def exploded(self):
2325
+ """Explode the graph into its connected components.
2326
+
2327
+ Returns
2328
+ -------
2329
+ list[:class:`compas.datastructures.Graph`]
2330
+
2331
+ """
2332
+ cls = type(self)
2333
+ graphs = []
2334
+ for nodes in self.connected_nodes():
2335
+ edges = [(u, v) for u in nodes for v in self.neighbors(u) if u < v]
2336
+ graph = cls(
2337
+ default_node_attributes=self.default_node_attributes,
2338
+ default_edge_attributes=self.default_edge_attributes,
2339
+ )
2340
+ for node in nodes:
2341
+ graph.add_node(node, attr_dict=self.node_attributes(node))
2342
+ for u, v in edges:
2343
+ graph.add_edge(u, v, attr_dict=self.edge_attributes((u, v)))
2344
+ graphs.append(graph)
2345
+ return graphs
2346
+
2347
+ def complement(self):
2348
+ """Generate the complement of a graph.
2349
+
2350
+ The complement of a graph G is the graph H with the same vertices
2351
+ but whose edges consists of the edges not present in the graph G [1]_.
2352
+
2353
+ Returns
2354
+ -------
2355
+ :class:`compas.datastructures.Graph`
2356
+ The complement graph.
2357
+
2358
+ References
2359
+ ----------
2360
+ .. [1] Wolfram MathWorld. *Graph complement*.
2361
+ Available at: http://mathworld.wolfram.com/GraphComplement.html.
2362
+
2363
+ Examples
2364
+ --------
2365
+ >>> import compas
2366
+ >>> from compas.datastructures import Graph
2367
+ >>> graph = Graph.from_obj(compas.get("lines.obj"))
2368
+ >>> complement = graph.complement()
2369
+ >>> any(complement.has_edge(u, v, directed=False) for u, v in graph.edges())
2370
+ False
2371
+
2372
+ """
2373
+ cls = type(self)
2374
+
2375
+ graph = cls(
2376
+ default_node_attributes=self.default_node_attributes,
2377
+ default_edge_attributes=self.default_edge_attributes,
2378
+ )
2379
+ for node in self.nodes():
2380
+ graph.add_node(node, attr_dict=self.node_attributes(node))
2381
+
2382
+ for u, v in combinations(self.nodes(), 2):
2383
+ if not self.has_edge((u, v), directed=False):
2384
+ graph.add_edge(u, v, attr_dict=self.edge_attributes((u, v)))
2385
+
2386
+ return graph
2387
+
2388
+ # --------------------------------------------------------------------------
2389
+ # Matrices
2390
+ # --------------------------------------------------------------------------
2391
+
2392
+ def adjacency_matrix(self, rtype="array"):
2393
+ """Creates a node adjacency matrix from a Graph datastructure.
2394
+
2395
+ Parameters
2396
+ ----------
2397
+ rtype : Literal['array', 'csc', 'csr', 'coo', 'list'], optional
2398
+ Format of the result.
2399
+
2400
+ Returns
2401
+ -------
2402
+ array_like
2403
+ Constructed adjacency matrix.
2404
+
2405
+ """
2406
+ from compas.matrices import adjacency_matrix
2407
+
2408
+ node_index = self.node_index()
2409
+ adjacency = [[node_index[nbr] for nbr in self.neighbors(key)] for key in self.nodes()]
2410
+ return adjacency_matrix(adjacency, rtype=rtype)
2411
+
2412
+ def connectivity_matrix(self, rtype="array"):
2413
+ """Creates a connectivity matrix from a Graph datastructure.
2414
+
2415
+ Parameters
2416
+ ----------
2417
+ rtype : Literal['array', 'csc', 'csr', 'coo', 'list'], optional
2418
+ Format of the result.
2419
+
2420
+ Returns
2421
+ -------
2422
+ array_like
2423
+ Constructed connectivity matrix.
2424
+
2425
+ """
2426
+ from compas.matrices import connectivity_matrix
2427
+
2428
+ node_index = self.node_index()
2429
+ edges = [(node_index[u], node_index[v]) for u, v in self.edges()]
2430
+ return connectivity_matrix(edges, rtype=rtype)
2431
+
2432
+ def degree_matrix(self, rtype="array"):
2433
+ """Creates a degree matrix from a Graph datastructure.
2434
+
2435
+ Parameters
2436
+ ----------
2437
+ rtype : Literal['array', 'csc', 'csr', 'coo', 'list'], optional
2438
+ Format of the result.
2439
+
2440
+ Returns
2441
+ -------
2442
+ array_like
2443
+ Constructed degree matrix.
2444
+
2445
+ """
2446
+ from compas.matrices import degree_matrix
2447
+
2448
+ node_index = self.node_index()
2449
+ adjacency = [[node_index[nbr] for nbr in self.neighbors(key)] for key in self.nodes()]
2450
+ return degree_matrix(adjacency, rtype=rtype)
2451
+
2452
+ def laplacian_matrix(self, normalize=False, rtype="array"):
2453
+ """Creates a Laplacian matrix from a Graph datastructure.
2454
+
2455
+ Parameters
2456
+ ----------
2457
+ normalize : bool, optional
2458
+ If True, normalize the entries such that the value on the diagonal is 1.
2459
+ rtype : Literal['array', 'csc', 'csr', 'coo', 'list'], optional
2460
+ Format of the result.
2461
+
2462
+ Returns
2463
+ -------
2464
+ array_like
2465
+ Constructed Laplacian matrix.
2466
+
2467
+ Notes
2468
+ -----
2469
+ ``d = L.dot(xyz)`` is currently a vector that points from the centroid to the node.
2470
+ Therefore ``c = xyz - d``. By changing the signs in the laplacian, the dsiplacement
2471
+ vectors could be used in a more natural way ``c = xyz + d``.
2472
+
2473
+ """
2474
+ from compas.matrices import laplacian_matrix
2475
+
2476
+ node_index = self.node_index()
2477
+ edges = [(node_index[u], node_index[v]) for u, v in self.edges()]
2478
+ return laplacian_matrix(edges, normalize=normalize, rtype=rtype)