From 86f2e11d6d27fea7cf99773127ad35d2abaef6a6 Mon Sep 17 00:00:00 2001 From: Gonzalo Casas Date: Tue, 4 Oct 2022 13:54:46 +0200 Subject: [PATCH 1/4] update max line length to120 everywhere --- .editorconfig | 2 +- CONTRIBUTING.md | 2 +- MANIFEST.in | 1 + docs/devguide.rst | 4 ++-- pyproject.toml | 26 ++++++++++++++++++++++++++ setup.cfg | 34 ++-------------------------------- 6 files changed, 33 insertions(+), 36 deletions(-) create mode 100644 pyproject.toml diff --git a/.editorconfig b/.editorconfig index 4b0d2ce44de0..aed9aa0c366b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,7 +8,7 @@ insert_final_newline = true indent_style = space indent_size = 4 charset = utf-8 -max_line_length = 180 +max_line_length = 120 [*.{bat,cmd,ps1}] end_of_line = crlf diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c0412ab60063..b8953077fff5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,7 +37,7 @@ In short, this is how that works. ``` 5. Start making your changes to the **master** branch (or branch off of it). -6. Auto-format your code using `black -l 180 `. +6. Auto-format your code using `black `. 7. Make sure all tests still pass: ```bash diff --git a/MANIFEST.in b/MANIFEST.in index b7f2653d4794..165e2d448ac2 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -13,6 +13,7 @@ include AUTHORS.md include CHANGELOG.md include requirements.txt include conftest.py +include pyproject.toml exclude requirements-dev.txt exclude pytest.ini .bumpversion.cfg .editorconfig diff --git a/docs/devguide.rst b/docs/devguide.rst index 4aa7a116ab5d..47c6b70843e9 100644 --- a/docs/devguide.rst +++ b/docs/devguide.rst @@ -74,7 +74,7 @@ The procedure for submitting a PR is the following. Style guide =========== -Please run `black -l 180 ` to auto-format your code. +Please run `black ` to auto-format your code. The command ``invoke lint`` runs the entire codebase through ``flake8``. As described in the `docs `_, @@ -88,7 +88,7 @@ https://flake8.pycqa.org/en/latest/user/error-codes.html The PEP-0008 style guide is available here: https://www.python.org/dev/peps/pep-0008/ -Note that the maximum line length is set to 180 rather 79 in the ``setup.cfg`` of the repo. +Note that the maximum line length is set to 120 rather 79 in the ``setup.cfg`` of the repo. Naming conventions diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000000..93c7eb302af6 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,26 @@ +[tool.black] +line-length = 120 + +[tool.pytest.ini_options] +minversion = "6.0" +testpaths = ["tests", "src/compas"] +python_files = [ + "test_*.py", + "tests.py" +] +addopts = "-ra --strict --doctest-modules --doctest-glob=*.rst --tb=short" +doctest_optionflags= "NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ALLOW_UNICODE ALLOW_BYTES NUMBER" +filterwarnings = "ignore::DeprecationWarning" + +[tool.isort] +line_length = 120 +multi_line_output = 3 +include_trailing_comma = true +force_grid_wrap = 0 +use_parentheses = true +force_single_line = true +ensure_newline_before_comments = true +known_first_party = "compas" +default_section = "THIRDPARTY" +forced_separate = "test_compas" +skip = ["__init__.py"] diff --git a/setup.cfg b/setup.cfg index a4a716c2878a..35dc86f8d502 100644 --- a/setup.cfg +++ b/setup.cfg @@ -2,43 +2,13 @@ universal = 1 [flake8] -max-line-length = 180 +max-line-length = 120 exclude = */migrations/* extend-ignore = E203 [doc8] -max-line-length = 180 +max-line-length = 120 ignore = D001 [pydocstyle] convention = numpy - -[tool:pytest] -testpaths = - tests - src/compas -norecursedirs = - migrations -python_files = - test_*.py - *_test.py - tests.py -addopts = - -ra - --strict - --doctest-glob=\*.rst - --tb=short -doctest_optionflags = - NORMALIZE_WHITESPACE - IGNORE_EXCEPTION_DETAIL - ALLOW_UNICODE - ALLOW_BYTES - NUMBER - -[isort] -force_single_line = True -line_length = 180 -known_first_party = compas -default_section = THIRDPARTY -forced_separate = test_compas -skip = migrations, __init__.py From b3f924796a1ce2475d3a2aba8f7bec910166e360 Mon Sep 17 00:00:00 2001 From: Gonzalo Casas Date: Tue, 4 Oct 2022 13:55:19 +0200 Subject: [PATCH 2/4] re-run black again --- src/compas/__init__.py | 12 +- src/compas/__main__.py | 6 +- src/compas/_os.py | 31 +-- src/compas/artists/artist.py | 4 +- src/compas/artists/exceptions.py | 8 +- src/compas/artists/meshartist.py | 43 +--- src/compas/artists/networkartist.py | 33 +--- src/compas/artists/robotmodelartist.py | 59 ++---- src/compas/artists/volmeshartist.py | 36 +--- src/compas/colors/color.py | 16 +- src/compas/data/data.py | 12 +- src/compas/data/encoders.py | 10 +- src/compas/data/validators.py | 4 +- src/compas/datastructures/assembly/part.py | 8 +- src/compas/datastructures/graph/graph.py | 8 +- .../datastructures/halfedge/halfedge.py | 33 +--- .../datastructures/halfface/halfface.py | 26 +-- src/compas/datastructures/mesh/clean.py | 5 +- .../datastructures/mesh/contours_numpy.py | 4 +- src/compas/datastructures/mesh/conway.py | 17 +- src/compas/datastructures/mesh/explode.py | 13 +- .../datastructures/mesh/geodesics_numpy.py | 10 +- src/compas/datastructures/mesh/join.py | 14 +- src/compas/datastructures/mesh/matrices.py | 14 +- src/compas/datastructures/mesh/mesh.py | 89 ++------- src/compas/datastructures/mesh/offset.py | 10 +- .../datastructures/mesh/operations/insert.py | 12 +- .../mesh/operations/substitute.py | 4 +- .../datastructures/mesh/operations/weld.py | 15 +- .../datastructures/mesh/planarisation.py | 4 +- src/compas/datastructures/mesh/pull_numpy.py | 18 +- src/compas/datastructures/mesh/remesh.py | 18 +- src/compas/datastructures/mesh/slice.py | 20 +- src/compas/datastructures/mesh/smoothing.py | 20 +- src/compas/datastructures/mesh/subdivision.py | 21 +- .../mesh/trimesh_samplepoints_numpy.py | 12 +- .../datastructures/network/complementarity.py | 6 +- src/compas/datastructures/network/duality.py | 7 +- src/compas/datastructures/network/explode.py | 5 +- src/compas/datastructures/network/matrices.py | 8 +- src/compas/datastructures/network/network.py | 8 +- .../datastructures/network/operations/join.py | 16 +- .../datastructures/network/planarity.py | 12 +- .../datastructures/network/smoothing.py | 8 +- src/compas/datastructures/volmesh/volmesh.py | 35 +--- src/compas/files/_xml/xml_pre_38.py | 8 +- src/compas/files/gltf/data_classes.py | 97 +++------ src/compas/files/gltf/extensions.py | 44 ++--- src/compas/files/gltf/gltf_content.py | 16 +- src/compas/files/gltf/gltf_exporter.py | 68 ++----- src/compas/files/gltf/gltf_mesh.py | 20 +- src/compas/files/gltf/gltf_node.py | 29 +-- src/compas/files/gltf/gltf_parser.py | 33 +--- src/compas/files/gltf/gltf_reader.py | 4 +- src/compas/files/gltf/helpers.py | 22 +-- src/compas/files/obj.py | 30 +-- src/compas/files/off.py | 20 +- src/compas/files/ply.py | 36 +--- src/compas/files/stl.py | 16 +- src/compas/files/urdf.py | 12 +- src/compas/geometry/_core/_algebra.py | 9 +- src/compas/geometry/_core/distance.py | 4 +- src/compas/geometry/curves/nurbs.py | 20 +- src/compas/geometry/hull/hull.py | 14 +- src/compas/geometry/interpolation/coons.py | 16 +- .../geometry/intersections/intersections.py | 8 +- src/compas/geometry/pointclouds/pointcloud.py | 4 +- .../geometry/predicates/predicates_2.py | 4 +- .../geometry/predicates/predicates_3.py | 10 +- src/compas/geometry/primitives/frame.py | 6 +- src/compas/geometry/primitives/line.py | 4 +- src/compas/geometry/primitives/point.py | 8 +- src/compas/geometry/primitives/polygon.py | 18 +- src/compas/geometry/primitives/polyline.py | 35 +--- src/compas/geometry/primitives/quaternion.py | 6 +- src/compas/geometry/primitives/vector.py | 4 +- src/compas/geometry/shapes/box.py | 30 +-- src/compas/geometry/shapes/polyhedron.py | 12 +- src/compas/geometry/shapes/sphere.py | 4 +- src/compas/geometry/shapes/torus.py | 16 +- src/compas/geometry/surfaces/nurbs.py | 4 +- src/compas/geometry/surfaces/surface.py | 14 +- .../geometry/transformations/matrices.py | 36 +--- .../geometry/transformations/rotation.py | 4 +- .../transformations/transformations.py | 12 +- .../geometry/transformations/translation.py | 4 +- src/compas/geometry/triangulation/__init__.py | 4 +- src/compas/geometry/triangulation/delaunay.py | 4 +- src/compas/geometry/trimesh/remesh.py | 4 +- src/compas/numerical/descent/descent_numpy.py | 10 +- src/compas/numerical/dr/dr.py | 43 +--- src/compas/numerical/ga/ga.py | 68 ++----- src/compas/numerical/ga/moga.py | 184 +++++------------- .../numerical/isolines/isolines_numpy.py | 4 +- src/compas/numerical/matrices.py | 12 +- src/compas/numerical/topop/topop_numpy.py | 28 +-- src/compas/plugins.py | 63 ++---- src/compas/robots/configuration.py | 56 ++---- src/compas/robots/model/geometry.py | 8 +- src/compas/robots/model/joint.py | 24 +-- src/compas/robots/model/link.py | 48 ++--- src/compas/robots/model/robot.py | 80 ++------ src/compas/robots/model/tool.py | 14 +- src/compas/robots/resources/github.py | 4 +- src/compas/rpc/__main__.py | 8 +- src/compas/rpc/dispatcher.py | 4 +- src/compas/rpc/proxy.py | 12 +- src/compas/rpc/services/default.py | 10 +- src/compas/topology/traversal.py | 8 +- src/compas/utilities/azync.py | 4 +- src/compas/utilities/colors.py | 4 +- src/compas/utilities/images.py | 4 +- src/compas/utilities/itertools.py | 4 +- src/compas/utilities/ssh.py | 14 +- src/compas/utilities/xfunc.py | 4 +- src/compas_blender/__init__.py | 10 +- src/compas_blender/artists/artist.py | 10 +- src/compas_blender/artists/boxartist.py | 7 +- src/compas_blender/artists/capsuleartist.py | 11 +- src/compas_blender/artists/circleartist.py | 11 +- src/compas_blender/artists/coneartist.py | 11 +- src/compas_blender/artists/curveartist.py | 7 +- src/compas_blender/artists/cylinderartist.py | 13 +- src/compas_blender/artists/lineartist.py | 4 +- src/compas_blender/artists/meshartist.py | 60 ++---- src/compas_blender/artists/networkartist.py | 28 +-- src/compas_blender/artists/polygonartist.py | 14 +- .../artists/polyhedronartist.py | 9 +- src/compas_blender/artists/polylineartist.py | 8 +- .../artists/robotmodelartist.py | 19 +- src/compas_blender/artists/sphereartist.py | 11 +- src/compas_blender/artists/surfaceartist.py | 15 +- src/compas_blender/artists/torusartist.py | 7 +- src/compas_blender/artists/vectorartist.py | 4 +- src/compas_blender/artists/volmeshartist.py | 85 ++------ src/compas_blender/install.py | 16 +- src/compas_blender/install_windows.py | 16 +- src/compas_blender/utilities/collections.py | 8 +- src/compas_blender/utilities/drawing.py | 44 ++--- src/compas_ghpython/__init__.py | 8 +- src/compas_ghpython/artists/meshartist.py | 4 +- src/compas_ghpython/artists/polygonartist.py | 9 +- src/compas_ghpython/artists/polylineartist.py | 4 +- src/compas_ghpython/artists/volmeshartist.py | 18 +- src/compas_ghpython/install.py | 4 +- src/compas_ghpython/uninstall.py | 15 +- src/compas_ghpython/utilities/drawing.py | 8 +- src/compas_plotters/artists/lineartist.py | 8 +- src/compas_plotters/artists/meshartist.py | 54 ++--- src/compas_plotters/artists/networkartist.py | 20 +- src/compas_plotters/core/drawing.py | 16 +- src/compas_plotters/core/helpers.py | 4 +- src/compas_plotters/core/utilities.py | 4 +- src/compas_plotters/plotter.py | 8 +- src/compas_rhino/__init__.py | 38 +--- src/compas_rhino/artists/circleartist.py | 12 +- src/compas_rhino/artists/curveartist.py | 4 +- src/compas_rhino/artists/frameartist.py | 8 +- src/compas_rhino/artists/lineartist.py | 12 +- src/compas_rhino/artists/meshartist.py | 53 ++--- src/compas_rhino/artists/networkartist.py | 24 +-- src/compas_rhino/artists/pointartist.py | 4 +- src/compas_rhino/artists/polygonartist.py | 21 +- src/compas_rhino/artists/polylineartist.py | 13 +- src/compas_rhino/artists/robotmodelartist.py | 10 +- src/compas_rhino/artists/surfaceartist.py | 8 +- src/compas_rhino/artists/vectorartist.py | 8 +- src/compas_rhino/artists/volmeshartist.py | 68 ++----- src/compas_rhino/conduits/faces.py | 4 +- src/compas_rhino/conduits/labels.py | 8 +- src/compas_rhino/conduits/lines.py | 8 +- src/compas_rhino/conduits/points.py | 5 +- src/compas_rhino/conversions/_primitives.py | 4 +- src/compas_rhino/conversions/_surfaces.py | 4 +- src/compas_rhino/conversions/box.py | 12 +- src/compas_rhino/conversions/cone.py | 4 +- src/compas_rhino/conversions/cylinder.py | 14 +- src/compas_rhino/conversions/mesh.py | 24 +-- src/compas_rhino/conversions/sphere.py | 18 +- src/compas_rhino/conversions/surface.py | 12 +- .../forms/etoforms/propertylist.py | 4 +- src/compas_rhino/forms/etoforms/settings.py | 4 +- src/compas_rhino/forms/slider.py | 4 +- .../geometry/booleans/__init__.py | 12 +- src/compas_rhino/geometry/brep/brep.py | 20 +- src/compas_rhino/geometry/brep/edge.py | 8 +- src/compas_rhino/geometry/curves/nurbs.py | 28 +-- src/compas_rhino/geometry/surfaces/nurbs.py | 22 +-- .../geometry/trimesh/curvature.py | 8 +- src/compas_rhino/install.py | 26 +-- src/compas_rhino/install_plugin.py | 8 +- src/compas_rhino/uninstall.py | 16 +- src/compas_rhino/utilities/drawing.py | 4 +- src/compas_rhino/utilities/layers.py | 8 +- src/compas_rhino/utilities/misc.py | 4 +- src/compas_rhino/utilities/objects.py | 45 +---- 196 files changed, 800 insertions(+), 2702 deletions(-) diff --git a/src/compas/__init__.py b/src/compas/__init__.py index 53f0ac26c99d..e9f7f96d597f 100644 --- a/src/compas/__init__.py +++ b/src/compas/__init__.py @@ -240,9 +240,7 @@ def get(filename): if os.path.exists(localpath): return localpath else: - return "https://raw.githubusercontent.com/compas-dev/compas/main/src/compas/data/samples/{}".format( - filename - ) + return "https://raw.githubusercontent.com/compas-dev/compas/main/src/compas/data/samples/{}".format(filename) def get_bunny(localstorage=None): @@ -288,14 +286,10 @@ def get_bunny(localstorage=None): os.makedirs(localstorage) if not os.path.isdir(localstorage): - raise Exception( - "Local storage location does not exist: {}".format(localstorage) - ) + raise Exception("Local storage location does not exist: {}".format(localstorage)) if not os.access(localstorage, os.W_OK): - raise Exception( - "Local storage location is not writable: {}".format(localstorage) - ) + raise Exception("Local storage location is not writable: {}".format(localstorage)) bunny = compas._os.absjoin(localstorage, "bunny/reconstruction/bun_zipper.ply") destination = compas._os.absjoin(localstorage, "bunny.tar.gz") diff --git a/src/compas/__main__.py b/src/compas/__main__.py index abd6600c1b2d..241818786bfb 100644 --- a/src/compas/__main__.py +++ b/src/compas/__main__.py @@ -23,11 +23,7 @@ print("Yay! COMPAS is installed correctly!") print() print("COMPAS: {}".format(compas.__version__)) - print( - "Python: {} ({})".format( - platform.python_version(), platform.python_implementation() - ) - ) + print("Python: {} ({})".format(platform.python_version(), platform.python_implementation())) if pkg_resources: working_set = pkg_resources.working_set diff --git a/src/compas/_os.py b/src/compas/_os.py index 1475d6cf40f7..e9382f5b8d66 100644 --- a/src/compas/_os.py +++ b/src/compas/_os.py @@ -194,9 +194,7 @@ def select_python(python_executable): either `python` or `pythonw`. """ if PYTHON_DIRECTORY and os.path.exists(PYTHON_DIRECTORY): - python_executables = ( - [python_executable] if python_executable else ["pythonw", "python"] - ) + python_executables = [python_executable] if python_executable else ["pythonw", "python"] for python_exe in python_executables: python = os.path.join(PYTHON_DIRECTORY, python_exe) @@ -284,9 +282,7 @@ def _realpath_ipy_win(path): parent_path = os.path.join(path, "..") args = 'dir /c "{}" /Al'.format(parent_path) - process = subprocess.Popen( - args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE - ) + process = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, _error = process.communicate() matches = SYMLINK_REGEX.finditer(output) @@ -302,9 +298,7 @@ def _realpath_ipy_win(path): def _realpath_ipy_posix(path): args = 'readlink -f "{}"'.format(path) - process = subprocess.Popen( - args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE - ) + process = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, _error = process.communicate() return output @@ -323,14 +317,8 @@ def _polyfill_symlinks(symlinks, raise_on_error): mklink_cmd.write("ECHO ret=%symlink_result%\n") for i, (source, link_name) in enumerate(symlinks): dir_symlink_arg = "/D" if os.path.isdir(source) else "" - mklink_cmd.write( - "mklink {} {}\n".format( - dir_symlink_arg, subprocess.list2cmdline([link_name, source]) - ) - ) - mklink_cmd.write( - "IF %ERRORLEVEL% EQU 0 SET /A symlink_result += {} \n".format(2**i) - ) + mklink_cmd.write("mklink {} {}\n".format(dir_symlink_arg, subprocess.list2cmdline([link_name, source]))) + mklink_cmd.write("IF %ERRORLEVEL% EQU 0 SET /A symlink_result += {} \n".format(2**i)) mklink_cmd.write("EXIT /B %symlink_result%\n") @@ -547,9 +535,7 @@ def _run_command_as_admin(command, arguments): with open(temp_path, "w") as remove_symlink_cmd: remove_symlink_cmd.write("@echo off\n") - remove_symlink_cmd.write( - "{} {}\n".format(command, subprocess.list2cmdline(arguments)) - ) + remove_symlink_cmd.write("{} {}\n".format(command, subprocess.list2cmdline(arguments))) _run_as_admin([temp_path]) @@ -588,10 +574,7 @@ def _run_as_admin(command): ctypes.windll.kernel32.WaitForSingleObject(process_handle, INFINITE) ret = ctypes.wintypes.DWORD() - if ( - ctypes.windll.kernel32.GetExitCodeProcess(process_handle, ctypes.byref(ret)) - == 0 - ): + if ctypes.windll.kernel32.GetExitCodeProcess(process_handle, ctypes.byref(ret)) == 0: raise RuntimeError("Failed to retrieve exit code") return ret.value diff --git a/src/compas/artists/artist.py b/src/compas/artists/artist.py index a2284dfe26c1..a973a2edcf7f 100644 --- a/src/compas/artists/artist.py +++ b/src/compas/artists/artist.py @@ -64,9 +64,7 @@ def _get_artist_cls(data, **kwargs): if cls is None: raise DataArtistNotRegistered( - "No artist is registered for this data type: {} in this context: {}".format( - dtype, Artist.CONTEXT - ) + "No artist is registered for this data type: {} in this context: {}".format(dtype, Artist.CONTEXT) ) return cls diff --git a/src/compas/artists/exceptions.py b/src/compas/artists/exceptions.py index 5fd210693326..8b21c798c028 100644 --- a/src/compas/artists/exceptions.py +++ b/src/compas/artists/exceptions.py @@ -12,11 +12,7 @@ class NoArtistContextError(Exception): def __init__(self): error_message = "No context defined." - error_message += ( - "\n\nThis usually means that the script that you are running requires" - ) - error_message += ( - "\na CAD environment but it is being ran as a standalone script" - ) + error_message += "\n\nThis usually means that the script that you are running requires" + error_message += "\na CAD environment but it is being ran as a standalone script" error_message += "\n(ie. from the command line or code editor)." super(NoArtistContextError, self).__init__(error_message) diff --git a/src/compas/artists/meshartist.py b/src/compas/artists/meshartist.py index 619af014ef5c..86afc77eec86 100644 --- a/src/compas/artists/meshartist.py +++ b/src/compas/artists/meshartist.py @@ -106,15 +106,7 @@ class MeshArtist(Artist): default_edgewidth = 1.0 def __init__( - self, - mesh, - vertices=None, - edges=None, - faces=None, - vertexcolor=None, - edgecolor=None, - facecolor=None, - **kwargs + self, mesh, vertices=None, edges=None, faces=None, vertexcolor=None, edgecolor=None, facecolor=None, **kwargs ): super(MeshArtist, self).__init__() @@ -197,10 +189,7 @@ def faces(self, faces): @property def vertex_xyz(self): if self._vertex_xyz is None: - return { - vertex: self.mesh.vertex_attributes(vertex, "xyz") - for vertex in self.mesh.vertices() - } + return {vertex: self.mesh.vertex_attributes(vertex, "xyz") for vertex in self.mesh.vertices()} return self._vertex_xyz @vertex_xyz.setter @@ -218,18 +207,14 @@ def vertex_text(self, text): if text == "key": self._vertex_text = {vertex: str(vertex) for vertex in self.mesh.vertices()} elif text == "index": - self._vertex_text = { - vertex: str(index) for index, vertex in enumerate(self.mesh.vertices()) - } + self._vertex_text = {vertex: str(index) for index, vertex in enumerate(self.mesh.vertices())} elif isinstance(text, dict): self._vertex_text = text @property def vertex_size(self): if not self._vertex_size: - self._vertex_size = { - vertex: self.default_vertexsize for vertex in self.mesh.vertices() - } + self._vertex_size = {vertex: self.default_vertexsize for vertex in self.mesh.vertices()} return self._vertex_size @vertex_size.setter @@ -242,30 +227,22 @@ def vertex_size(self, vertexsize): @property def edge_text(self): if self._edge_text is None: - self._edge_text = { - edge: "{}-{}".format(*edge) for edge in self.mesh.edges() - } + self._edge_text = {edge: "{}-{}".format(*edge) for edge in self.mesh.edges()} return self._edge_text @edge_text.setter def edge_text(self, text): if text == "key": - self._edge_text = { - edge: "{}-{}".format(*edge) for edge in self.mesh.edges() - } + self._edge_text = {edge: "{}-{}".format(*edge) for edge in self.mesh.edges()} elif text == "index": - self._edge_text = { - edge: str(index) for index, edge in enumerate(self.mesh.edges()) - } + self._edge_text = {edge: str(index) for index, edge in enumerate(self.mesh.edges())} elif isinstance(text, dict): self._edge_text = text @property def edge_width(self): if not self._edge_width: - self._edge_width = { - edge: self.default_edgewidth for edge in self.mesh.edges() - } + self._edge_width = {edge: self.default_edgewidth for edge in self.mesh.edges()} return self._edge_width @edge_width.setter @@ -286,9 +263,7 @@ def face_text(self, text): if text == "key": self._face_text = {face: str(face) for face in self.mesh.faces()} elif text == "index": - self._face_text = { - face: str(index) for index, face in enumerate(self.mesh.faces()) - } + self._face_text = {face: str(index) for index, face in enumerate(self.mesh.faces())} elif isinstance(text, dict): self._face_text = text diff --git a/src/compas/artists/networkartist.py b/src/compas/artists/networkartist.py index 1f3f181b21b9..02d8bf948133 100644 --- a/src/compas/artists/networkartist.py +++ b/src/compas/artists/networkartist.py @@ -79,9 +79,7 @@ class NetworkArtist(Artist): default_nodesize = 5 default_edgewidth = 1.0 - def __init__( - self, network, nodes=None, edges=None, nodecolor=None, edgecolor=None, **kwargs - ): + def __init__(self, network, nodes=None, edges=None, nodecolor=None, edgecolor=None, **kwargs): super(NetworkArtist, self).__init__() self._default_nodecolor = None @@ -141,10 +139,7 @@ def edges(self, edges): @property def node_xyz(self): if not self._node_xyz: - return { - node: self.network.node_attributes(node, "xyz") - for node in self.network.nodes() - } + return {node: self.network.node_attributes(node, "xyz") for node in self.network.nodes()} return self._node_xyz @node_xyz.setter @@ -154,9 +149,7 @@ def node_xyz(self, node_xyz): @property def node_size(self): if not self._node_size: - self._node_size = { - node: self.default_nodesize for node in self.network.nodes() - } + self._node_size = {node: self.default_nodesize for node in self.network.nodes()} return self._node_size @node_size.setter @@ -177,39 +170,29 @@ def node_text(self, text): if text == "key": self._node_text = {node: str(node) for node in self.network.nodes()} elif text == "index": - self._node_text = { - node: str(index) for index, node in enumerate(self.network.nodes()) - } + self._node_text = {node: str(index) for index, node in enumerate(self.network.nodes())} elif isinstance(text, dict): self._node_text = text @property def edge_text(self): if not self._edge_text: - self._edge_text = { - edge: "{}-{}".format(*edge) for edge in self.network.edges() - } + self._edge_text = {edge: "{}-{}".format(*edge) for edge in self.network.edges()} return self._edge_text @edge_text.setter def edge_text(self, text): if text == "key": - self._edge_text = { - edge: "{}-{}".format(*edge) for edge in self.network.edges() - } + self._edge_text = {edge: "{}-{}".format(*edge) for edge in self.network.edges()} elif text == "index": - self._edge_text = { - edge: str(index) for index, edge in enumerate(self.network.edges()) - } + self._edge_text = {edge: str(index) for index, edge in enumerate(self.network.edges())} elif isinstance(text, dict): self._edge_text = text @property def edge_width(self): if not self._edge_width: - self._edge_width = { - edge: self.default_edgewidth for edge in self.network.edges() - } + self._edge_width = {edge: self.default_edgewidth for edge in self.network.edges()} return self._edge_width @edge_width.setter diff --git a/src/compas/artists/robotmodelartist.py b/src/compas/artists/robotmodelartist.py index 26a56acb5aee..539d1f88ab50 100644 --- a/src/compas/artists/robotmodelartist.py +++ b/src/compas/artists/robotmodelartist.py @@ -93,10 +93,7 @@ def attached_tool_model(self): tool_model = None if self.attached_tool_models: link_name = self.model.get_end_effector_link() - tool_model = ( - self.attached_tool_models.get(link_name) - or list(self.attached_tool_models.values())[0] - ) + tool_model = self.attached_tool_models.get(link_name) or list(self.attached_tool_models.values())[0] return tool_model def attach_tool_model(self, tool_model): @@ -120,17 +117,9 @@ def attach_tool_model(self, tool_model): self.attached_tool_models[tool_model.link_name] = tool_model ee_frame = link.parent_joint.origin.copy() - initial_transformation = Transformation.from_frame_to_frame( - Frame.worldXY(), ee_frame - ) - - sample_geometry = ( - link.collision[0] - if link.collision - else link.visual[0] - if link.visual - else None - ) + initial_transformation = Transformation.from_frame_to_frame(Frame.worldXY(), ee_frame) + + sample_geometry = link.collision[0] if link.collision else link.visual[0] if link.visual else None if hasattr(sample_geometry, "current_transformation"): relative_transformation = sample_geometry.current_transformation @@ -186,20 +175,12 @@ def attach_mesh(self, mesh, name, link=None, frame=None): sample_geometry = None while sample_geometry is None: - sample_geometry = ( - link.collision[0] - if link.collision - else link.visual[0] - if link.visual - else None - ) + sample_geometry = link.collision[0] if link.collision else link.visual[0] if link.visual else None link = self.model.get_link_by_name(link.parent_joint.parent.link) native_mesh = self.create_geometry(mesh) init_transformation = transformation * sample_geometry.init_transformation - self.transform( - native_mesh, sample_geometry.current_transformation * init_transformation - ) + self.transform(native_mesh, sample_geometry.current_transformation * init_transformation) item = LinkItem() item.native_geometry = [native_mesh] @@ -272,9 +253,7 @@ def create(self, link=None, context=None): str(i), ] mesh_name = ".".join(mesh_name_components) - native_mesh = self.create_geometry( - mesh, name=mesh_name, color=color - ) + native_mesh = self.create_geometry(mesh, name=mesh_name, color=color) self.transform(native_mesh, item.init_transformation) @@ -323,9 +302,7 @@ def meshes(self, link=None, visual=True, collision=False, attached_meshes=True): mesh.transform(item.current_transformation) meshes += new_meshes for child_joint in link.joints: - meshes += self.meshes( - child_joint.child_link, visual, collision, attached_meshes - ) + meshes += self.meshes(child_joint.child_link, visual, collision, attached_meshes) return meshes def scale(self, factor): @@ -398,9 +375,7 @@ def _apply_transformation_on_transformed_link(self, item, transformation): """ if getattr(item, "current_transformation"): - relative_transformation = ( - transformation * item.current_transformation.inverse() - ) + relative_transformation = transformation * item.current_transformation.inverse() else: relative_transformation = transformation for native_geometry in item.native_geometry or []: @@ -431,9 +406,7 @@ def update(self, joint_state, visual=True, collision=True): tool=tool, visual=visual, collision=collision, - transformation=Transformation.from_frame_to_frame( - Frame.worldXY(), frame - ), + transformation=Transformation.from_frame_to_frame(Frame.worldXY(), frame), ) def _update( @@ -444,13 +417,9 @@ def _update( collision=True, parent_transformation=None, ): - transformations = model.compute_transformations( - joint_state, parent_transformation=parent_transformation - ) + transformations = model.compute_transformations(joint_state, parent_transformation=parent_transformation) for j in model.iter_joints(): - self._transform_link_geometry( - j.child_link, transformations[j.name], collision - ) + self._transform_link_geometry(j.child_link, transformations[j.name], collision) return transformations def _transform_link_geometry(self, link, transformation, collision=True): @@ -464,9 +433,7 @@ def _transform_link_geometry(self, link, transformation, collision=True): for item in self.attached_items.get(link.name, {}).values(): self._apply_transformation_on_transformed_link(item, transformation) - def update_tool( - self, tool, joint_state=None, visual=True, collision=True, transformation=None - ): + def update_tool(self, tool, joint_state=None, visual=True, collision=True, transformation=None): """Triggers the update of the robot geometry of the tool. Parameters diff --git a/src/compas/artists/volmeshartist.py b/src/compas/artists/volmeshartist.py index 26596302c85b..86ba6e1f68f3 100644 --- a/src/compas/artists/volmeshartist.py +++ b/src/compas/artists/volmeshartist.py @@ -192,8 +192,7 @@ def cells(self, cells): def vertex_xyz(self): if not self._vertex_xyz: self._vertex_xyz = { - vertex: self.volmesh.vertex_attributes(vertex, "xyz") - for vertex in self.volmesh.vertices() + vertex: self.volmesh.vertex_attributes(vertex, "xyz") for vertex in self.volmesh.vertices() } return self._vertex_xyz @@ -204,43 +203,30 @@ def vertex_xyz(self, vertex_xyz): @property def vertex_text(self): if not self._vertex_text: - self._vertex_text = { - vertex: str(vertex) for vertex in self.volmesh.vertices() - } + self._vertex_text = {vertex: str(vertex) for vertex in self.volmesh.vertices()} return self._vertex_text @vertex_text.setter def vertex_text(self, text): if text == "key": - self._vertex_text = { - vertex: str(vertex) for vertex in self.volmesh.vertices() - } + self._vertex_text = {vertex: str(vertex) for vertex in self.volmesh.vertices()} elif text == "index": - self._vertex_text = { - vertex: str(index) - for index, vertex in enumerate(self.volmesh.vertices()) - } + self._vertex_text = {vertex: str(index) for index, vertex in enumerate(self.volmesh.vertices())} elif isinstance(text, dict): self._vertex_text = text @property def edge_text(self): if not self._edge_text: - self._edge_text = { - edge: "{}-{}".format(*edge) for edge in self.volmesh.edges() - } + self._edge_text = {edge: "{}-{}".format(*edge) for edge in self.volmesh.edges()} return self._edge_text @edge_text.setter def edge_text(self, text): if text == "key": - self._edge_text = { - edge: "{}-{}".format(*edge) for edge in self.volmesh.edges() - } + self._edge_text = {edge: "{}-{}".format(*edge) for edge in self.volmesh.edges()} elif text == "index": - self._edge_text = { - edge: str(index) for index, edge in enumerate(self.volmesh.edges()) - } + self._edge_text = {edge: str(index) for index, edge in enumerate(self.volmesh.edges())} elif isinstance(text, dict): self._edge_text = text @@ -255,9 +241,7 @@ def face_text(self, text): if text == "key": self._face_text = {face: str(face) for face in self.volmesh.faces()} elif text == "index": - self._face_text = { - face: str(index) for index, face in enumerate(self.volmesh.faces()) - } + self._face_text = {face: str(index) for index, face in enumerate(self.volmesh.faces())} elif isinstance(text, dict): self._face_text = text @@ -272,9 +256,7 @@ def cell_text(self, text): if text == "key": self._cell_text = {cell: str(cell) for cell in self.volmesh.cells()} elif text == "index": - self._cell_text = { - cell: str(index) for index, cell in enumerate(self.volmesh.cells()) - } + self._cell_text = {cell: str(index) for index, cell in enumerate(self.volmesh.cells())} elif isinstance(text, dict): self._cell_text = text diff --git a/src/compas/colors/color.py b/src/compas/colors/color.py index 854098a45e92..64f05d9c9bf6 100644 --- a/src/compas/colors/color.py +++ b/src/compas/colors/color.py @@ -825,9 +825,7 @@ def is_rgb1(color): bool """ - return color and all( - isinstance(c, float) and (c >= 0 and c <= 1) for c in color - ) + return color and all(isinstance(c, float) and (c >= 0 and c <= 1) for c in color) @staticmethod def is_rgb255(color): @@ -838,9 +836,7 @@ def is_rgb255(color): bool """ - return color and all( - isinstance(c, int) and (c >= 0 and c <= 255) for c in color - ) + return color and all(isinstance(c, int) and (c >= 0 and c <= 255) for c in color) @staticmethod def is_hex(color): @@ -877,9 +873,7 @@ def lighten(self, factor=10): """ if factor > 100 or factor < 0: - raise ValueError( - "Percentage of increased lightness should be in the range 0-100." - ) + raise ValueError("Percentage of increased lightness should be in the range 0-100.") factor = 1.0 + factor / 100 @@ -930,9 +924,7 @@ def darken(self, factor=10): """ if factor > 100 or factor < 0: - raise ValueError( - "Percentage of reduced lightness should be in the range 0-100." - ) + raise ValueError("Percentage of reduced lightness should be in the range 0-100.") factor = 1.0 - factor / 100 diff --git a/src/compas/data/data.py b/src/compas/data/data.py index cf44c12fb094..bf51b686ec60 100644 --- a/src/compas/data/data.py +++ b/src/compas/data/data.py @@ -143,9 +143,7 @@ def JSONSCHEMA(self): """dict : The schema of the JSON representation of the data of this object.""" if not self._JSONSCHEMA: schema_filename = "{}.json".format(self.JSONSCHEMANAME.lower()) - schema_path = os.path.join( - os.path.dirname(__file__), "schemas", schema_filename - ) + schema_path = os.path.join(os.path.dirname(__file__), "schemas", schema_filename) with open(schema_path, "r") as fp: self._JSONSCHEMA = json.load(fp) return self._JSONSCHEMA @@ -154,9 +152,7 @@ def JSONSCHEMA(self): def jsondefinitions(self): """dict : Reusable schema definitions.""" if not self._jsondefinitions: - schema_path = os.path.join( - os.path.dirname(__file__), "schemas", "compas.json" - ) + schema_path = os.path.join(os.path.dirname(__file__), "schemas", "compas.json") with open(schema_path, "r") as fp: self._jsondefinitions = json.load(fp) return self._jsondefinitions @@ -173,9 +169,7 @@ def jsonvalidator(self): @property def dtype(self): - return "{}/{}".format( - ".".join(self.__class__.__module__.split(".")[:2]), self.__class__.__name__ - ) + return "{}/{}".format(".".join(self.__class__.__module__.split(".")[:2]), self.__class__.__name__) @property def data(self): diff --git a/src/compas/data/encoders.py b/src/compas/data/encoders.py index 785333cbe1cf..47dddadd68d3 100644 --- a/src/compas/data/encoders.py +++ b/src/compas/data/encoders.py @@ -214,16 +214,10 @@ def object_hook(self, o): ) except ImportError: - raise DecoderError( - "The module of the data type can't be found: {}.".format(o["dtype"]) - ) + raise DecoderError("The module of the data type can't be found: {}.".format(o["dtype"])) except AttributeError: - raise DecoderError( - "The data type can't be found in the specified module: {}.".format( - o["dtype"] - ) - ) + raise DecoderError("The data type can't be found in the specified module: {}.".format(o["dtype"])) obj_value = o["value"] diff --git a/src/compas/data/validators.py b/src/compas/data/validators.py index 086171f41f48..b0c5f8521b11 100644 --- a/src/compas/data/validators.py +++ b/src/compas/data/validators.py @@ -125,9 +125,7 @@ def is_float4x4(items): bool """ - return len(items) == 4 and all( - len(item) == 4 and all(isinstance(i, float) for i in item) for item in items - ) + return len(items) == 4 and all(len(item) == 4 and all(isinstance(i, float) for i in item) for item in items) def is_sequence_of_list(items): diff --git a/src/compas/datastructures/assembly/part.py b/src/compas/datastructures/assembly/part.py index b08f70f22ce1..48965acaab08 100644 --- a/src/compas/datastructures/assembly/part.py +++ b/src/compas/datastructures/assembly/part.py @@ -120,12 +120,8 @@ def data(self, data): self.key = data["key"] self.frame.data = data["frame"] self.shape.data = data["shape"] - self.features = [ - (Shape.from_data(shape), operation) for shape, operation in data["features"] - ] - self.transformations = deque( - [Transformation.from_data(T) for T in data["transformations"]] - ) + self.features = [(Shape.from_data(shape), operation) for shape, operation in data["features"]] + self.transformations = deque([Transformation.from_data(T) for T in data["transformations"]]) # ========================================================================== # properties diff --git a/src/compas/datastructures/graph/graph.py b/src/compas/datastructures/graph/graph.py index ba775852665a..3c006debaf4f 100644 --- a/src/compas/datastructures/graph/graph.py +++ b/src/compas/datastructures/graph/graph.py @@ -42,9 +42,7 @@ class Graph(Datastructure): """ - def __init__( - self, name=None, default_node_attributes=None, default_edge_attributes=None - ): + def __init__(self, name=None, default_node_attributes=None, default_edge_attributes=None): super(Graph, self).__init__() self._max_node = -1 self.attributes = {"name": name or "Graph"} @@ -1493,6 +1491,4 @@ def has_edge(self, u, v, directed=True): """ if directed: return u in self.edge and v in self.edge[u] - return (u in self.edge and v in self.edge[u]) or ( - v in self.edge and u in self.edge[v] - ) + return (u in self.edge and v in self.edge[u]) or (v in self.edge and u in self.edge[v]) diff --git a/src/compas/datastructures/halfedge/halfedge.py b/src/compas/datastructures/halfedge/halfedge.py index 08bbc3fe22fb..fe24093be871 100644 --- a/src/compas/datastructures/halfedge/halfedge.py +++ b/src/compas/datastructures/halfedge/halfedge.py @@ -75,9 +75,7 @@ def __init__( def __str__(self): tpl = "" - return tpl.format( - self.number_of_vertices(), self.number_of_faces(), self.number_of_edges() - ) + return tpl.format(self.number_of_vertices(), self.number_of_faces(), self.number_of_edges()) # -------------------------------------------------------------------------- # descriptors @@ -113,17 +111,10 @@ def DATASCHEMA(self): "face": schema.And( dict, is_sequence_of_uint, - lambda x: all( - all(isinstance(item, int) for item in value) - for value in x.values() - ), - lambda x: all( - all(item >= 0 for item in value) for value in x.values() - ), + lambda x: all(all(isinstance(item, int) for item in value) for value in x.values()), + lambda x: all(all(item >= 0 for item in value) for value in x.values()), lambda x: all(len(value) > 2 for value in x.values()), - lambda x: all( - len(value) == len(set(value)) for value in x.values() - ), + lambda x: all(len(value) == len(set(value)) for value in x.values()), ), "facedata": schema.And( dict, @@ -1252,9 +1243,7 @@ def face_attributes(self, key, names=None, values=None): return # use it as a getter if not names: - return FaceAttributeView( - self.default_face_attributes, self.facedata.setdefault(key, {}) - ) + return FaceAttributeView(self.default_face_attributes, self.facedata.setdefault(key, {})) values = [] for name in names: value = self.face_attribute(key, name) @@ -1464,9 +1453,7 @@ def edge_attributes(self, edge, names=None, values=None): if not names: key = str(tuple(sorted(edge))) # get the entire attribute dict - return EdgeAttributeView( - self.default_edge_attributes, self.edgedata.setdefault(key, {}) - ) + return EdgeAttributeView(self.default_edge_attributes, self.edgedata.setdefault(key, {})) # get only the values of the named attributes values = [] for name in names: @@ -1809,9 +1796,7 @@ def euler(self): The Euler characteristic. """ - V = len( - [vkey for vkey in self.vertices() if len(self.vertex_neighbors(vkey)) != 0] - ) + V = len([vkey for vkey in self.vertices() if len(self.vertex_neighbors(vkey)) != 0]) E = self.number_of_edges() F = self.number_of_faces() return V - E + F @@ -2576,9 +2561,7 @@ def face_adjacency_vertices(self, f1, f2): or None, if the faces are not adjacent. """ - return [ - vkey for vkey in self.face_vertices(f1) if vkey in self.face_vertices(f2) - ] + return [vkey for vkey in self.face_vertices(f1) if vkey in self.face_vertices(f2)] def is_face_on_boundary(self, key): """Verify that a face is on a boundary. diff --git a/src/compas/datastructures/halfface/halfface.py b/src/compas/datastructures/halfface/halfface.py index fe7935a64f0a..7d703fd7813b 100644 --- a/src/compas/datastructures/halfface/halfface.py +++ b/src/compas/datastructures/halfface/halfface.py @@ -1210,9 +1210,7 @@ def vertex_attributes(self, vertex, names=None, values=None): # use it as a getter if not names: # return all vertex attributes as a dict - return VertexAttributeView( - self.default_vertex_attributes, self._vertex[vertex] - ) + return VertexAttributeView(self.default_vertex_attributes, self._vertex[vertex]) values = [] for name in names: if name in self._vertex[vertex]: @@ -1425,9 +1423,7 @@ def edge_attributes(self, edge, names=None, values=None): return if not names: key = str(tuple(sorted(edge))) - return EdgeAttributeView( - self.default_edge_attributes, self._edge_data.setdefault(key, {}) - ) + return EdgeAttributeView(self.default_edge_attributes, self._edge_data.setdefault(key, {})) values = [] for name in names: value = self.edge_attribute(edge, name) @@ -1630,9 +1626,7 @@ def face_attributes(self, face, names=None, values=None): self._face_data[key][name] = value return if not names: - return FaceAttributeView( - self.default_face_attributes, self._face_data.setdefault(key, {}) - ) + return FaceAttributeView(self.default_face_attributes, self._face_data.setdefault(key, {})) values = [] for name in names: value = self.face_attribute(face, name) @@ -1835,9 +1829,7 @@ def cell_attributes(self, cell, names=None, values=None): self._cell_data[cell][name] = value return if not names: - return CellAttributeView( - self.default_cell_attributes, self._cell_data.setdefault(cell, {}) - ) + return CellAttributeView(self.default_cell_attributes, self._cell_data.setdefault(cell, {})) values = [] for name in names: value = self.cell_attribute(cell, name) @@ -2508,15 +2500,7 @@ def cell_vertices(self, cell): but in the context of a cell of the `VolMesh`. """ - return list( - set( - [ - vertex - for face in self.cell_faces(cell) - for vertex in self.halfface_vertices(face) - ] - ) - ) + return list(set([vertex for face in self.cell_faces(cell) for vertex in self.halfface_vertices(face)])) def cell_halfedges(self, cell): """The halfedges of a cell. diff --git a/src/compas/datastructures/mesh/clean.py b/src/compas/datastructures/mesh/clean.py index 349d0b058368..4e47478ae865 100644 --- a/src/compas/datastructures/mesh/clean.py +++ b/src/compas/datastructures/mesh/clean.py @@ -47,10 +47,7 @@ def mesh_delete_duplicate_vertices(mesh, precision=None): 36 """ - key_gkey = { - key: geometric_key(mesh.vertex_attributes(key, "xyz"), precision=precision) - for key in mesh.vertices() - } + key_gkey = {key: geometric_key(mesh.vertex_attributes(key, "xyz"), precision=precision) for key in mesh.vertices()} gkey_key = {gkey: key for key, gkey in iter(key_gkey.items())} for key in list(mesh.vertices()): diff --git a/src/compas/datastructures/mesh/contours_numpy.py b/src/compas/datastructures/mesh/contours_numpy.py index 771de47533bf..c1feb571e9a4 100644 --- a/src/compas/datastructures/mesh/contours_numpy.py +++ b/src/compas/datastructures/mesh/contours_numpy.py @@ -82,9 +82,7 @@ def mesh_contours_numpy(mesh, levels=50, density=100): x = xy[:, 0] y = xy[:, 1] - X, Y = meshgrid( - linspace(amin(x), amax(x), 2 * density), linspace(amin(y), amax(y), 2 * density) - ) + X, Y = meshgrid(linspace(amin(x), amax(x), 2 * density), linspace(amin(y), amax(y), 2 * density)) Z = griddata((x, y), z, (X, Y), method="cubic") diff --git a/src/compas/datastructures/mesh/conway.py b/src/compas/datastructures/mesh/conway.py index 6dd6ccc64348..9b72c3912ff4 100644 --- a/src/compas/datastructures/mesh/conway.py +++ b/src/compas/datastructures/mesh/conway.py @@ -59,13 +59,9 @@ def mesh_conway_dual(mesh): vertices = [mesh.face_centroid(fkey) for fkey in mesh.faces()] old_faces_to_new_vertices = {fkey: i for i, fkey in enumerate(mesh.faces())} faces = [ - [ - old_faces_to_new_vertices[fkey] - for fkey in reversed(mesh.vertex_faces(vkey, ordered=True)) - ] + [old_faces_to_new_vertices[fkey] for fkey in reversed(mesh.vertex_faces(vkey, ordered=True))] for vkey in mesh.vertices() - if not mesh.is_vertex_on_boundary(vkey) - and len(mesh.vertex_neighbors(vkey)) != 0 + if not mesh.is_vertex_on_boundary(vkey) and len(mesh.vertex_neighbors(vkey)) != 0 ] return cls.from_vertices_and_faces(vertices, faces) @@ -443,18 +439,13 @@ def mesh_conway_gyro(mesh): cls = type(mesh) vertices = [mesh.vertex_coordinates(vkey) for vkey in mesh.vertices()] vertices += [mesh.face_centroid(fkey) for fkey in mesh.faces()] - vertices += [ - mesh.edge_point(u, v, t=0.33) for u in mesh.vertices() for v in mesh.halfedge[u] - ] + vertices += [mesh.edge_point(u, v, t=0.33) for u in mesh.vertices() for v in mesh.halfedge[u]] V = mesh.number_of_vertices() F = mesh.number_of_faces() vkey_index = {vkey: i for i, vkey in enumerate(mesh.vertices())} fkey_index = {fkey: i + V for i, fkey in enumerate(mesh.faces())} ekey_index = { - halfedge: i + V + F - for i, halfedge in enumerate( - [(u, v) for u in mesh.vertices() for v in mesh.halfedge[u]] - ) + halfedge: i + V + F for i, halfedge in enumerate([(u, v) for u in mesh.vertices() for v in mesh.halfedge[u]]) } faces = [] for fkey in mesh.faces(): diff --git a/src/compas/datastructures/mesh/explode.py b/src/compas/datastructures/mesh/explode.py index 188dc17d5bc7..9d4f584daad0 100644 --- a/src/compas/datastructures/mesh/explode.py +++ b/src/compas/datastructures/mesh/explode.py @@ -43,10 +43,7 @@ def mesh_disconnected_faces(mesh): """ parts = mesh_disconnected_vertices(mesh) - return [ - set([fkey for vkey in part for fkey in mesh.vertex_faces(vkey)]) - for part in parts - ] + return [set([fkey for vkey in part for fkey in mesh.vertex_faces(vkey)]) for part in parts] def mesh_explode(mesh, cls=None): @@ -71,13 +68,9 @@ def mesh_explode(mesh, cls=None): parts = mesh_disconnected_faces(mesh) exploded_meshes = [] for part in parts: - vertex_keys = list( - set([vkey for fkey in part for vkey in mesh.face_vertices(fkey)]) - ) + vertex_keys = list(set([vkey for fkey in part for vkey in mesh.face_vertices(fkey)])) vertices = [mesh.vertex_coordinates(vkey) for vkey in vertex_keys] key_to_index = {vkey: i for i, vkey in enumerate(vertex_keys)} - faces = [ - [key_to_index[vkey] for vkey in mesh.face_vertices(fkey)] for fkey in part - ] + faces = [[key_to_index[vkey] for vkey in mesh.face_vertices(fkey)] for fkey in part] exploded_meshes.append(cls.from_vertices_and_faces(vertices, faces)) return exploded_meshes diff --git a/src/compas/datastructures/mesh/geodesics_numpy.py b/src/compas/datastructures/mesh/geodesics_numpy.py index 162aa3b6d7ea..a88daf7c86b6 100644 --- a/src/compas/datastructures/mesh/geodesics_numpy.py +++ b/src/compas/datastructures/mesh/geodesics_numpy.py @@ -45,9 +45,7 @@ def mesh_geodesic_distances_numpy(mesh, sources, m=1.0): key_index = mesh.key_index() vertices = mesh.vertices_attributes("xyz") - faces = [ - [key_index[key] for key in mesh.face_vertices(fkey)] for fkey in mesh.faces() - ] + faces = [[key_index[key] for key in mesh.face_vertices(fkey)] for fkey in mesh.faces()] V = array(vertices) F = array(faces, dtype=int) @@ -83,11 +81,7 @@ def mesh_geodesic_distances_numpy(mesh, sources, m=1.0): unit_e12 = cross(unit, e12) unit_e20 = cross(unit, e20) - grad_u = ( - unit_e01 * u[F[:, 2], None] - + unit_e12 * u[F[:, 0], None] - + unit_e20 * u[F[:, 1], None] - ) / A2 + grad_u = (unit_e01 * u[F[:, 2], None] + unit_e12 * u[F[:, 0], None] + unit_e20 * u[F[:, 1], None]) / A2 X = -grad_u / normrow(grad_u) diff --git a/src/compas/datastructures/mesh/join.py b/src/compas/datastructures/mesh/join.py index 7efb0fce21e4..107b1822adba 100644 --- a/src/compas/datastructures/mesh/join.py +++ b/src/compas/datastructures/mesh/join.py @@ -37,15 +37,10 @@ def mesh_weld(mesh, precision=None, cls=None): gkey_index = {gkey: index for index, gkey in enumerate(gkey_key)} vertices = [key_xyz[key] for gkey, key in gkey_key.items()] - faces = [ - [gkey_index[geo(key_xyz[key], precision)] for key in mesh.face_vertices(fkey)] - for fkey in mesh.faces() - ] + faces = [[gkey_index[geo(key_xyz[key], precision)] for key in mesh.face_vertices(fkey)] for fkey in mesh.faces()] faces[:] = [[u for u, v in pairwise(face + face[:1]) if u != v] for face in faces] - faces[:] = [ - face for face in faces if len(face) > 2 - ] # make sure no face has less than 3 vertices + faces[:] = [face for face in faces if len(face) > 2] # make sure no face has less than 3 vertices mesh = cls.from_vertices_and_faces(vertices, faces) return mesh @@ -92,10 +87,7 @@ def meshes_join(meshes, cls=None): for mesh in meshes: key_index = {key: len(vertices) + i for i, key in enumerate(mesh.vertices())} vertices += [mesh.vertex_coordinates(key) for key in mesh.vertices()] - faces += [ - [key_index[key] for key in mesh.face_vertices(fkey)] - for fkey in mesh.faces() - ] + faces += [[key_index[key] for key in mesh.face_vertices(fkey)] for fkey in mesh.faces()] return cls.from_vertices_and_faces(vertices, faces) diff --git a/src/compas/datastructures/mesh/matrices.py b/src/compas/datastructures/mesh/matrices.py index a9e7012b3705..de5f2a3336c2 100644 --- a/src/compas/datastructures/mesh/matrices.py +++ b/src/compas/datastructures/mesh/matrices.py @@ -59,10 +59,7 @@ def mesh_adjacency_matrix(mesh, rtype="array"): """ key_index = mesh.key_index() - adjacency = [ - [key_index[nbr] for nbr in mesh.vertex_neighbors(key)] - for key in mesh.vertices() - ] + adjacency = [[key_index[nbr] for nbr in mesh.vertex_neighbors(key)] for key in mesh.vertices()] return adjacency_matrix(adjacency, rtype=rtype) @@ -132,10 +129,7 @@ def mesh_degree_matrix(mesh, rtype="array"): """ key_index = mesh.key_index() - adjacency = [ - [key_index[nbr] for nbr in mesh.vertex_neighbors(key)] - for key in mesh.vertices() - ] + adjacency = [[key_index[nbr] for nbr in mesh.vertex_neighbors(key)] for key in mesh.vertices()] return degree_matrix(adjacency, rtype=rtype) @@ -192,9 +186,7 @@ def mesh_face_matrix(mesh, rtype="array"): """ key_index = {key: index for index, key in enumerate(mesh.vertices())} - face_vertices = [ - [key_index[key] for key in mesh.face_vertices(fkey)] for fkey in mesh.faces() - ] + face_vertices = [[key_index[key] for key in mesh.face_vertices(fkey)] for fkey in mesh.faces()] return face_matrix(face_vertices, rtype=rtype) diff --git a/src/compas/datastructures/mesh/mesh.py b/src/compas/datastructures/mesh/mesh.py index d7ea5918082c..b863b893c48b 100644 --- a/src/compas/datastructures/mesh/mesh.py +++ b/src/compas/datastructures/mesh/mesh.py @@ -147,9 +147,7 @@ def __init__( def __str__(self): tpl = "" - return tpl.format( - self.number_of_vertices(), self.number_of_faces(), self.number_of_edges() - ) + return tpl.format(self.number_of_vertices(), self.number_of_faces(), self.number_of_edges()) # -------------------------------------------------------------------------- # customisation @@ -427,21 +425,13 @@ def from_polylines(cls, boundary_polylines, other_polylines): for polyline in boundary_polylines + other_polylines for xyz in [polyline[0], polyline[-1]] ] - boundary_vertices = [ - geometric_key(xyz) for polyline in boundary_polylines for xyz in polyline - ] + boundary_vertices = [geometric_key(xyz) for polyline in boundary_polylines for xyz in polyline] mesh = cls.from_lines( - [ - (u, v) - for polyline in boundary_polylines + other_polylines - for u, v in pairwise(polyline) - ] + [(u, v) for polyline in boundary_polylines + other_polylines for u, v in pairwise(polyline)] ) # remove the vertices that are not from the polyline extremities and the faces with all their vertices on the boundary vertex_keys = [ - vkey - for vkey in mesh.vertices() - if geometric_key(mesh.vertex_coordinates(vkey)) in corner_vertices + vkey for vkey in mesh.vertices() if geometric_key(mesh.vertex_coordinates(vkey)) in corner_vertices ] vertex_map = {vkey: i for i, vkey in enumerate(vertex_keys)} vertices = [mesh.vertex_coordinates(vkey) for vkey in vertex_keys] @@ -449,8 +439,7 @@ def from_polylines(cls, boundary_polylines, other_polylines): for fkey in mesh.faces(): if sum( [ - geometric_key(mesh.vertex_coordinates(vkey)) - not in boundary_vertices + geometric_key(mesh.vertex_coordinates(vkey)) not in boundary_vertices for vkey in mesh.face_vertices(fkey) ] ): @@ -458,8 +447,7 @@ def from_polylines(cls, boundary_polylines, other_polylines): [ vertex_map[vkey] for vkey in mesh.face_vertices(fkey) - if geometric_key(mesh.vertex_coordinates(vkey)) - in corner_vertices + if geometric_key(mesh.vertex_coordinates(vkey)) in corner_vertices ] ) mesh.cull_vertices() @@ -533,10 +521,7 @@ def to_vertices_and_faces(self, triangulated=False): vertices = [self.vertex_coordinates(key) for key in self.vertices()] if not triangulated: - faces = [ - [key_index[key] for key in self.face_vertices(fkey)] - for fkey in self.faces() - ] + faces = [[key_index[key] for key in self.face_vertices(fkey)] for fkey in self.faces()] return vertices, faces faces = [] @@ -552,9 +537,7 @@ def to_vertices_and_faces(self, triangulated=False): faces.append([key_index[a], key_index[b], key_index[c]]) faces.append([key_index[a], key_index[c], key_index[d]]) else: - centroid = centroid_polygon( - [vertices[key_index[key]] for key in face_vertices] - ) + centroid = centroid_polygon([vertices[key_index[key]] for key in face_vertices]) ckey = len(vertices) vertices.append(centroid) @@ -705,10 +688,7 @@ def from_meshgrid(cls, dx, nx, dy=None, ny=None): dy = dy or dx ny = ny or nx - vertices = [ - [x, y, 0.0] - for x, y in product(linspace(0, dx, nx + 1), linspace(0, dy, ny + 1)) - ] + vertices = [[x, y, 0.0] for x, y in product(linspace(0, dx, nx + 1), linspace(0, dy, ny + 1))] faces = [ [ i * (ny + 1) + j, @@ -934,12 +914,7 @@ def centroid(self): """ return scale_vector( - sum_vectors( - [ - scale_vector(self.face_centroid(fkey), self.face_area(fkey)) - for fkey in self.faces() - ] - ), + sum_vectors([scale_vector(self.face_centroid(fkey), self.face_area(fkey)) for fkey in self.faces()]), 1.0 / self.area(), ) @@ -953,12 +928,7 @@ def normal(self): """ return scale_vector( - sum_vectors( - [ - scale_vector(self.face_normal(fkey), self.face_area(fkey)) - for fkey in self.faces() - ] - ), + sum_vectors([scale_vector(self.face_normal(fkey), self.face_area(fkey)) for fkey in self.faces()]), 1.0 / self.area(), ) @@ -1053,9 +1023,7 @@ def vertex_neighborhood_centroid(self, key): The coordinates of the centroid. """ - return centroid_points( - [self.vertex_coordinates(nbr) for nbr in self.vertex_neighbors(key)] - ) + return centroid_points([self.vertex_coordinates(nbr) for nbr in self.vertex_neighbors(key)]) def vertex_normal(self, key): """Return the normal vector at the vertex as the weighted average of the @@ -1072,11 +1040,7 @@ def vertex_normal(self, key): The components of the normal vector. """ - vectors = [ - self.face_normal(fkey, False) - for fkey in self.vertex_faces(key) - if fkey is not None - ] + vectors = [self.face_normal(fkey, False) for fkey in self.vertex_faces(key) if fkey is not None] return normalize_vector(centroid_points(vectors)) def vertex_curvature(self, vkey): @@ -1100,10 +1064,7 @@ def vertex_curvature(self, vkey): """ C = 0 - for u, v in pairwise( - self.vertex_neighbors(vkey, ordered=True) - + self.vertex_neighbors(vkey, ordered=True)[:1] - ): + for u, v in pairwise(self.vertex_neighbors(vkey, ordered=True) + self.vertex_neighbors(vkey, ordered=True)[:1]): C += angle_points( self.vertex_coordinates(vkey), self.vertex_coordinates(u), @@ -1135,9 +1096,7 @@ def edge_coordinates(self, u, v, axes="xyz"): The coordinates of the end point. """ - return self.vertex_coordinates(u, axes=axes), self.vertex_coordinates( - v, axes=axes - ) + return self.vertex_coordinates(u, axes=axes), self.vertex_coordinates(v, axes=axes) def edge_length(self, u, v): """Return the length of an edge. @@ -1260,9 +1219,7 @@ def face_coordinates(self, fkey, axes="xyz"): The coordinates of the vertices of the face. """ - return [ - self.vertex_coordinates(key, axes=axes) for key in self.face_vertices(fkey) - ] + return [self.vertex_coordinates(key, axes=axes) for key in self.face_vertices(fkey)] def face_normal(self, fkey, unitized=True): """Compute the normal of a face. @@ -1382,9 +1339,7 @@ def face_aspect_ratio(self, fkey): * Wikipedia. *Types of mesh*. Available at: https://en.wikipedia.org/wiki/Types_of_mesh. """ - face_edge_lengths = [ - self.edge_length(u, v) for u, v in self.face_halfedges(fkey) - ] + face_edge_lengths = [self.edge_length(u, v) for u, v in self.face_halfedges(fkey)] return max(face_edge_lengths) / min(face_edge_lengths) def face_skewness(self, fkey): @@ -1442,9 +1397,7 @@ def face_curvature(self, fkey): centroid = self.face_centroid(fkey) plane = bestfit_plane(points) max_deviation = max([distance_point_plane(point, plane) for point in points]) - average_distances = vector_average( - [distance_point_point(point, centroid) for point in points] - ) + average_distances = vector_average([distance_point_point(point, centroid) for point in points]) return max_deviation / average_distances def face_plane(self, face): @@ -1583,11 +1536,7 @@ def vertices_on_boundaries(self): nbrs = [vertex for vertex in nbrs if vertex not in vertices] # remove all boundary vertices that were already identified - vertices_all = [ - vertex - for vertex in vertices_all - if all(vertex not in vertices for vertices in boundaries) - ] + vertices_all = [vertex for vertex in vertices_all if all(vertex not in vertices for vertices in boundaries)] # process the remaining boundary vertices if any if vertices_all: diff --git a/src/compas/datastructures/mesh/offset.py b/src/compas/datastructures/mesh/offset.py index 4b0ec017ac11..3b1ba93562d8 100644 --- a/src/compas/datastructures/mesh/offset.py +++ b/src/compas/datastructures/mesh/offset.py @@ -49,9 +49,7 @@ def mesh_offset(mesh, distance=1.0): for vertex in offset.vertices(): normal = mesh.vertex_normal(vertex) xyz = mesh.vertex_coordinates(vertex) - offset.vertex_attributes( - vertex, "xyz", add_vectors(xyz, scale_vector(normal, distance)) - ) + offset.vertex_attributes(vertex, "xyz", add_vectors(xyz, scale_vector(normal, distance))) return offset @@ -109,11 +107,7 @@ def mesh_thicken(mesh, thickness=1.0, both=True): # close boundaries n = thickened_mesh.number_of_vertices() / 2 - edges_on_boundary = [ - edge - for boundary in list(thickened_mesh.edges_on_boundaries()) - for edge in boundary - ] + edges_on_boundary = [edge for boundary in list(thickened_mesh.edges_on_boundaries()) for edge in boundary] for u, v in edges_on_boundary: if u < n and v < n: diff --git a/src/compas/datastructures/mesh/operations/insert.py b/src/compas/datastructures/mesh/operations/insert.py index 85a5e4bf6241..d1d03ee5805b 100644 --- a/src/compas/datastructures/mesh/operations/insert.py +++ b/src/compas/datastructures/mesh/operations/insert.py @@ -106,19 +106,11 @@ def mesh_insert_vertex_on_edge(mesh, u, v, vkey=None): # add new vertex if there is none or if vkey not in vertices if vkey is None: - vkey = mesh.add_vertex( - attr_dict={ - attr: xyz - for attr, xyz in zip(["x", "y", "z"], mesh.edge_midpoint(u, v)) - } - ) + vkey = mesh.add_vertex(attr_dict={attr: xyz for attr, xyz in zip(["x", "y", "z"], mesh.edge_midpoint(u, v))}) elif vkey not in list(mesh.vertices()): vkey = mesh.add_vertex( key=vkey, - attr_dict={ - attr: xyz - for attr, xyz in zip(["x", "y", "z"], mesh.edge_midpoint(u, v)) - }, + attr_dict={attr: xyz for attr, xyz in zip(["x", "y", "z"], mesh.edge_midpoint(u, v))}, ) # insert vertex diff --git a/src/compas/datastructures/mesh/operations/substitute.py b/src/compas/datastructures/mesh/operations/substitute.py index 5786db322164..850e3c9ec895 100644 --- a/src/compas/datastructures/mesh/operations/substitute.py +++ b/src/compas/datastructures/mesh/operations/substitute.py @@ -32,9 +32,7 @@ def mesh_substitute_vertex_in_faces(mesh, old_vkey, new_vkey, fkeys=None): # substitute vertices for fkey in fkeys: - face_vertices = [ - new_vkey if key == old_vkey else key for key in mesh.face_vertices(fkey) - ] + face_vertices = [new_vkey if key == old_vkey else key for key in mesh.face_vertices(fkey)] mesh.delete_face(fkey) mesh.add_face(face_vertices, fkey) diff --git a/src/compas/datastructures/mesh/operations/weld.py b/src/compas/datastructures/mesh/operations/weld.py index f926864beb4d..28d915164f6e 100644 --- a/src/compas/datastructures/mesh/operations/weld.py +++ b/src/compas/datastructures/mesh/operations/weld.py @@ -82,11 +82,7 @@ def mesh_unweld_edges(mesh, edges): # through the edges to unweld network_edges = [] for nbr in mesh.vertex_neighbors(vkey): - if ( - not mesh.is_edge_on_boundary(vkey, nbr) - and (vkey, nbr) not in edges - and (nbr, vkey) not in edges - ): + if not mesh.is_edge_on_boundary(vkey, nbr) and (vkey, nbr) not in edges and (nbr, vkey) not in edges: network_edges.append( ( old_to_new[mesh.halfedge[vkey][nbr]], @@ -104,18 +100,13 @@ def mesh_unweld_edges(mesh, edges): adjacency[i] = {} # collect the disconnected parts around the vertex due to unwelding - vertex_changes[vkey] = [ - [new_to_old[key] for key in part] - for part in connected_components(adjacency) - ] + vertex_changes[vkey] = [[new_to_old[key] for key in part] for part in connected_components(adjacency)] for vkey, changes in vertex_changes.items(): # for each disconnected part replace the vertex by a new vertex in the # faces of the part for change in changes: - mesh_substitute_vertex_in_faces( - mesh, vkey, mesh.add_vertex(attr_dict=mesh.vertex[vkey]), change - ) + mesh_substitute_vertex_in_faces(mesh, vkey, mesh.add_vertex(attr_dict=mesh.vertex[vkey]), change) # delete old vertices mesh.delete_vertex(vkey) diff --git a/src/compas/datastructures/mesh/planarisation.py b/src/compas/datastructures/mesh/planarisation.py index 9f2f79a379bb..a2b3ba870a9c 100644 --- a/src/compas/datastructures/mesh/planarisation.py +++ b/src/compas/datastructures/mesh/planarisation.py @@ -49,9 +49,7 @@ def mesh_flatness(mesh, maxdev=1.0): if len(points) == 3: dev.append(0.0) else: - lengths = [ - distance_point_point(a, b) for a, b in window(points + points[0:1], 2) - ] + lengths = [distance_point_point(a, b) for a, b in window(points + points[0:1], 2)] length = sum(lengths) / len(lengths) d = distance_line_line((points[0], points[2]), (points[1], points[3])) dev.append((d / length) / maxdev) diff --git a/src/compas/datastructures/mesh/pull_numpy.py b/src/compas/datastructures/mesh/pull_numpy.py index ea1885bdf59a..894ed7b06030 100644 --- a/src/compas/datastructures/mesh/pull_numpy.py +++ b/src/compas/datastructures/mesh/pull_numpy.py @@ -46,9 +46,7 @@ def trimesh_pull_points_numpy(mesh, points): i_k = mesh.index_key() fk_fi = {fkey: index for index, fkey in enumerate(mesh.faces())} vertices = array(mesh.vertices_attributes("xyz"), dtype=float64).reshape((-1, 3)) - triangles = array( - [mesh.face_coordinates(fkey) for fkey in mesh.faces()], dtype=float64 - ) + triangles = array([mesh.face_coordinates(fkey) for fkey in mesh.faces()], dtype=float64) points = array(points, dtype=float64).reshape((-1, 3)) closest_vis = argmin(distance_matrix(points, vertices), axis=1) # transformation matrices @@ -59,15 +57,9 @@ def trimesh_pull_points_numpy(mesh, points): point = points[i] closest_vi = closest_vis[i] closest_vk = i_k[closest_vi] - closest_tris = [ - fk_fi[fk] - for fk in mesh.vertex_faces(closest_vk, ordered=True) - if fk is not None - ] + closest_tris = [fk_fi[fk] for fk in mesh.vertex_faces(closest_vk, ordered=True) if fk is not None] # process the connected triangles - d, p, c = _find_closest_component( - point, vertices, triangles, closest_tris, closest_vi - ) + d, p, c = _find_closest_component(point, vertices, triangles, closest_tris, closest_vi) pulled_points.append(p) return pulled_points @@ -80,9 +72,7 @@ def trimesh_pull_points_numpy(mesh, points): def _is_point_in_edgezone(p, p0, p1): n = cross_vectors(p1 - p0, [0, 0, 1.0]) return ( - is_ccw_xy(p0 - p0, n, p - p0) - and not is_ccw_xy(p0 - p0, p1 - p0, p - p0) - and not is_ccw_xy(p1 - p1, n, p - p1) + is_ccw_xy(p0 - p0, n, p - p0) and not is_ccw_xy(p0 - p0, p1 - p0, p - p0) and not is_ccw_xy(p1 - p1, n, p - p1) ) diff --git a/src/compas/datastructures/mesh/remesh.py b/src/compas/datastructures/mesh/remesh.py index 07e97b1a4f9a..583d26cd584d 100644 --- a/src/compas/datastructures/mesh/remesh.py +++ b/src/compas/datastructures/mesh/remesh.py @@ -161,9 +161,7 @@ def trimesh_remesh( if verbose: print("collapse edge: {0} - {1}".format(u, v)) - trimesh_collapse_edge( - mesh, u, v, allow_boundary=allow_boundary_collapse, fixed=fixed - ) + trimesh_collapse_edge(mesh, u, v, allow_boundary=allow_boundary_collapse, fixed=fixed) visited.add(u) visited.add(v) @@ -207,18 +205,8 @@ def trimesh_remesh( if v2 in boundary: valency4 += 2 - current_error = ( - abs(valency1 - 6) - + abs(valency2 - 6) - + abs(valency3 - 6) - + abs(valency4 - 6) - ) - flipped_error = ( - abs(valency1 - 7) - + abs(valency2 - 7) - + abs(valency3 - 5) - + abs(valency4 - 5) - ) + current_error = abs(valency1 - 6) + abs(valency2 - 6) + abs(valency3 - 6) + abs(valency4 - 6) + flipped_error = abs(valency1 - 7) + abs(valency2 - 7) + abs(valency3 - 5) + abs(valency4 - 5) if current_error <= flipped_error: continue diff --git a/src/compas/datastructures/mesh/slice.py b/src/compas/datastructures/mesh/slice.py index ebfdcb3b18f7..d7b6d5100637 100644 --- a/src/compas/datastructures/mesh/slice.py +++ b/src/compas/datastructures/mesh/slice.py @@ -91,10 +91,7 @@ def positive(self): for key in vertices: faces += self.mesh.vertex_faces(key) faces = list(set(faces)) - vdict = { - key: self.mesh.vertex_coordinates(key) - for key in vertices + self.intersections - } + vdict = {key: self.mesh.vertex_coordinates(key) for key in vertices + self.intersections} fdict = [self.mesh.face_vertices(fkey) for fkey in faces] mesh = self.meshtype.from_vertices_and_faces(vdict, fdict) if self.is_mesh_closed: @@ -124,10 +121,7 @@ def negative(self): for key in vertices: faces += self.mesh.vertex_faces(key) faces = list(set(faces)) - vdict = { - key: self.mesh.vertex_coordinates(key) - for key in vertices + self.intersections - } + vdict = {key: self.mesh.vertex_coordinates(key) for key in vertices + self.intersections} fdict = [self.mesh.face_vertices(fkey) for fkey in faces] mesh = self.meshtype.from_vertices_and_faces(vdict, fdict) if self.is_mesh_closed: @@ -153,9 +147,7 @@ def intersect(self): x = intersection_segment_plane((a, b), self.plane) if not x: continue - if any([i != j for i, j in zip(x, a)]) and any( - [i != j for i, j in zip(x, b)] - ): + if any([i != j for i, j in zip(x, a)]) and any([i != j for i, j in zip(x, b)]): L_ax = length_vector(subtract_vectors(x, a)) L_ab = length_vector(subtract_vectors(b, a)) t = L_ax / L_ab @@ -171,11 +163,7 @@ def intersect(self): def split(self): for fkey in list(self.mesh.faces()): - split = [ - key - for key in self.mesh.face_vertices(fkey) - if key in self.intersections - ] + split = [key for key in self.mesh.face_vertices(fkey) if key in self.intersections] if len(split) == 2: u, v = split try: diff --git a/src/compas/datastructures/mesh/smoothing.py b/src/compas/datastructures/mesh/smoothing.py index 5e76e400dd45..fbcd4163086a 100644 --- a/src/compas/datastructures/mesh/smoothing.py +++ b/src/compas/datastructures/mesh/smoothing.py @@ -13,9 +13,7 @@ ] -def mesh_smooth_centroid( - mesh, fixed=None, kmax=100, damping=0.5, callback=None, callback_args=None -): +def mesh_smooth_centroid(mesh, fixed=None, kmax=100, damping=0.5, callback=None, callback_args=None): """Smooth a mesh by moving every free vertex to the centroid of its neighbors. Parameters @@ -59,9 +57,7 @@ def mesh_smooth_centroid( x, y, z = key_xyz[key] - cx, cy, cz = centroid_points( - [key_xyz[nbr] for nbr in mesh.vertex_neighbors(key)] - ) + cx, cy, cz = centroid_points([key_xyz[nbr] for nbr in mesh.vertex_neighbors(key)]) attr["x"] += damping * (cx - x) attr["y"] += damping * (cy - y) @@ -71,9 +67,7 @@ def mesh_smooth_centroid( callback(k, callback_args) -def mesh_smooth_centerofmass( - mesh, fixed=None, kmax=100, damping=0.5, callback=None, callback_args=None -): +def mesh_smooth_centerofmass(mesh, fixed=None, kmax=100, damping=0.5, callback=None, callback_args=None): """Smooth a mesh by moving every free vertex to the center of mass of the polygon formed by the neighboring vertices. Parameters @@ -117,9 +111,7 @@ def mesh_smooth_centerofmass( x, y, z = key_xyz[key] - cx, cy, cz = centroid_polygon( - [key_xyz[nbr] for nbr in mesh.vertex_neighbors(key, ordered=True)] - ) + cx, cy, cz = centroid_polygon([key_xyz[nbr] for nbr in mesh.vertex_neighbors(key, ordered=True)]) attr["x"] += damping * (cx - x) attr["y"] += damping * (cy - y) @@ -129,9 +121,7 @@ def mesh_smooth_centerofmass( callback(k, callback_args) -def mesh_smooth_area( - mesh, fixed=None, kmax=100, damping=0.5, callback=None, callback_args=None -): +def mesh_smooth_area(mesh, fixed=None, kmax=100, damping=0.5, callback=None, callback_args=None): """Smooth a mesh by moving each vertex to the barycenter of the centroids of the surrounding faces, weighted by area. Parameters diff --git a/src/compas/datastructures/mesh/subdivision.py b/src/compas/datastructures/mesh/subdivision.py index b776916ec131..376b43eef13d 100644 --- a/src/compas/datastructures/mesh/subdivision.py +++ b/src/compas/datastructures/mesh/subdivision.py @@ -411,11 +411,7 @@ def mesh_subdivide_catmullclark(mesh, k=1, fixed=None): C = sum(1 if crease else 0 for crease in creases) if C < 2: - fnbrs = [ - mesh.face_centroid(fkey) - for fkey in mesh.vertex_faces(key) - if fkey is not None - ] + fnbrs = [mesh.face_centroid(fkey) for fkey in mesh.vertex_faces(key) if fkey is not None] enbrs = [ key_xyz[nbr] for nbr in subd.halfedge[key] ] # this should be the location of the original neighbour @@ -536,11 +532,7 @@ def mesh_subdivide_doosabin(mesh, k=1, fixed=None): if key in boundary: continue - face = [ - fkey_old_new[fkey][key] - for fkey in mesh.vertex_faces(key, ordered=True) - if fkey is not None - ] + face = [fkey_old_new[fkey][key] for fkey in mesh.vertex_faces(key, ordered=True) if fkey is not None] subd.add_face(face[::-1]) @@ -697,9 +689,7 @@ def trimesh_subdivide_loop(mesh, k=1, fixed=None): key_xyz = {key: subd.vertex_coordinates(key) for key in subd.vertices()} fkey_vertices = {fkey: subd.face_vertices(fkey)[:] for fkey in subd.faces()} uv_w = { - (u, v): subd.face_vertex_ancestor(fkey, u) - for fkey in subd.faces() - for u, v in subd.face_halfedges(fkey) + (u, v): subd.face_vertex_ancestor(fkey, u) for fkey in subd.faces() for u, v in subd.face_halfedges(fkey) } boundary = set(subd.vertices_on_boundary()) @@ -758,10 +748,7 @@ def trimesh_subdivide_loop(mesh, k=1, fixed=None): if (u, v) in uv_w and (v, u) in uv_w: c = key_xyz[uv_w[(u, v)]] d = key_xyz[uv_w[(v, u)]] - xyz = [ - (3.0 / 8.0) * (a[i] + b[i]) + (1.0 / 8.0) * (c[i] + d[i]) - for i in range(3) - ] + xyz = [(3.0 / 8.0) * (a[i] + b[i]) + (1.0 / 8.0) * (c[i] + d[i]) for i in range(3)] else: xyz = [0.5 * (a[i] + b[i]) for i in range(3)] diff --git a/src/compas/datastructures/mesh/trimesh_samplepoints_numpy.py b/src/compas/datastructures/mesh/trimesh_samplepoints_numpy.py index 189b3771e37a..0edbaae9cba3 100644 --- a/src/compas/datastructures/mesh/trimesh_samplepoints_numpy.py +++ b/src/compas/datastructures/mesh/trimesh_samplepoints_numpy.py @@ -66,9 +66,7 @@ def trimesh_samplepoints_numpy(mesh, num_points=1000, return_normals=False): # (1) Prepare data for computing key_index = mesh.key_index() vertices = mesh.vertices_attributes("xyz") - faces = [ - [key_index[key] for key in mesh.face_vertices(fkey)] for fkey in mesh.faces() - ] + faces = [[key_index[key] for key in mesh.face_vertices(fkey)] for fkey in mesh.faces()] V = array(vertices, dtype=float64) F = array(faces, dtype=int) @@ -103,13 +101,9 @@ def trimesh_samplepoints_numpy(mesh, num_points=1000, return_normals=False): if return_normals: samples_points_normals = cross((v1 - v0), (v2 - v1), axis=1) - samples_points_normals_norm = norm( - samples_points_normals, ord=2, axis=1, keepdims=True - ) + samples_points_normals_norm = norm(samples_points_normals, ord=2, axis=1, keepdims=True) samples_points_normals = samples_points_normals / samples_points_normals_norm - samples_points_normals = clip( - samples_points_normals, a_min=finfo(float64).eps, a_max=None - ) + samples_points_normals = clip(samples_points_normals, a_min=finfo(float64).eps, a_max=None) samples_points_normals = samples_points_normals[samples_faces_idx] return samples_points, samples_points_normals diff --git a/src/compas/datastructures/network/complementarity.py b/src/compas/datastructures/network/complementarity.py index 2be933fa7759..a770a300e086 100644 --- a/src/compas/datastructures/network/complementarity.py +++ b/src/compas/datastructures/network/complementarity.py @@ -44,10 +44,6 @@ def network_complement(network, cls=None): cls = type(network) nodes = [network.node_coordinates(key) for key in network.nodes()] - edges = [ - (u, v) - for u, v in combinations(network.nodes(), 2) - if not network.has_edge(u, v, directed=False) - ] + edges = [(u, v) for u, v in combinations(network.nodes(), 2) if not network.has_edge(u, v, directed=False)] return cls.from_nodes_and_edges(nodes, edges) diff --git a/src/compas/datastructures/network/duality.py b/src/compas/datastructures/network/duality.py index 8ff91838fe62..bcd7610b435c 100644 --- a/src/compas/datastructures/network/duality.py +++ b/src/compas/datastructures/network/duality.py @@ -54,10 +54,9 @@ def network_find_cycles(network, breakpoints=None): leaves = list(network.leaves()) if leaves: - u = sorted( - [(key, network.node_coordinates(key, "xy")) for key in leaves], - key=lambda x: (x[1][1], x[1][0]), - )[0][0] + u = sorted([(key, network.node_coordinates(key, "xy")) for key in leaves], key=lambda x: (x[1][1], x[1][0]),)[ + 0 + ][0] else: u = sorted(network.nodes(True), key=lambda x: (x[1]["y"], x[1]["x"]))[0][0] diff --git a/src/compas/datastructures/network/explode.py b/src/compas/datastructures/network/explode.py index 35cb1146c77e..aeb88e933181 100644 --- a/src/compas/datastructures/network/explode.py +++ b/src/compas/datastructures/network/explode.py @@ -43,10 +43,7 @@ def network_disconnected_edges(network): """ components = network_disconnected_nodes(network) - return [ - [(u, v) for u in component for v in network.neighbors(u) if u < v] - for component in components - ] + return [[(u, v) for u in component for v in network.neighbors(u) if u < v] for component in components] def network_explode(network, cls=None): diff --git a/src/compas/datastructures/network/matrices.py b/src/compas/datastructures/network/matrices.py index 38742f775dea..ef113f53f437 100644 --- a/src/compas/datastructures/network/matrices.py +++ b/src/compas/datastructures/network/matrices.py @@ -47,9 +47,7 @@ def network_adjacency_matrix(network, rtype="array"): """ key_index = network.key_index() - adjacency = [ - [key_index[nbr] for nbr in network.neighbors(key)] for key in network.nodes() - ] + adjacency = [[key_index[nbr] for nbr in network.neighbors(key)] for key in network.nodes()] return adjacency_matrix(adjacency, rtype=rtype) @@ -70,9 +68,7 @@ def network_degree_matrix(network, rtype="array"): """ key_index = network.key_index() - adjacency = [ - [key_index[nbr] for nbr in network.neighbors(key)] for key in network.nodes() - ] + adjacency = [[key_index[nbr] for nbr in network.neighbors(key)] for key in network.nodes()] return degree_matrix(adjacency, rtype=rtype) diff --git a/src/compas/datastructures/network/network.py b/src/compas/datastructures/network/network.py index e8bbfdf5a344..ee359c654ffc 100644 --- a/src/compas/datastructures/network/network.py +++ b/src/compas/datastructures/network/network.py @@ -84,9 +84,7 @@ class Network(Graph): is_planar = network_is_planar is_planar_embedding = network_is_planar_embedding - def __init__( - self, name=None, default_node_attributes=None, default_edge_attributes=None - ): + def __init__(self, name=None, default_node_attributes=None, default_edge_attributes=None): _default_node_attributes = {"x": 0.0, "y": 0.0, "z": 0.0} _default_edge_attributes = {} if default_node_attributes: @@ -424,9 +422,7 @@ def node_neighborhood_centroid(self, key): The coordinates of the centroid. """ - return centroid_points( - [self.node_coordinates(nbr) for nbr in self.neighbors(key)] - ) + return centroid_points([self.node_coordinates(nbr) for nbr in self.neighbors(key)]) # -------------------------------------------------------------------------- # edge geometry diff --git a/src/compas/datastructures/network/operations/join.py b/src/compas/datastructures/network/operations/join.py index 61f2a6b93b40..7d2f3f818fd3 100644 --- a/src/compas/datastructures/network/operations/join.py +++ b/src/compas/datastructures/network/operations/join.py @@ -109,23 +109,17 @@ def network_polylines(network, splits=None): # ... or until both end are non-two-valent vertices if ( len(network.neighbors(polyline[-1])) != 2 - or geometric_key(network.node_coordinates(polyline[-1])) - in stop_geom_keys + or geometric_key(network.node_coordinates(polyline[-1])) in stop_geom_keys ): polyline = list(reversed(polyline)) if ( len(network.neighbors(polyline[-1])) != 2 - or geometric_key(network.node_coordinates(polyline[-1])) - in stop_geom_keys + or geometric_key(network.node_coordinates(polyline[-1])) in stop_geom_keys ): break # add next edge - polyline.append( - [nbr for nbr in network.neighbors(polyline[-1]) if nbr != polyline[-2]][ - 0 - ] - ) + polyline.append([nbr for nbr in network.neighbors(polyline[-1]) if nbr != polyline[-2]][0]) # delete polyline edges from the list of univisted edges for u, v in pairwise(polyline): @@ -136,6 +130,4 @@ def network_polylines(network, splits=None): polylines.append(polyline) - return [ - [network.node_coordinates(vkey) for vkey in polyline] for polyline in polylines - ] + return [[network.node_coordinates(vkey) for vkey in polyline] for polyline in polylines] diff --git a/src/compas/datastructures/network/planarity.py b/src/compas/datastructures/network/planarity.py index ab85c42afa7c..95243a1f6edf 100644 --- a/src/compas/datastructures/network/planarity.py +++ b/src/compas/datastructures/network/planarity.py @@ -215,11 +215,7 @@ def network_is_planar_embedding(network): Fase otherwise. """ - return ( - network_is_planar(network) - and network_is_xy(network) - and not network_is_crossed(network) - ) + return network_is_planar(network) and network_is_xy(network) and not network_is_crossed(network) def network_embed_in_plane(network, fixed=None, straightline=True): @@ -259,11 +255,7 @@ def network_embed_in_plane(network, fixed=None, straightline=True): xspan = xmax - xmin yspan = ymax - ymin - edges = [ - (u, v) - for u, v in network.edges() - if not network.is_leaf(u) and not network.is_leaf(v) - ] + edges = [(u, v) for u, v in network.edges() if not network.is_leaf(u) and not network.is_leaf(v)] is_embedded = False diff --git a/src/compas/datastructures/network/smoothing.py b/src/compas/datastructures/network/smoothing.py index bf2dae22a39b..ccb708ff3b01 100644 --- a/src/compas/datastructures/network/smoothing.py +++ b/src/compas/datastructures/network/smoothing.py @@ -10,9 +10,7 @@ ] -def network_smooth_centroid( - network, fixed=None, kmax=100, damping=0.5, callback=None, callback_args=None -): +def network_smooth_centroid(network, fixed=None, kmax=100, damping=0.5, callback=None, callback_args=None): """Smooth a network by moving every free node to the centroid of its neighbors. Parameters @@ -56,9 +54,7 @@ def network_smooth_centroid( x, y, z = key_xyz[key] - cx, cy, cz = centroid_points( - [key_xyz[nbr] for nbr in network.neighbors(key)] - ) + cx, cy, cz = centroid_points([key_xyz[nbr] for nbr in network.neighbors(key)]) attr["x"] += damping * (cx - x) attr["y"] += damping * (cy - y) diff --git a/src/compas/datastructures/volmesh/volmesh.py b/src/compas/datastructures/volmesh/volmesh.py index 45d072f17d32..a596d5584ef1 100644 --- a/src/compas/datastructures/volmesh/volmesh.py +++ b/src/compas/datastructures/volmesh/volmesh.py @@ -262,8 +262,7 @@ def to_vertices_and_cells(self): cells = [] for cell in self.cell: faces = [ - [vertex_index[vertex] for vertex in self.halfface_vertices(face)] - for face in self.cell_faces(cell) + [vertex_index[vertex] for vertex in self.halfface_vertices(face)] for face in self.cell_faces(cell) ] cells.append(faces) return vertices, cells @@ -305,10 +304,7 @@ def cell_to_vertices_and_faces(self, cell): faces = self.cell_faces(cell) vertex_index = dict((vertex, index) for index, vertex in enumerate(vertices)) vertices = [self.vertex_coordinates(vertex) for vertex in vertices] - faces = [ - [vertex_index[vertex] for vertex in self.halfface_vertices(face)] - for face in faces - ] + faces = [[vertex_index[vertex] for vertex in self.halfface_vertices(face)] for face in faces] return vertices, faces # -------------------------------------------------------------------------- @@ -374,9 +370,7 @@ def centroid(self): The coordinates of the centroid. """ - return centroid_points( - [self.vertex_coordinates(vertex) for vertex in self.vertices()] - ) + return centroid_points([self.vertex_coordinates(vertex) for vertex in self.vertices()]) # -------------------------------------------------------------------------- # vertex geometry @@ -433,9 +427,7 @@ def vertex_neighborhood_centroid(self, vertex): The coordinates of the centroid. """ - return centroid_points( - [self.vertex_coordinates(nbr) for nbr in self.vertex_neighbors(vertex)] - ) + return centroid_points([self.vertex_coordinates(nbr) for nbr in self.vertex_neighbors(vertex)]) # -------------------------------------------------------------------------- # edge geometry @@ -460,9 +452,7 @@ def edge_coordinates(self, edge, axes="xyz"): """ u, v = edge - return self.vertex_coordinates(u, axes=axes), self.vertex_coordinates( - v, axes=axes - ) + return self.vertex_coordinates(u, axes=axes), self.vertex_coordinates(v, axes=axes) def edge_length(self, edge): """Return the length of an edge. @@ -574,10 +564,7 @@ def face_coordinates(self, face, axes="xyz"): The coordinates of the vertices of the face. """ - return [ - self.vertex_coordinates(vertex, axes=axes) - for vertex in self.face_vertices(face) - ] + return [self.vertex_coordinates(vertex, axes=axes) for vertex in self.face_vertices(face)] def face_normal(self, face, unitized=True): """Compute the oriented normal of a face. @@ -694,9 +681,7 @@ def face_aspect_ratio(self, face): Available at: https://en.wikipedia.org/wiki/Types_of_mesh. """ - face_edge_lengths = [ - self.edge_length(edge) for edge in self.face_halfedges(face) - ] + face_edge_lengths = [self.edge_length(edge) for edge in self.face_halfedges(face)] return max(face_edge_lengths) / min(face_edge_lengths) halfface_area = face_area @@ -763,9 +748,5 @@ def cell_vertex_normal(self, cell, vertex): """ cell_faces = self.cell_faces(cell) - vectors = [ - self.face_normal(face) - for face in self.vertex_faces(vertex) - if face in cell_faces - ] + vectors = [self.face_normal(face) for face in self.vertex_faces(vertex) if face in cell_faces] return normalize_vector(centroid_points(vectors)) diff --git a/src/compas/files/_xml/xml_pre_38.py b/src/compas/files/_xml/xml_pre_38.py index b230baade47a..6661ca6c8fec 100644 --- a/src/compas/files/_xml/xml_pre_38.py +++ b/src/compas/files/_xml/xml_pre_38.py @@ -17,9 +17,7 @@ def xml_from_file(source, tree_parser=None): if tree_parser: - raise NotImplementedError( - "XML parsing on CPython 3.7 and older does not support a custom tree parser" - ) + raise NotImplementedError("XML parsing on CPython 3.7 and older does not support a custom tree parser") tree_parser = ET.XMLPullParser parser = tree_parser(events=("start", "start-ns")) @@ -32,9 +30,7 @@ def xml_from_file(source, tree_parser=None): def xml_from_string(text, tree_parser=None): if tree_parser: - raise NotImplementedError( - "XML parsing on CPython 3.7 and older does not support a custom tree parser" - ) + raise NotImplementedError("XML parsing on CPython 3.7 and older does not support a custom tree parser") tree_parser = ET.XMLPullParser parser = tree_parser(events=("start", "end", "start-ns", "end-ns")) diff --git a/src/compas/files/gltf/data_classes.py b/src/compas/files/gltf/data_classes.py index 36c103e5c96e..0ee6dc996868 100644 --- a/src/compas/files/gltf/data_classes.py +++ b/src/compas/files/gltf/data_classes.py @@ -112,9 +112,7 @@ def from_data(cls, sampler): class TextureData(BaseGLTFDataClass): - def __init__( - self, sampler=None, source=None, name=None, extras=None, extensions=None - ): + def __init__(self, sampler=None, source=None, name=None, extras=None, extensions=None): super(TextureData, self).__init__(extras, extensions) self.sampler = sampler self.source = source @@ -179,18 +177,12 @@ def from_data(cls, texture_info): class OcclusionTextureInfoData(TextureInfoData): - def __init__( - self, index, tex_coord=None, extras=None, extensions=None, strength=None - ): - super(OcclusionTextureInfoData, self).__init__( - index, tex_coord, extras, extensions - ) + def __init__(self, index, tex_coord=None, extras=None, extensions=None, strength=None): + super(OcclusionTextureInfoData, self).__init__(index, tex_coord, extras, extensions) self.strength = strength def to_data(self, texture_index_by_key): - texture_info_dict = super(OcclusionTextureInfoData, self).to_data( - texture_index_by_key - ) + texture_info_dict = super(OcclusionTextureInfoData, self).to_data(texture_index_by_key) if self.strength is not None: texture_info_dict["strength"] = self.strength return texture_info_dict @@ -210,15 +202,11 @@ def from_data(cls, texture_info): class NormalTextureInfoData(TextureInfoData): def __init__(self, index, tex_coord=None, extras=None, extensions=None, scale=None): - super(NormalTextureInfoData, self).__init__( - index, tex_coord, extras, extensions - ) + super(NormalTextureInfoData, self).__init__(index, tex_coord, extras, extensions) self.scale = scale def to_data(self, texture_index_by_key): - texture_info_dict = super(NormalTextureInfoData, self).to_data( - texture_index_by_key - ) + texture_info_dict = super(NormalTextureInfoData, self).to_data(texture_index_by_key) if self.scale is not None: texture_info_dict["scale"] = self.scale return texture_info_dict @@ -259,17 +247,13 @@ def to_data(self, texture_index_by_key): if self.base_color_factor is not None: roughness_dict["baseColorFactor"] = self.base_color_factor if self.base_color_texture is not None: - roughness_dict["baseColorTexture"] = self.base_color_texture.to_data( - texture_index_by_key - ) + roughness_dict["baseColorTexture"] = self.base_color_texture.to_data(texture_index_by_key) if self.metallic_factor is not None: roughness_dict["metallicFactor"] = self.metallic_factor if self.roughness_factor is not None: roughness_dict["roughnessFactor"] = self.roughness_factor if self.metallic_roughness_texture is not None: - roughness_dict[ - "metallicRoughnessTexture" - ] = self.metallic_roughness_texture.to_data(texture_index_by_key) + roughness_dict["metallicRoughnessTexture"] = self.metallic_roughness_texture.to_data(texture_index_by_key) if self.extras is not None: roughness_dict["extras"] = self.extras if self.extensions is not None: @@ -282,14 +266,10 @@ def from_data(cls, texture_info): return None return cls( base_color_factor=texture_info.get("baseColorFactor"), - base_color_texture=TextureInfoData.from_data( - texture_info.get("baseColorTexture") - ), + base_color_texture=TextureInfoData.from_data(texture_info.get("baseColorTexture")), metallic_factor=texture_info.get("metallicFactor"), roughness_factor=texture_info.get("roughnessFactor"), - metallic_roughness_texture=TextureInfoData.from_data( - texture_info.get("metallicRoughnessTexture") - ), + metallic_roughness_texture=TextureInfoData.from_data(texture_info.get("metallicRoughnessTexture")), extras=texture_info.get("extras"), extensions=cls.extensions_from_data(texture_info.get("extensions")), ) @@ -328,21 +308,13 @@ def to_data(self, texture_index_by_key): if self.extras is not None: material_dict["extras"] = self.extras if self.pbr_metallic_roughness is not None: - material_dict["pbrMetallicRoughness"] = self.pbr_metallic_roughness.to_data( - texture_index_by_key - ) + material_dict["pbrMetallicRoughness"] = self.pbr_metallic_roughness.to_data(texture_index_by_key) if self.normal_texture is not None: - material_dict["normalTexture"] = self.normal_texture.to_data( - texture_index_by_key - ) + material_dict["normalTexture"] = self.normal_texture.to_data(texture_index_by_key) if self.occlusion_texture is not None: - material_dict["materialTexture"] = self.occlusion_texture.to_data( - texture_index_by_key - ) + material_dict["materialTexture"] = self.occlusion_texture.to_data(texture_index_by_key) if self.emissive_texture is not None: - material_dict["emissiveTexture"] = self.emissive_texture.to_data( - texture_index_by_key - ) + material_dict["emissiveTexture"] = self.emissive_texture.to_data(texture_index_by_key) if self.emissive_factor is not None: material_dict["emissiveFactor"] = self.emissive_factor if self.alpha_mode is not None: @@ -352,9 +324,7 @@ def to_data(self, texture_index_by_key): if self.double_sided is not None: material_dict["doubleSided"] = self.double_sided if self.extensions is not None: - material_dict["extensions"] = self.extensions_to_data( - texture_index_by_key=texture_index_by_key - ) + material_dict["extensions"] = self.extensions_to_data(texture_index_by_key=texture_index_by_key) return material_dict @classmethod @@ -364,15 +334,9 @@ def from_data(cls, material): return cls( name=material.get("name"), extras=material.get("extras"), - pbr_metallic_roughness=PBRMetallicRoughnessData.from_data( - material.get("pbrMetallicRoughness") - ), - normal_texture=NormalTextureInfoData.from_data( - material.get("normalTexture") - ), - occlusion_texture=OcclusionTextureInfoData.from_data( - material.get("occlusionTexture") - ), + pbr_metallic_roughness=PBRMetallicRoughnessData.from_data(material.get("pbrMetallicRoughness")), + normal_texture=NormalTextureInfoData.from_data(material.get("normalTexture")), + occlusion_texture=OcclusionTextureInfoData.from_data(material.get("occlusionTexture")), emissive_texture=TextureInfoData.from_data(material.get("emissiveTexture")), emissive_factor=material.get("emissiveFactor"), alpha_mode=material.get("alphaMode"), @@ -427,9 +391,7 @@ def from_data(cls, camera): class AnimationSamplerData(BaseGLTFDataClass): - def __init__( - self, input_, output, interpolation=None, extras=None, extensions=None - ): + def __init__(self, input_, output, interpolation=None, extras=None, extensions=None): super(AnimationSamplerData, self).__init__(extras, extensions) self.input = input_ self.output = output @@ -519,9 +481,7 @@ def from_data(cls, channel): class AnimationData(BaseGLTFDataClass): - def __init__( - self, channels, samplers_dict, name=None, extras=None, extensions=None - ): + def __init__(self, channels, samplers_dict, name=None, extras=None, extensions=None): super(AnimationData, self).__init__(extras, extensions) self.channels = channels self.samplers_dict = samplers_dict @@ -531,8 +491,7 @@ def __init__( def to_data(self, samplers_list, node_index_by_key): channels = [ - channel_data.to_data(node_index_by_key, self._sampler_index_by_key) - for channel_data in self.channels + channel_data.to_data(node_index_by_key, self._sampler_index_by_key) for channel_data in self.channels ] animation_dict = { "channels": channels, @@ -547,9 +506,7 @@ def to_data(self, samplers_list, node_index_by_key): return animation_dict def get_sampler_index_by_key(self): - self._sampler_index_by_key = { - key: index for index, key in enumerate(self.samplers_dict) - } + self._sampler_index_by_key = {key: index for index, key in enumerate(self.samplers_dict)} return self._sampler_index_by_key @classmethod @@ -582,11 +539,7 @@ def __init__( self.name = name def to_data(self, node_index_by_key, accessor_index): - node_indices = [ - node_index_by_key.get(item) - for item in self.joints - if node_index_by_key.get(item) is not None - ] + node_indices = [node_index_by_key.get(item) for item in self.joints if node_index_by_key.get(item) is not None] skin_dict = {"joints": node_indices} if self.skeleton is not None: skin_dict["skeleton"] = self.skeleton @@ -680,9 +633,7 @@ def __init__( self.mode = mode self.targets = targets - def to_data( - self, indices_accessor, attributes_dict, targets_dict, material_index_by_key - ): + def to_data(self, indices_accessor, attributes_dict, targets_dict, material_index_by_key): primitive_dict = {"indices": indices_accessor} if self.material is not None: primitive_dict["material"] = material_index_by_key[self.material] diff --git a/src/compas/files/gltf/extensions.py b/src/compas/files/gltf/extensions.py index 8756f047093a..9c21932765f8 100644 --- a/src/compas/files/gltf/extensions.py +++ b/src/compas/files/gltf/extensions.py @@ -31,9 +31,7 @@ def to_data(self, texture_index_by_key, **kwargs): if self.transmission_factor is not None: dct["transmissionFactor"] = self.transmission_factor if self.transmission_texture is not None: - dct["transmissionTexture"] = self.transmission_texture.to_data( - texture_index_by_key - ) + dct["transmissionTexture"] = self.transmission_texture.to_data(texture_index_by_key) if self.extras is not None: dct["extras"] = self.extras if self.extensions is not None: @@ -46,9 +44,7 @@ def from_data(cls, dct): return None return cls( transmission_factor=dct.get("transmissionFactor"), - transmission_texture=create_if_data( - TextureInfoData, dct, "transmissionTexture" - ), + transmission_texture=create_if_data(TextureInfoData, dct, "transmissionTexture"), extensions=cls.extensions_from_data(dct.get("extensions")), extras=dct.get("extras"), ) @@ -86,9 +82,7 @@ def to_data(self, texture_index_by_key, **kwargs): if self.specular_color_factor is not None: dct["specularColorFactor"] = self.specular_color_factor if self.specular_color_texture is not None: - dct["specularColorTexture"] = self.specular_color_texture.to_data( - texture_index_by_key - ) + dct["specularColorTexture"] = self.specular_color_texture.to_data(texture_index_by_key) if self.extras is not None: dct["extras"] = self.extras if self.extensions is not None: @@ -103,9 +97,7 @@ def from_data(cls, dct): specular_factor=dct.get("specularFactor"), specular_texture=create_if_data(TextureInfoData, dct, "specularTexture"), specular_color_factor=dct.get("specularColorFactor"), - specular_color_texture=create_if_data( - TextureInfoData, dct, "specularColorTexture" - ), + specular_color_texture=create_if_data(TextureInfoData, dct, "specularColorTexture"), extensions=cls.extensions_from_data(dct.get("extensions")), extras=dct.get("extras"), ) @@ -179,19 +171,13 @@ def to_data(self, texture_index_by_key, **kwargs): if self.clearcoat_factor is not None: dct["clearcoatFactor"] = self.clearcoat_factor if self.clearcoat_texture is not None: - dct["clearcoatTexture"] = self.clearcoat_texture.to_data( - texture_index_by_key - ) + dct["clearcoatTexture"] = self.clearcoat_texture.to_data(texture_index_by_key) if self.clearcoat_roughness_factor is not None: dct["clearcoatRoughnessFactor"] = self.clearcoat_roughness_factor if self.clearcoat_roughness_texture is not None: - dct["clearcoatRoughnessTexture"] = self.clearcoat_roughness_texture.to_data( - texture_index_by_key - ) + dct["clearcoatRoughnessTexture"] = self.clearcoat_roughness_texture.to_data(texture_index_by_key) if self.clearcoat_normal_texture is not None: - dct["clearcoatNormalTexture"] = self.clearcoat_normal_texture.to_data( - texture_index_by_key - ) + dct["clearcoatNormalTexture"] = self.clearcoat_normal_texture.to_data(texture_index_by_key) if self.extras is not None: dct["extras"] = self.extras if self.extensions is not None: @@ -206,12 +192,8 @@ def from_data(cls, dct): clearcoat_factor=dct.get("clearcoatFactor"), clearcoat_texture=create_if_data(TextureInfoData, dct, "clearcoatTexture"), clearcoat_roughness_factor=dct.get("clearcoatRoughnessFactor"), - clearcoat_roughness_texture=create_if_data( - TextureInfoData, dct, "clearcoatRoughnessTexture" - ), - clearcoat_normal_texture=create_if_data( - NormalTextureInfoData, dct, "clearcoatNormalTexture" - ), + clearcoat_roughness_texture=create_if_data(TextureInfoData, dct, "clearcoatRoughnessTexture"), + clearcoat_normal_texture=create_if_data(NormalTextureInfoData, dct, "clearcoatNormalTexture"), extensions=cls.extensions_from_data(dct.get("extensions")), extras=dct.get("extras"), ) @@ -303,9 +285,7 @@ def to_data(self, texture_index_by_key, **kwargs): if self.glossiness_factor is not None: dct["glossinessFactor"] = self.glossiness_factor if self.specular_glossiness_texture is not None: - dct["specularGlossinessTexture"] = self.specular_glossiness_texture.to_data( - texture_index_by_key - ) + dct["specularGlossinessTexture"] = self.specular_glossiness_texture.to_data(texture_index_by_key) if self.extras is not None: dct["extras"] = self.extras if self.extensions is not None: @@ -321,9 +301,7 @@ def from_data(cls, dct): diffuse_texture=create_if_data(TextureInfoData, dct, "diffuseTexture"), specular_factor=dct.get("specularFactor"), glossiness_factor=dct.get("glossinessFactor"), - specular_glossiness_texture=create_if_data( - TextureInfoData, dct, "specularGlossinessTexture" - ), + specular_glossiness_texture=create_if_data(TextureInfoData, dct, "specularGlossinessTexture"), extensions=cls.extensions_from_data(dct.get("extensions")), extras=dct.get("extras"), ) diff --git a/src/compas/files/gltf/gltf_content.py b/src/compas/files/gltf/gltf_content.py index 4f9f349d9244..dafde42716d0 100644 --- a/src/compas/files/gltf/gltf_content.py +++ b/src/compas/files/gltf/gltf_content.py @@ -135,9 +135,7 @@ def visit_node(key): else: visited_sampler_keys.append(channel.sampler) animation.samplers_dict = { - key: animation.samplers_dict[key] - for key in animation.samplers_dict - if key in visited_sampler_keys + key: animation.samplers_dict[key] for key in animation.samplers_dict if key in visited_sampler_keys } if not animation.samplers_dict: del self.animations[animation_key] @@ -232,9 +230,7 @@ def update_scene_transforms_and_positions(self, scene): cur = self.nodes[cur_key] for child_key in cur.children: child = self.nodes[child_key] - child.transform = multiply_matrices( - cur.transform, child.matrix or child.get_matrix_from_trs() - ) + child.transform = multiply_matrices(cur.transform, child.matrix or child.get_matrix_from_trs()) child.position = transform_points([origin], child.transform)[0] queue.append(child_key) @@ -522,9 +518,7 @@ def visit(node, key): image_uri = "compas_icon_white.png" image_file = os.path.join(dirname, image_uri) try: - download_file_from_remote( - "https://compas.dev/images/compas_icon_white.png", image_file - ) + download_file_from_remote("https://compas.dev/images/compas_icon_white.png", image_file) except urllib.error.HTTPError: pass @@ -553,9 +547,7 @@ def visit(node, key): material.name = "Texture" material.pbr_metallic_roughness = PBRMetallicRoughnessData() material.pbr_metallic_roughness.metallic_factor = 0.0 - material.pbr_metallic_roughness.base_color_texture = TextureInfoData( - index=texture_idx - ) + material.pbr_metallic_roughness.base_color_texture = TextureInfoData(index=texture_idx) material_key = cnt.add_material(material) # add extension diff --git a/src/compas/files/gltf/gltf_exporter.py b/src/compas/files/gltf/gltf_exporter.py index 11ed4a8c2180..7a27a53aebb7 100644 --- a/src/compas/files/gltf/gltf_exporter.py +++ b/src/compas/files/gltf/gltf_exporter.py @@ -199,17 +199,9 @@ def _add_images(self): if src != dst: shutil.copyfile(src, dst) image_data.uri = basename - uri = ( - self._construct_image_data_uri(image_data) if self.embed_data else None - ) - buffer_view = ( - self._construct_buffer_view(image_data.data) - if not self.embed_data - else None - ) - images_list[self._image_index_by_key[key]] = image_data.to_data( - uri, buffer_view - ) + uri = self._construct_image_data_uri(image_data) if self.embed_data else None + buffer_view = self._construct_buffer_view(image_data.data) if not self.embed_data else None + images_list[self._image_index_by_key[key]] = image_data.to_data(uri, buffer_view) self._add_extensions_recursively(image_data) self._gltf_dict["images"] = images_list @@ -253,9 +245,7 @@ def _add_materials(self): return materials_list = [None] * len(self._content.materials) for key, material_data in self._content.materials.items(): - materials_list[self._material_index_by_key[key]] = material_data.to_data( - self._texture_index_by_key - ) + materials_list[self._material_index_by_key[key]] = material_data.to_data(self._texture_index_by_key) self._add_extensions_recursively(material_data) self._gltf_dict["materials"] = materials_list @@ -264,12 +254,8 @@ def _add_skins(self): return skins_list = [None] * len(self._content.skins) for key, skin_data in self._content.skins.items(): - accessor_index = self._construct_accessor( - skin_data.inverse_bind_matrices, COMPONENT_TYPE_FLOAT, TYPE_MAT4 - ) - skins_list[self._skin_index_by_key[key]] = skin_data.to_data( - self._node_index_by_key, accessor_index - ) + accessor_index = self._construct_accessor(skin_data.inverse_bind_matrices, COMPONENT_TYPE_FLOAT, TYPE_MAT4) + skins_list[self._skin_index_by_key[key]] = skin_data.to_data(self._node_index_by_key, accessor_index) self._add_extensions_recursively(skin_data) self._gltf_dict["skins"] = skins_list @@ -297,9 +283,7 @@ def _add_buffer(self): return buffer = {"byteLength": len(self._buffer)} if self._embed_data: - buffer["uri"] = "data:application/octet-stream;base64," + base64.b64encode( - self._buffer - ).decode("ascii") + buffer["uri"] = "data:application/octet-stream;base64," + base64.b64encode(self._buffer).decode("ascii") elif self._ext == ".gltf": buffer["uri"] = self.get_bin_filename() self._gltf_dict["buffers"] = [buffer] @@ -310,9 +294,7 @@ def _add_animations(self): animation_list = [] for animation_data in self._content.animations.values(): samplers_list = self._construct_animation_samplers_list(animation_data) - animation_list.append( - animation_data.to_data(samplers_list, self._node_index_by_key) - ) + animation_list.append(animation_data.to_data(samplers_list, self._node_index_by_key)) self._add_extensions_recursively(animation_data) self._gltf_dict["animations"] = animation_list @@ -327,18 +309,12 @@ def _construct_animation_samplers_list(self, animation_data): include_bounds=True, ) type_ = TYPE_VEC3 - if isinstance(sampler_data.output[0], int) or isinstance( - sampler_data.output[0], float - ): + if isinstance(sampler_data.output[0], int) or isinstance(sampler_data.output[0], float): type_ = TYPE_SCALAR elif len(sampler_data.output[0]) == 4: type_ = TYPE_VEC4 - output_accessor = self._construct_accessor( - sampler_data.output, COMPONENT_TYPE_FLOAT, type_ - ) - samplers_list[sampler_index_by_key[key]] = sampler_data.to_data( - input_accessor, output_accessor - ) + output_accessor = self._construct_accessor(sampler_data.output, COMPONENT_TYPE_FLOAT, type_) + samplers_list[sampler_index_by_key[key]] = sampler_data.to_data(input_accessor, output_accessor) return samplers_list def _set_initial_gltf_dict(self): @@ -354,16 +330,12 @@ def _add_scenes(self): if not self._content.scenes: return if self._content.default_scene_key is not None: - self._gltf_dict["scene"] = self._scene_index_by_key[ - self._content.default_scene_key - ] + self._gltf_dict["scene"] = self._scene_index_by_key[self._content.default_scene_key] else: self._gltf_dict["scene"] = list(self._content.scenes.values())[0].key scene_list = [None] * len(self._content.scenes.values()) for key, scene in self._content.scenes.items(): - scene_list[self._scene_index_by_key[key]] = scene.to_data( - self._node_index_by_key - ) + scene_list[self._scene_index_by_key[key]] = scene.to_data(self._node_index_by_key) self._gltf_dict["scenes"] = scene_list def _add_nodes(self): @@ -388,11 +360,7 @@ def _construct_primitives(self, mesh_data): attributes = {} for attr in primitive_data.attributes: - component_type = ( - COMPONENT_TYPE_UNSIGNED_INT - if attr.startswith("JOINT") - else COMPONENT_TYPE_FLOAT - ) + component_type = COMPONENT_TYPE_UNSIGNED_INT if attr.startswith("JOINT") else COMPONENT_TYPE_FLOAT type_ = TYPE_VEC3 if len(primitive_data.attributes[attr][0]) == 4: type_ = TYPE_VEC4 @@ -408,14 +376,10 @@ def _construct_primitives(self, mesh_data): for attr in target: component_type = COMPONENT_TYPE_FLOAT type_ = TYPE_VEC3 - target_dict[attr] = self._construct_accessor( - target[attr], component_type, type_, True - ) + target_dict[attr] = self._construct_accessor(target[attr], component_type, type_, True) targets.append(target_dict) - primitive_dict = primitive_data.to_data( - indices_accessor, attributes, targets, self._material_index_by_key - ) + primitive_dict = primitive_data.to_data(indices_accessor, attributes, targets, self._material_index_by_key) primitives.append(primitive_dict) return primitives diff --git a/src/compas/files/gltf/gltf_mesh.py b/src/compas/files/gltf/gltf_mesh.py index d217604b0abd..14e2fa37b8db 100644 --- a/src/compas/files/gltf/gltf_mesh.py +++ b/src/compas/files/gltf/gltf_mesh.py @@ -131,15 +131,11 @@ def validate_faces(cls, faces): if not faces: return if len(faces[0]) > 3: - raise Exception( - "Invalid mesh. Expected mesh composed of points, lines xor triangles." - ) + raise Exception("Invalid mesh. Expected mesh composed of points, lines xor triangles.") for face in faces: if len(face) != len(faces[0]): # This restriction could be removed by splitting into multiple primitives. - raise NotImplementedError( - "Invalid mesh. Expected mesh composed of points, lines xor triangles." - ) + raise NotImplementedError("Invalid mesh. Expected mesh composed of points, lines xor triangles.") @classmethod def validate_vertices(cls, vertices): @@ -160,14 +156,10 @@ def validate_vertices(cls, vertices): positions = list(vertices.values()) if isinstance(vertices, dict) else vertices for position in positions: if len(position) != 3: - raise Exception( - "Invalid mesh. Vertices are expected to be points in 3-space." - ) + raise Exception("Invalid mesh. Vertices are expected to be points in 3-space.") @classmethod - def from_vertices_and_faces( - cls, context, vertices, faces, mesh_name=None, extras=None - ): + def from_vertices_and_faces(cls, context, vertices, faces, mesh_name=None, extras=None): """Construct a :class:`~compas.files.GLTFMesh` object from lists of vertices and faces. Vertices can be given as either a list of xyz-tuples or -lists, in which case the faces reference vertices by index, or vertices can be given as a dictionary of @@ -200,9 +192,7 @@ def from_vertices_and_faces( positions = vertices face_list = list(itertools.chain(*faces)) - primitive = PrimitiveData( - {"POSITION": positions}, face_list, None, mode, None, None - ) + primitive = PrimitiveData({"POSITION": positions}, face_list, None, mode, None, None) return cls([primitive], context, mesh_name=mesh_name, extras=extras) diff --git a/src/compas/files/gltf/gltf_node.py b/src/compas/files/gltf/gltf_node.py index ff14a6a91cc6..44650a8e455a 100644 --- a/src/compas/files/gltf/gltf_node.py +++ b/src/compas/files/gltf/gltf_node.py @@ -147,9 +147,7 @@ def translation(self, value): if self._matrix: raise Exception("Cannot set translation when matrix is set.") if not isinstance(value, list) or len(value) != 3: - raise Exception( - "Invalid translation. Translations are expected to be of the form [x, y, z]." - ) + raise Exception("Invalid translation. Translations are expected to be of the form [x, y, z].") self._translation = value @property @@ -163,11 +161,7 @@ def rotation(self, value): return if self._matrix: raise Exception("Cannot set rotation when matrix is set.") - if ( - not isinstance(value, list) - or len(value) != 4 - or fabs(sum([q**2 for q in value]) - 1) > 1e-03 - ): + if not isinstance(value, list) or len(value) != 4 or fabs(sum([q**2 for q in value]) - 1) > 1e-03: raise Exception( "Invalid rotation. Rotations are expected to be given as " "unit quaternions of the form [q1, q2, q3, q4]" @@ -186,9 +180,7 @@ def scale(self, value): if self._matrix: raise Exception("Cannot set scale when matrix is set.") if not isinstance(value, list) or len(value) != 3: - raise Exception( - "Invalid scale. Scales are expected to be of the form [s1, s2, s3]" - ) + raise Exception("Invalid scale. Scales are expected to be of the form [s1, s2, s3]") self._scale = value @property @@ -203,15 +195,8 @@ def matrix(self, value): self._matrix = value return if self.translation or self.rotation or self.scale: - raise Exception( - "Cannot set matrix when translation, rotation or scale is set." - ) - if ( - not isinstance(value, list) - or not value - or not value[0] - or not isinstance(value[0], list) - ): + raise Exception("Cannot set matrix when translation, rotation or scale is set.") + if not isinstance(value, list) or not value or not value[0] or not isinstance(value[0], list): raise Exception("Invalid matrix. A list of lists is expected.") if len(value) != 4 or len(value[0]) != 4: raise Exception("Invalid matrix. A 4x4 matrix is expected.") @@ -359,9 +344,7 @@ def from_data(cls, node, context): gltf_node.translation = node.get("translation") gltf_node.rotation = node.get("rotation") gltf_node.scale = node.get("scale") - gltf_node.matrix = ( - get_matrix_from_col_major_list(node["matrix"]) if "matrix" in node else None - ) + gltf_node.matrix = get_matrix_from_col_major_list(node["matrix"]) if "matrix" in node else None gltf_node.weights = node.get("weights") gltf_node.mesh_key = node.get("mesh") gltf_node.camera = node.get("camera") diff --git a/src/compas/files/gltf/gltf_parser.py b/src/compas/files/gltf/gltf_parser.py index 90ee744b1802..98c82b956581 100644 --- a/src/compas/files/gltf/gltf_parser.py +++ b/src/compas/files/gltf/gltf_parser.py @@ -41,24 +41,18 @@ def parse(self): self.content.extras = self._get_extras() self.content.extensions = self._get_extensions() - self.content.images = { - key: image_data for key, image_data in enumerate(self.reader.image_data) - } + self.content.images = {key: image_data for key, image_data in enumerate(self.reader.image_data)} self.content.samplers = { - key: SamplerData.from_data(sampler) - for key, sampler in enumerate(self.reader.json.get("samplers", [])) + key: SamplerData.from_data(sampler) for key, sampler in enumerate(self.reader.json.get("samplers", [])) } self.content.textures = { - key: TextureData.from_data(texture) - for key, texture in enumerate(self.reader.json.get("textures", [])) + key: TextureData.from_data(texture) for key, texture in enumerate(self.reader.json.get("textures", [])) } self.content.materials = { - key: MaterialData.from_data(material) - for key, material in enumerate(self.reader.json.get("materials", [])) + key: MaterialData.from_data(material) for key, material in enumerate(self.reader.json.get("materials", [])) } self.content.cameras = { - key: CameraData.from_data(camera) - for key, camera in enumerate(self.reader.json.get("cameras", [])) + key: CameraData.from_data(camera) for key, camera in enumerate(self.reader.json.get("cameras", [])) } self.content.skins = { key: SkinData.from_data(skin, self.reader.data[skin["inverseBindMatrices"]]) @@ -83,12 +77,8 @@ def _get_animation_data(self, animation): for index, sampler in enumerate(animation["samplers"]): input_ = self.reader.data[sampler["input"]] output = self.reader.data[sampler["output"]] - sampler_data_dict[index] = AnimationSamplerData.from_data( - sampler, input_, output - ) - channel_data_list = [ - ChannelData.from_data(channel) for channel in animation["channels"] - ] + sampler_data_dict[index] = AnimationSamplerData.from_data(sampler, input_, output) + channel_data_list = [ChannelData.from_data(channel) for channel in animation["channels"]] return AnimationData.from_data(animation, channel_data_list, sampler_data_dict) def _get_extras(self): @@ -120,15 +110,10 @@ def _add_gltf_mesh(self, mesh): target_list = [] for target in primitive.get("targets", []): - target_data = { - attr: self.reader.data[accessor_index] - for attr, accessor_index in target.items() - } + target_data = {attr: self.reader.data[accessor_index] for attr, accessor_index in target.items()} target_list.append(target_data) - primitive_data = PrimitiveData.from_data( - primitive, attributes, indices, target_list - ) + primitive_data = PrimitiveData.from_data(primitive, attributes, indices, target_list) primitive_data_list.append(primitive_data) diff --git a/src/compas/files/gltf/gltf_reader.py b/src/compas/files/gltf/gltf_reader.py index 140267ec2156..c05ecb833e59 100644 --- a/src/compas/files/gltf/gltf_reader.py +++ b/src/compas/files/gltf/gltf_reader.py @@ -209,9 +209,7 @@ def _access_data(self, accessor): return data - def _read_from_buffer_view( - self, buffer_view_index, count, component_type, accessor_offset, num_components - ): + def _read_from_buffer_view(self, buffer_view_index, count, component_type, accessor_offset, num_components): buffer_view = self.json["bufferViews"][buffer_view_index] buffer_view_offset = buffer_view.get("byteOffset", 0) diff --git a/src/compas/files/gltf/helpers.py b/src/compas/files/gltf/helpers.py index 0681723cc382..5acbb644fbe0 100644 --- a/src/compas/files/gltf/helpers.py +++ b/src/compas/files/gltf/helpers.py @@ -25,14 +25,10 @@ def apply_weight(weight, target_coordinate): return weight * target_coordinate def weighted_sum(vertex_coordinate, *targets_coordinate): - return vertex_coordinate + math.fsum( - map(apply_weight, weights, targets_coordinate) - ) + return vertex_coordinate + math.fsum(map(apply_weight, weights, targets_coordinate)) def apply_morph_target(vertex, *targets): - return tuple(map(weighted_sum, vertex, *targets)) + ( - (vertex[-1],) if len(vertex) == 4 else () - ) + return tuple(map(weighted_sum, vertex, *targets)) + ((vertex[-1],) if len(vertex) == 4 else ()) return apply_morph_target @@ -47,23 +43,13 @@ def get_weighted_mesh_vertices(mesh, weights): for primitive_data in mesh.primitive_data_list: position_target_data = [target["POSITION"] for target in primitive_data.targets] apply_morph_targets = get_morph_function(weights) - vertices += list( - map( - apply_morph_targets, - primitive_data.attributes["POSITION"], - *position_target_data - ) - ) + vertices += list(map(apply_morph_targets, primitive_data.attributes["POSITION"], *position_target_data)) return vertices def get_unweighted_primitive_vertices(primitive_data_list): """This returns the vertices within a primitive without any weighted morph targets applied.""" - return list( - itertools.chain( - *[primitive.attributes["POSITION"] for primitive in primitive_data_list] - ) - ) + return list(itertools.chain(*[primitive.attributes["POSITION"] for primitive in primitive_data_list])) def get_mode(faces): diff --git a/src/compas/files/obj.py b/src/compas/files/obj.py index 53b27eb2bcc0..b7478f463fec 100644 --- a/src/compas/files/obj.py +++ b/src/compas/files/obj.py @@ -136,9 +136,7 @@ def write(self, mesh, unweld=False, **kwargs): None """ - self._writer = OBJWriter( - self.filepath, mesh, precision=self.precision, unweld=unweld, **kwargs - ) + self._writer = OBJWriter(self.filepath, mesh, precision=self.precision, unweld=unweld, **kwargs) self._writer.write() @property @@ -534,19 +532,9 @@ def parse(self): self.vertices = [xyz for xyz in iter(vertex.values())] self.points = [index_index[index] for index in self.reader.points] - self.lines = [ - [index_index[index] for index in line] - for line in self.reader.lines - if len(line) == 2 - ] - self.polylines = [ - [index_index[index] for index in line] - for line in self.reader.lines - if len(line) > 2 - ] - self.faces = [ - [index_index[index] for index in face] for face in self.reader.faces - ] + self.lines = [[index_index[index] for index in line] for line in self.reader.lines if len(line) == 2] + self.polylines = [[index_index[index] for index in line] for line in self.reader.lines if len(line) > 2] + self.faces = [[index_index[index] for index in face] for face in self.reader.faces] self.groups = self.reader.groups self.objects = {} for name in self.reader.objects: @@ -601,15 +589,7 @@ def __init__( self.precision = precision or compas.PRECISION self.unweld = unweld self.vertex_tpl = ( - "v {0:." - + self.precision - + "}" - + " {1:." - + self.precision - + "}" - + " {2:." - + self.precision - + "}\n" + "v {0:." + self.precision + "}" + " {1:." + self.precision + "}" + " {2:." + self.precision + "}\n" ) self.v = sum(mesh.number_of_vertices() for mesh in self.meshes) self.f = sum(mesh.number_of_faces() for mesh in self.meshes) diff --git a/src/compas/files/off.py b/src/compas/files/off.py index da9e86d316d9..e96b3cd906f3 100644 --- a/src/compas/files/off.py +++ b/src/compas/files/off.py @@ -247,9 +247,7 @@ class OFFWriter(object): """ - def __init__( - self, filepath, mesh, author=None, email=None, date=None, precision=None - ): + def __init__(self, filepath, mesh, author=None, email=None, date=None, precision=None): self.filepath = filepath self.mesh = mesh self.author = author @@ -257,15 +255,7 @@ def __init__( self.date = date self.precision = precision or compas.PRECISION self.vertex_tpl = ( - "{0:." - + self.precision - + "}" - + " {1:." - + self.precision - + "}" - + " {2:." - + self.precision - + "}\n" + "{0:." + self.precision + "}" + " {1:." + self.precision + "}" + " {2:." + self.precision + "}\n" ) self.v = mesh.number_of_vertices() self.f = mesh.number_of_faces() @@ -305,8 +295,4 @@ def _write_faces(self): for fkey in self.mesh.faces(): vertices = self.mesh.face_vertices(fkey) v = len(vertices) - self.file.write( - "{0} {1}\n".format( - v, " ".join([str(key_index[key]) for key in vertices]) - ) - ) + self.file.write("{0} {1}\n".format(v, " ".join([str(key_index[key]) for key in vertices]))) diff --git a/src/compas/files/ply.py b/src/compas/files/ply.py index d62dce5837c7..2b2ab89699b9 100644 --- a/src/compas/files/ply.py +++ b/src/compas/files/ply.py @@ -315,9 +315,7 @@ def _read_header(self): property_length = parts[2] property_type = parts[3] property_name = parts[4] - self.face_properties.append( - (property_name, property_type, property_length) - ) + self.face_properties.append((property_name, property_type, property_length)) else: property_type = parts[1] property_name = parts[2] @@ -351,9 +349,7 @@ def _read_data(self): elif section == "face": self._read_faces() else: - print( - "user-defined elements are not supported: {0}".format(section) - ) + print("user-defined elements are not supported: {0}".format(section)) pass def _read_data_binary(self): @@ -369,9 +365,7 @@ def _read_data_binary(self): elif section == "face": self._read_faces_binary_wo_numpy() else: - print( - "user-defined elements are not supported: {0}".format(section) - ) + print("user-defined elements are not supported: {0}".format(section)) pass # ========================================================================== @@ -590,9 +584,7 @@ def parse(self): None """ - self.vertices = [ - (vertex["x"], vertex["y"], vertex["z"]) for vertex in self.reader.vertices - ] + self.vertices = [(vertex["x"], vertex["y"], vertex["z"]) for vertex in self.reader.vertices] self.faces = [face["vertex_indices"] for face in self.reader.faces] @@ -616,9 +608,7 @@ class PLYWriter(object): """ - def __init__( - self, filepath, mesh, author=None, email=None, date=None, precision=None - ): + def __init__(self, filepath, mesh, author=None, email=None, date=None, precision=None): self.filepath = filepath self.mesh = mesh self.author = author @@ -626,15 +616,7 @@ def __init__( self.date = date self.precision = precision or compas.PRECISION self.vertex_tpl = ( - "{0:." - + self.precision - + "}" - + " {1:." - + self.precision - + "}" - + " {2:." - + self.precision - + "}\n" + "{0:." + self.precision + "}" + " {1:." + self.precision + "}" + " {2:." + self.precision + "}\n" ) self.v = mesh.number_of_vertices() self.f = mesh.number_of_faces() @@ -681,8 +663,4 @@ def _write_faces(self): for fkey in self.mesh.faces(): vertices = self.mesh.face_vertices(fkey) v = len(vertices) - self.file.write( - "{0} {1}\n".format( - v, " ".join([str(key_index[key]) for key in vertices]) - ) - ) + self.file.write("{0} {1}\n".format(v, " ".join([str(key_index[key]) for key in vertices]))) diff --git a/src/compas/files/stl.py b/src/compas/files/stl.py index 860e66ad76dd..5bc71db857d1 100644 --- a/src/compas/files/stl.py +++ b/src/compas/files/stl.py @@ -361,9 +361,7 @@ def _vertex_xyz(self): mesh = self.mesh.transformed(T) else: mesh = self.mesh - return { - vertex: mesh.vertex_attributes(vertex, "xyz") for vertex in mesh.vertices() - } + return {vertex: mesh.vertex_attributes(vertex, "xyz") for vertex in mesh.vertices()} def write(self): """Write the data to a file. @@ -396,14 +394,10 @@ def _write_footer(self): def _write_faces(self): vertex_xyz = self._vertex_xyz for face in self.mesh.faces(): - self.file.write( - "facet normal {0} {1} {2}\n".format(*self.mesh.face_normal(face)) - ) + self.file.write("facet normal {0} {1} {2}\n".format(*self.mesh.face_normal(face))) self.file.write(" outer loop\n") for vertex in self.mesh.face_vertices(face): - self.file.write( - " vertex {0} {1} {2}\n".format(*vertex_xyz[vertex]) - ) + self.file.write(" vertex {0} {1} {2}\n".format(*vertex_xyz[vertex])) self.file.write(" endloop\n") self.file.write("endfacet\n") @@ -414,9 +408,7 @@ def _write_binary_num_faces(self): try: self.file.write(struct.pack(" tol - for a, b in zip(l1, l2) - ): + if any(not allclose(a, b, tol) if hasattr(a, "__iter__") else fabs(a - b) > tol for a, b in zip(l1, l2)): return False return True @@ -1323,9 +1320,7 @@ def orthonormalize_vectors(vectors): basis = [] for v in vectors: if basis: - e = subtract_vectors( - v, sum_vectors([vector_component(v, b) for b in basis]) - ) + e = subtract_vectors(v, sum_vectors([vector_component(v, b) for b in basis])) else: e = v if any(axis > 1e-10 for axis in e): diff --git a/src/compas/geometry/_core/distance.py b/src/compas/geometry/_core/distance.py index 73b7bb03cc61..899f7992e787 100644 --- a/src/compas/geometry/_core/distance.py +++ b/src/compas/geometry/_core/distance.py @@ -575,9 +575,7 @@ def closest_point_in_cloud(point, cloud): return sqrt(d), xyz, index -def closest_points_in_cloud_numpy( - points, cloud, threshold=10**7, distances=True, num_nbrs=1 -): +def closest_points_in_cloud_numpy(points, cloud, threshold=10**7, distances=True, num_nbrs=1): """Find the closest points in a point cloud to a set of sample points. Parameters diff --git a/src/compas/geometry/curves/nurbs.py b/src/compas/geometry/curves/nurbs.py index f5b5bc340132..5f1d313ffce5 100644 --- a/src/compas/geometry/curves/nurbs.py +++ b/src/compas/geometry/curves/nurbs.py @@ -161,9 +161,7 @@ def from_data(cls, data): multiplicities = data["multiplicities"] degree = data["degree"] is_periodic = data["is_periodic"] - return cls.from_parameters( - points, weights, knots, multiplicities, degree, is_periodic - ) + return cls.from_parameters(points, weights, knots, multiplicities, degree, is_periodic) # ============================================================================== # Properties @@ -225,9 +223,7 @@ def from_step(cls, filepath): return new_nurbscurve_from_step(cls, filepath) @classmethod - def from_parameters( - cls, points, weights, knots, multiplicities, degree, is_periodic=False - ): + def from_parameters(cls, points, weights, knots, multiplicities, degree, is_periodic=False): """Construct a NURBS curve from explicit curve parameters. Parameters @@ -250,9 +246,7 @@ def from_parameters( :class:`~compas.geometry.NurbsCurve` """ - return new_nurbscurve_from_parameters( - cls, points, weights, knots, multiplicities, degree, is_periodic=False - ) + return new_nurbscurve_from_parameters(cls, points, weights, knots, multiplicities, degree, is_periodic=False) @classmethod def from_points(cls, points, degree=3): @@ -336,9 +330,7 @@ def from_circle(cls, circle): knots = [0, 1 / 4, 1 / 2, 3 / 4, 1] mults = [3, 2, 2, 2, 3] weights = [1, w, 1, w, 1, w, 1, w, 1] - return cls.from_parameters( - points=points, weights=weights, knots=knots, multiplicities=mults, degree=2 - ) + return cls.from_parameters(points=points, weights=weights, knots=knots, multiplicities=mults, degree=2) @classmethod def from_ellipse(cls, ellipse): @@ -372,9 +364,7 @@ def from_ellipse(cls, ellipse): knots = [0, 1 / 4, 1 / 2, 3 / 4, 1] mults = [3, 2, 2, 2, 3] weights = [1, w, 1, w, 1, w, 1, w, 1] - return cls.from_parameters( - points=points, weights=weights, knots=knots, multiplicities=mults, degree=2 - ) + return cls.from_parameters(points=points, weights=weights, knots=knots, multiplicities=mults, degree=2) @classmethod def from_line(cls, line): diff --git a/src/compas/geometry/hull/hull.py b/src/compas/geometry/hull/hull.py index ae2c4a58be2f..9004464c42bf 100644 --- a/src/compas/geometry/hull/hull.py +++ b/src/compas/geometry/hull/hull.py @@ -58,12 +58,8 @@ def _seen(face, p): return dot_vectors(normal, vec) >= 0 def _bdry(faces): - bdry_fw = set( - [(face[i - 1], face[i]) for face in faces for i in range(len(face))] - ) - bdry_bk = set( - [(face[i], face[i - 1]) for face in faces for i in range(len(face))] - ) + bdry_fw = set([(face[i - 1], face[i]) for face in faces for i in range(len(face))]) + bdry_bk = set([(face[i], face[i - 1]) for face in faces for i in range(len(face))]) return bdry_fw - bdry_bk def _add_point(hull, p): @@ -72,11 +68,7 @@ def _add_point(hull, p): if len(seen_faces) == len(hull): # if can see all faces, unsee ones looking "down" normal = _normal_face(seen_faces[0]) - seen_faces = [ - face - for face in seen_faces - if dot_vectors(_normal_face(face), normal) > 0 - ] + seen_faces = [face for face in seen_faces if dot_vectors(_normal_face(face), normal) > 0] for face in seen_faces: hull.remove(face) diff --git a/src/compas/geometry/interpolation/coons.py b/src/compas/geometry/interpolation/coons.py index 6be49afe9c0d..8b28675adc3f 100644 --- a/src/compas/geometry/interpolation/coons.py +++ b/src/compas/geometry/interpolation/coons.py @@ -83,13 +83,9 @@ def discrete_coons_patch(ab, bc, dc, ad): for i, ki in enumerate(n_norm): for j, kj in enumerate(m_norm): # first function: linear interpolation of first two opposite curves - lin_interp_ab_dc = add_vectors( - scale_vector(ab[i], (1 - kj)), scale_vector(dc[i], kj) - ) + lin_interp_ab_dc = add_vectors(scale_vector(ab[i], (1 - kj)), scale_vector(dc[i], kj)) # second function: linear interpolation of other two opposite curves - lin_interp_bc_ad = add_vectors( - scale_vector(ad[j], (1 - ki)), scale_vector(bc[j], ki) - ) + lin_interp_bc_ad = add_vectors(scale_vector(ad[j], (1 - ki)), scale_vector(bc[j], ki)) # third function: linear interpolation of four corners resulting a hypar a = scale_vector(ab[0], (1 - ki) * (1 - kj)) b = scale_vector(bc[0], ki * (1 - kj)) @@ -97,9 +93,7 @@ def discrete_coons_patch(ab, bc, dc, ad): d = scale_vector(ad[-1], (1 - ki) * kj) lin_interp_a_b_c_d = sum_vectors([a, b, c, d]) # coons patch = first + second - third functions - array[i][j] = subtract_vectors( - add_vectors(lin_interp_ab_dc, lin_interp_bc_ad), lin_interp_a_b_c_d - ) + array[i][j] = subtract_vectors(add_vectors(lin_interp_ab_dc, lin_interp_bc_ad), lin_interp_a_b_c_d) # create vertex list vertices = [] @@ -110,7 +104,5 @@ def discrete_coons_patch(ab, bc, dc, ad): faces = [] for i in range(n - 1): for j in range(m - 1): - faces.append( - [i * m + j, i * m + j + 1, (i + 1) * m + j + 1, (i + 1) * m + j] - ) + faces.append([i * m + j, i * m + j + 1, (i + 1) * m + j + 1, (i + 1) * m + j]) return vertices, faces diff --git a/src/compas/geometry/intersections/intersections.py b/src/compas/geometry/intersections/intersections.py index e9a456ecfa5f..40484290c55f 100644 --- a/src/compas/geometry/intersections/intersections.py +++ b/src/compas/geometry/intersections/intersections.py @@ -307,9 +307,7 @@ def intersection_segment_plane(segment, plane, tol=1e-6): return None -def intersection_polyline_plane( - polyline, plane, expected_number_of_intersections=None, tol=1e-6 -): +def intersection_polyline_plane(polyline, plane, expected_number_of_intersections=None, tol=1e-6): """Calculate the intersection point of a plane with a polyline. Reduce expected_number_of_intersections to speed up. Parameters @@ -627,9 +625,7 @@ def intersection_sphere_line(sphere, line): a = (l2[0] - l1[0]) ** 2 + (l2[1] - l1[1]) ** 2 + (l2[2] - l1[2]) ** 2 b = 2.0 * ( - (l2[0] - l1[0]) * (l1[0] - sp[0]) - + (l2[1] - l1[1]) * (l1[1] - sp[1]) - + (l2[2] - l1[2]) * (l1[2] - sp[2]) + (l2[0] - l1[0]) * (l1[0] - sp[0]) + (l2[1] - l1[1]) * (l1[1] - sp[1]) + (l2[2] - l1[2]) * (l1[2] - sp[2]) ) c = ( diff --git a/src/compas/geometry/pointclouds/pointcloud.py b/src/compas/geometry/pointclouds/pointcloud.py index a4cdd1d7c99d..7f8daf97f8e7 100644 --- a/src/compas/geometry/pointclouds/pointcloud.py +++ b/src/compas/geometry/pointclouds/pointcloud.py @@ -44,9 +44,7 @@ def DATASCHEMA(self): from schema import Schema from compas.data import is_float3 - return Schema( - {"points": lambda points: all(is_float3(point) for point in points)} - ) + return Schema({"points": lambda points: all(is_float3(point) for point in points)}) @property def JSONSCHEMANAME(self): diff --git a/src/compas/geometry/predicates/predicates_2.py b/src/compas/geometry/predicates/predicates_2.py index 404319a419a2..9e25a7f51b72 100644 --- a/src/compas/geometry/predicates/predicates_2.py +++ b/src/compas/geometry/predicates/predicates_2.py @@ -442,6 +442,4 @@ def is_intersection_segment_segment_xy(ab, cd): """ a, b = ab c, d = cd - return is_ccw_xy(a, c, d) != is_ccw_xy(b, c, d) and is_ccw_xy(a, b, c) != is_ccw_xy( - a, b, d - ) + return is_ccw_xy(a, c, d) != is_ccw_xy(b, c, d) and is_ccw_xy(a, b, c) != is_ccw_xy(a, b, d) diff --git a/src/compas/geometry/predicates/predicates_3.py b/src/compas/geometry/predicates/predicates_3.py index acffef137e5e..52e138ddf5d1 100644 --- a/src/compas/geometry/predicates/predicates_3.py +++ b/src/compas/geometry/predicates/predicates_3.py @@ -409,11 +409,7 @@ def is_on_same_side(p1, p2, segment): a, b, c = triangle - if ( - is_on_same_side(point, a, (b, c)) - and is_on_same_side(point, b, (a, c)) - and is_on_same_side(point, c, (a, b)) - ): + if is_on_same_side(point, a, (b, c)) and is_on_same_side(point, b, (a, c)) and is_on_same_side(point, c, (a, b)): return True return False @@ -704,7 +700,5 @@ def is_point_in_polyhedron(point, polyhedron): """ vertices, faces = polyhedron polygons = [[vertices[index] for index in face] for face in faces] - planes = [ - [centroid_points(polygon), normal_polygon(polygon)] for polygon in polygons - ] + planes = [[centroid_points(polygon), normal_polygon(polygon)] for polygon in polygons] return all(is_point_behind_plane(point, plane) for plane in planes) diff --git a/src/compas/geometry/primitives/frame.py b/src/compas/geometry/primitives/frame.py index 40d703ff3935..d6b427f7d732 100644 --- a/src/compas/geometry/primitives/frame.py +++ b/src/compas/geometry/primitives/frame.py @@ -231,11 +231,7 @@ def __iter__(self): return iter([self.point, self.xaxis, self.yaxis]) def __eq__(self, other, tol=1e-05): - if ( - not hasattr(other, "__iter__") - or not hasattr(other, "__len__") - or len(self) != len(other) - ): + if not hasattr(other, "__iter__") or not hasattr(other, "__len__") or len(self) != len(other): return False return allclose(self, other) diff --git a/src/compas/geometry/primitives/line.py b/src/compas/geometry/primitives/line.py index 36ae7e4cf462..798ee4a3f5be 100644 --- a/src/compas/geometry/primitives/line.py +++ b/src/compas/geometry/primitives/line.py @@ -65,9 +65,7 @@ def DATASCHEMA(self): """:class:`schema.Schema` : Schema of the data representation.""" from schema import Schema - return Schema( - {"start": Point.DATASCHEMA.fget(None), "end": Point.DATASCHEMA.fget(None)} - ) + return Schema({"start": Point.DATASCHEMA.fget(None), "end": Point.DATASCHEMA.fget(None)}) @property def JSONSCHEMANAME(self): diff --git a/src/compas/geometry/primitives/point.py b/src/compas/geometry/primitives/point.py index 976495adae14..4fd46d91b3db 100644 --- a/src/compas/geometry/primitives/point.py +++ b/src/compas/geometry/primitives/point.py @@ -200,9 +200,7 @@ def z(self, z): # ========================================================================== def __repr__(self): - return "Point({0:.{3}f}, {1:.{3}f}, {2:.{3}f})".format( - self.x, self.y, self.z, PRECISION[:1] - ) + return "Point({0:.{3}f}, {1:.{3}f}, {2:.{3}f})".format(self.x, self.y, self.z, PRECISION[:1]) def __len__(self): return 3 @@ -783,9 +781,7 @@ def in_polyhedron(self, polyhedron): """ vertices, faces = polyhedron polygons = [[vertices[index] for index in face] for face in faces] - planes = [ - [centroid_points(polygon), normal_polygon(polygon)] for polygon in polygons - ] + planes = [[centroid_points(polygon), normal_polygon(polygon)] for polygon in polygons] return all(is_point_behind_plane(self, plane) for plane in planes) # ========================================================================== diff --git a/src/compas/geometry/primitives/polygon.py b/src/compas/geometry/primitives/polygon.py index 55d86e9a0b31..1c1cc1e61cfd 100644 --- a/src/compas/geometry/primitives/polygon.py +++ b/src/compas/geometry/primitives/polygon.py @@ -82,9 +82,7 @@ def DATASCHEMA(self): from schema import Schema from compas.data import is_float3 - return Schema( - {"points": lambda points: all(is_float3(point) for point in points)} - ) + return Schema({"points": lambda points: all(is_float3(point) for point in points)}) @property def JSONSCHEMANAME(self): @@ -143,9 +141,7 @@ def points(self, points): @property def lines(self): if not self._lines: - self._lines = [ - Line(a, b) for a, b in pairwise(self.points + self.points[:1]) - ] + self._lines = [Line(a, b) for a, b in pairwise(self.points + self.points[:1])] return self._lines @property @@ -184,9 +180,7 @@ def area(self): # ========================================================================== def __repr__(self): - return "Polygon([{0}])".format( - ", ".join(["{0!r}".format(point) for point in self.points]) - ) + return "Polygon([{0}])".format(", ".join(["{0!r}".format(point) for point in self.points])) def __len__(self): return len(self.points) @@ -202,11 +196,7 @@ def __iter__(self): return iter(self.points) def __eq__(self, other): - if ( - not hasattr(other, "__iter__") - or not hasattr(other, "__len__") - or len(self) != len(other) - ): + if not hasattr(other, "__iter__") or not hasattr(other, "__len__") or len(self) != len(other): return False return allclose(self, other) diff --git a/src/compas/geometry/primitives/polyline.py b/src/compas/geometry/primitives/polyline.py index 217d8421cc05..96b71eb76037 100644 --- a/src/compas/geometry/primitives/polyline.py +++ b/src/compas/geometry/primitives/polyline.py @@ -74,9 +74,7 @@ def DATASCHEMA(self): from schema import Schema from compas.data import is_float3 - return Schema( - {"points": lambda points: all(is_float3(point) for point in points)} - ) + return Schema({"points": lambda points: all(is_float3(point) for point in points)}) @property def JSONSCHEMANAME(self): @@ -144,9 +142,7 @@ def length(self): # ========================================================================== def __repr__(self): - return "Polyline([{0}])".format( - ", ".join(["{0!r}".format(point) for point in self.points]) - ) + return "Polyline([{0}])".format(", ".join(["{0!r}".format(point) for point in self.points])) def __len__(self): return len(self.points) @@ -162,11 +158,7 @@ def __iter__(self): return iter(self.points) def __eq__(self, other): - if ( - not hasattr(other, "__iter__") - or not hasattr(other, "__len__") - or len(self) != len(other) - ): + if not hasattr(other, "__iter__") or not hasattr(other, "__len__") or len(self) != len(other): return False return allclose(self, other) @@ -321,9 +313,7 @@ def split_at_corners(self, angle_threshold): if id1 < id2: split_polylines.append(Polyline(points[id1 : id2 + 1])) else: - looped_pts = [points[i] for i in range(id1, len(points))] + points[ - 1 : id2 + 1 - ] + looped_pts = [points[i] for i in range(id1, len(points))] + points[1 : id2 + 1] split_polylines.append(Polyline(looped_pts)) if self.is_closed() and not corner_ids: @@ -415,10 +405,7 @@ def divide_polyline_by_length(self, length, strict=True, tol=1e-06): if strict is False and not self.is_closed() and len(division_pts) < num_pts + 1: division_pts.append(new_polyline.points[-1]) - elif ( - strict is False - and division_pts[-1].distance_to_point(self.points[-1]) > tol - ): + elif strict is False and division_pts[-1].distance_to_point(self.points[-1]) > tol: division_pts.append(self.points[-1]) return division_pts @@ -441,9 +428,7 @@ def extend(self, length): """ try: start, end = length - self.points[0] = self.points[0] + self.lines[0].vector.unitized().scaled( - -start - ) + self.points[0] = self.points[0] + self.lines[0].vector.unitized().scaled(-start) except TypeError: start = end = length self.points[-1] = self.points[-1] + self.lines[-1].vector.unitized().scaled(end) @@ -491,9 +476,7 @@ def shorten(self, length): del self.points[0] break else: - self.points[0] = line.end + line.vector.unitized().scaled( - -(total_length - start) - ) + self.points[0] = line.end + line.vector.unitized().scaled(-(total_length - start)) break except TypeError: start = end = length @@ -508,9 +491,7 @@ def shorten(self, length): del self.points[-1] break else: - self.points[-1] = line.start + line.vector.unitized().scaled( - total_length - end - ) + self.points[-1] = line.start + line.vector.unitized().scaled(total_length - end) break def shortened(self, length): diff --git a/src/compas/geometry/primitives/quaternion.py b/src/compas/geometry/primitives/quaternion.py index 9a844b316f64..d9b14e5dbcc6 100644 --- a/src/compas/geometry/primitives/quaternion.py +++ b/src/compas/geometry/primitives/quaternion.py @@ -254,11 +254,7 @@ def __setitem__(self, key, value): raise KeyError def __eq__(self, other, tol=1e-05): - if ( - not hasattr(other, "__iter__") - or not hasattr(other, "__len__") - or len(self) != len(other) - ): + if not hasattr(other, "__iter__") or not hasattr(other, "__len__") or len(self) != len(other): return False for v1, v2 in zip(self, other): if math.fabs(v1 - v2) > tol: diff --git a/src/compas/geometry/primitives/vector.py b/src/compas/geometry/primitives/vector.py index 0a09bf2c965e..f7ca259941ca 100644 --- a/src/compas/geometry/primitives/vector.py +++ b/src/compas/geometry/primitives/vector.py @@ -163,9 +163,7 @@ def length(self): # ========================================================================== def __repr__(self): - return "Vector({0:.{3}f}, {1:.{3}f}, {2:.{3}f})".format( - self.x, self.y, self.z, PRECISION[:1] - ) + return "Vector({0:.{3}f}, {1:.{3}f}, {2:.{3}f})".format(self.x, self.y, self.z, PRECISION[:1]) def __len__(self): return 3 diff --git a/src/compas/geometry/shapes/box.py b/src/compas/geometry/shapes/box.py index fba065fe3660..309e28963d3d 100644 --- a/src/compas/geometry/shapes/box.py +++ b/src/compas/geometry/shapes/box.py @@ -166,9 +166,7 @@ def from_data(cls, data): >>> data = {'frame': Frame.worldXY().data, 'xsize': 1.0, 'ysize': 1.0, 'zsize': 1.0} >>> box = Box.from_data(data) """ - return cls( - Frame.from_data(data["frame"]), data["xsize"], data["ysize"], data["zsize"] - ) + return cls(Frame.from_data(data["frame"]), data["xsize"], data["ysize"], data["zsize"]) # ========================================================================== # properties @@ -253,11 +251,7 @@ def dimensions(self): @property def area(self): - return ( - 2 * self.xsize * self.ysize - + 2 * self.ysize * self.zsize - + 2 * self.zsize * self.xsize - ) + return 2 * self.xsize * self.ysize + 2 * self.ysize * self.zsize + 2 * self.zsize * self.xsize @property def volume(self): @@ -275,18 +269,10 @@ def vertices(self): zaxis = self.frame.zaxis width, depth, height = self.xsize, self.ysize, self.zsize - a = point + ( - xaxis * (-0.5 * width) + yaxis * (-0.5 * depth) + zaxis * (-0.5 * height) - ) - b = point + ( - xaxis * (-0.5 * width) + yaxis * (+0.5 * depth) + zaxis * (-0.5 * height) - ) - c = point + ( - xaxis * (+0.5 * width) + yaxis * (+0.5 * depth) + zaxis * (-0.5 * height) - ) - d = point + ( - xaxis * (+0.5 * width) + yaxis * (-0.5 * depth) + zaxis * (-0.5 * height) - ) + a = point + (xaxis * (-0.5 * width) + yaxis * (-0.5 * depth) + zaxis * (-0.5 * height)) + b = point + (xaxis * (-0.5 * width) + yaxis * (+0.5 * depth) + zaxis * (-0.5 * height)) + c = point + (xaxis * (+0.5 * width) + yaxis * (+0.5 * depth) + zaxis * (-0.5 * height)) + d = point + (xaxis * (+0.5 * width) + yaxis * (-0.5 * depth) + zaxis * (-0.5 * height)) e = a + zaxis * height f = d + zaxis * height @@ -335,9 +321,7 @@ def edges(self): # ========================================================================== def __repr__(self): - return "Box({0!r}, {1!r}, {2!r}, {3!r})".format( - self.frame, self.xsize, self.ysize, self.zsize - ) + return "Box({0!r}, {1!r}, {2!r}, {3!r})".format(self.frame, self.xsize, self.ysize, self.zsize) def __len__(self): return 4 diff --git a/src/compas/geometry/shapes/polyhedron.py b/src/compas/geometry/shapes/polyhedron.py index c4525bcb63c5..33e6b7cb9954 100644 --- a/src/compas/geometry/shapes/polyhedron.py +++ b/src/compas/geometry/shapes/polyhedron.py @@ -266,9 +266,7 @@ def edges(self): # ========================================================================== def __repr__(self): - return "".format( - len(self.vertices), len(self.faces) - ) + return "".format(len(self.vertices), len(self.faces)) def __len__(self): return 2 @@ -330,9 +328,7 @@ def from_platonicsolid(cls, f): elif f == 20: vertices, faces = icosahedron() else: - raise ValueError( - "The number of sides of a platonic solid must be one of: 4, 6, 8, 12, 20." - ) + raise ValueError("The number of sides of a platonic solid must be one of: 4, 6, 8, 12, 20.") solid = cls(vertices, faces) return solid @@ -378,9 +374,7 @@ def from_halfspaces(cls, halfspaces, interior_point): interior_point = asarray(interior_point, dtype=float) hsi = HalfspaceIntersection(halfspaces, interior_point) hull = ConvexHull(hsi.intersections) - mesh = Mesh.from_vertices_and_faces( - [hsi.intersections[i] for i in hull.vertices], hull.simplices - ) + mesh = Mesh.from_vertices_and_faces([hsi.intersections[i] for i in hull.vertices], hull.simplices) mesh.unify_cycles() to_merge = [] for a, b in combinations(mesh.faces(), 2): diff --git a/src/compas/geometry/shapes/sphere.py b/src/compas/geometry/shapes/sphere.py index dc810d763826..a6dade3bab3f 100644 --- a/src/compas/geometry/shapes/sphere.py +++ b/src/compas/geometry/shapes/sphere.py @@ -70,9 +70,7 @@ def DATASCHEMA(self): import schema from compas.data import is_float3 - return schema.Schema( - {"point": is_float3, "radius": schema.And(float, lambda x: x > 0)} - ) + return schema.Schema({"point": is_float3, "radius": schema.And(float, lambda x: x > 0)}) @property def JSONSCHEMANAME(self): diff --git a/src/compas/geometry/shapes/torus.py b/src/compas/geometry/shapes/torus.py index 61e3c1133f90..c8cee95683e1 100644 --- a/src/compas/geometry/shapes/torus.py +++ b/src/compas/geometry/shapes/torus.py @@ -125,9 +125,7 @@ def from_data(cls, data): >>> torus = Torus.from_data(data) """ - torus = cls( - Plane.from_data(data["plane"]), data["radius_axis"], data["radius_pipe"] - ) + torus = cls(Plane.from_data(data["plane"]), data["radius_axis"], data["radius_pipe"]) return torus # ========================================================================== @@ -175,9 +173,7 @@ def volume(self): # ========================================================================== def __repr__(self): - return "Torus({0!r}, {1!r}, {2!r})".format( - self.plane, self.radius_axis, self.radius_pipe - ) + return "Torus({0!r}, {1!r}, {2!r})".format(self.plane, self.radius_axis, self.radius_pipe) def __len__(self): return 3 @@ -244,12 +240,8 @@ def to_vertices_and_faces(self, u=16, v=16, triangulated=False): vertices = [] for i in range(u): for j in range(v): - x = cos(i * theta) * ( - self.radius_axis + self.radius_pipe * cos(j * phi) - ) - y = sin(i * theta) * ( - self.radius_axis + self.radius_pipe * cos(j * phi) - ) + x = cos(i * theta) * (self.radius_axis + self.radius_pipe * cos(j * phi)) + y = sin(i * theta) * (self.radius_axis + self.radius_pipe * cos(j * phi)) z = self.radius_pipe * sin(j * phi) vertices.append([x, y, z]) diff --git a/src/compas/geometry/surfaces/nurbs.py b/src/compas/geometry/surfaces/nurbs.py index e4709c8aa68e..cd58634fd1ee 100644 --- a/src/compas/geometry/surfaces/nurbs.py +++ b/src/compas/geometry/surfaces/nurbs.py @@ -296,9 +296,7 @@ def from_points(cls, points, u_degree=3, v_degree=3): :class:`~compas.geometry.NurbsSurface` """ - return new_nurbssurface_from_points( - cls, points, u_degree=u_degree, v_degree=v_degree - ) + return new_nurbssurface_from_points(cls, points, u_degree=u_degree, v_degree=v_degree) @classmethod def from_meshgrid(cls, nu=10, nv=10): diff --git a/src/compas/geometry/surfaces/surface.py b/src/compas/geometry/surfaces/surface.py index f48819a68566..272ed9cb7fd3 100644 --- a/src/compas/geometry/surfaces/surface.py +++ b/src/compas/geometry/surfaces/surface.py @@ -154,10 +154,7 @@ def to_mesh(self, nu=100, nv=None): from compas.datastructures import Mesh nv = nv or nu - vertices = [ - self.point_at(i, j) - for i, j in product(self.u_space(nu + 1), self.v_space(nv + 1)) - ] + vertices = [self.point_at(i, j) for i, j in product(self.u_space(nu + 1), self.v_space(nv + 1))] faces = [ [ i * (nv + 1) + j, @@ -188,10 +185,7 @@ def to_triangles(self, nu=100, nv=None): """ nv = nv or nu - vertices = [ - self.point_at(i, j) - for i, j in product(self.u_space(nu + 1), self.v_space(nv + 1)) - ] + vertices = [self.point_at(i, j) for i, j in product(self.u_space(nu + 1), self.v_space(nv + 1))] triangles = [] for i, j in product(range(nu), range(nv)): a = i * (nv + 1) + j @@ -287,9 +281,7 @@ def xyz(self, nu=10, nv=10): The size of the grid in the V direction. """ - return [ - self.point_at(i, j) for i, j in product(self.u_space(nu), self.v_space(nv)) - ] + return [self.point_at(i, j) for i, j in product(self.u_space(nu), self.v_space(nv))] def point_at(self, u, v): """Compute a point on the surface. diff --git a/src/compas/geometry/transformations/matrices.py b/src/compas/geometry/transformations/matrices.py index 7e4c63418d30..9b1d3ea5756d 100644 --- a/src/compas/geometry/transformations/matrices.py +++ b/src/compas/geometry/transformations/matrices.py @@ -175,9 +175,7 @@ def matrix_determinant(M, check=True): D = 0 for c in range(dim): - D += ( - (-1) ** c * M[0][c] * matrix_determinant(matrix_minor(M, 0, c), check=False) - ) + D += (-1) ** c * M[0][c] * matrix_determinant(matrix_minor(M, 0, c), check=False) return D @@ -232,9 +230,7 @@ def matrix_inverse(M): for r in range(len(M)): cofactor_row = [] for c in range(len(M)): - cofactor_row.append( - (-1) ** (r + c) * matrix_determinant(matrix_minor(M, r, c)) - ) + cofactor_row.append((-1) ** (r + c) * matrix_determinant(matrix_minor(M, r, c))) cofactors.append(cofactor_row) cofactors = transpose_matrix(cofactors) @@ -384,18 +380,14 @@ def decompose_matrix(M): P = deepcopy(Mt) P[0][3], P[1][3], P[2][3], P[3][3] = 0.0, 0.0, 0.0, 1.0 Ptinv = matrix_inverse(transpose_matrix(P)) - perspective = multiply_matrix_vector( - Ptinv, [Mt[0][3], Mt[1][3], Mt[2][3], Mt[3][3]] - ) + perspective = multiply_matrix_vector(Ptinv, [Mt[0][3], Mt[1][3], Mt[2][3], Mt[3][3]]) else: perspective = [0.0, 0.0, 0.0, 1.0] return scale, shear, angles, translation, perspective -def compose_matrix( - scale=None, shear=None, angles=None, translation=None, perspective=None -): +def compose_matrix(scale=None, shear=None, angles=None, translation=None, perspective=None): """Calculates a matrix from the components of scale, shear, euler_angles, translation and perspective. Parameters @@ -775,9 +767,7 @@ def matrix_from_axis_and_angle(axis, angle, point=None): R = [[cosa, 0.0, 0.0], [0.0, cosa, 0.0], [0.0, 0.0, cosa]] - outer_product = [ - [axis[i] * axis[j] * (1.0 - cosa) for i in range(3)] for j in range(3) - ] + outer_product = [[axis[i] * axis[j] * (1.0 - cosa) for i in range(3)] for j in range(3)] R = [[R[i][j] + outer_product[i][j] for i in range(3)] for j in range(3)] axis = scale_vector(axis, sina) @@ -1231,9 +1221,7 @@ def matrix_from_parallel_projection(plane, direction): for i in range(3): T[i][j] -= direction[i] * normal[j] / scale - T[0][3], T[1][3], T[2][3] = scale_vector( - direction, dot_vectors(point, normal) / scale - ) + T[0][3], T[1][3], T[2][3] = scale_vector(direction, dot_vectors(point, normal) / scale) return T @@ -1265,17 +1253,13 @@ def matrix_from_perspective_projection(plane, center_of_projection): T = identity_matrix(4) normal = normalize_vector(normal) - T[0][0] = T[1][1] = T[2][2] = dot_vectors( - subtract_vectors(center_of_projection, point), normal - ) + T[0][0] = T[1][1] = T[2][2] = dot_vectors(subtract_vectors(center_of_projection, point), normal) for j in range(3): for i in range(3): T[i][j] -= center_of_projection[i] * normal[j] - T[0][3], T[1][3], T[2][3] = scale_vector( - center_of_projection, dot_vectors(point, normal) - ) + T[0][3], T[1][3], T[2][3] = scale_vector(center_of_projection, dot_vectors(point, normal)) for i in range(3): T[3][i] -= normal[i] @@ -1407,9 +1391,7 @@ def matrix_from_shear(angle, direction, point, normal): for i in range(3): M[i][j] += angle * direction[i] * normal[j] - M[0][3], M[1][3], M[2][3] = scale_vector( - direction, -angle * dot_vectors(point, normal) - ) + M[0][3], M[1][3], M[2][3] = scale_vector(direction, -angle * dot_vectors(point, normal)) return M diff --git a/src/compas/geometry/transformations/rotation.py b/src/compas/geometry/transformations/rotation.py index a92509428c67..623d95c9ad5f 100644 --- a/src/compas/geometry/transformations/rotation.py +++ b/src/compas/geometry/transformations/rotation.py @@ -77,9 +77,7 @@ def __init__(self, matrix=None, check=True): if matrix: _, _, angles, _, _ = decompose_matrix(matrix) if check: - if not allclose( - flatten(matrix), flatten(matrix_from_euler_angles(angles)) - ): + if not allclose(flatten(matrix), flatten(matrix_from_euler_angles(angles))): raise ValueError("This is not a proper rotation matrix.") super(Rotation, self).__init__(matrix=matrix) diff --git a/src/compas/geometry/transformations/transformations.py b/src/compas/geometry/transformations/transformations.py index fe40114e0a89..3a06358f87c7 100644 --- a/src/compas/geometry/transformations/transformations.py +++ b/src/compas/geometry/transformations/transformations.py @@ -248,9 +248,7 @@ def transform_points(points, T): >>> points_transformed = transform_points(points, T) """ - return dehomogenize( - multiply_matrices(homogenize(points, w=1.0), transpose_matrix(T)) - ) + return dehomogenize(multiply_matrices(homogenize(points, w=1.0), transpose_matrix(T))) def transform_vectors(vectors, T): @@ -275,9 +273,7 @@ def transform_vectors(vectors, T): >>> vectors_transformed = transform_vectors(vectors, T) """ - return dehomogenize( - multiply_matrices(homogenize(vectors, w=0.0), transpose_matrix(T)) - ) + return dehomogenize(multiply_matrices(homogenize(vectors, w=0.0), transpose_matrix(T))) def transform_frames(frames, T): @@ -304,9 +300,7 @@ def transform_frames(frames, T): """ points_and_vectors = homogenize_and_flatten_frames(frames) - return dehomogenize_and_unflatten_frames( - multiply_matrices(points_and_vectors, transpose_matrix(T)) - ) + return dehomogenize_and_unflatten_frames(multiply_matrices(points_and_vectors, transpose_matrix(T))) def world_to_local_coordinates(frame, xyz): diff --git a/src/compas/geometry/transformations/translation.py b/src/compas/geometry/transformations/translation.py index f47a21cc79a2..655115f68b04 100644 --- a/src/compas/geometry/transformations/translation.py +++ b/src/compas/geometry/transformations/translation.py @@ -69,9 +69,7 @@ def __init__(self, matrix=None, check=True): if matrix: _, _, _, translation, _ = decompose_matrix(matrix) if check: - if not allclose( - flatten(matrix), flatten(matrix_from_translation(translation)) - ): + if not allclose(flatten(matrix), flatten(matrix_from_translation(translation))): raise ValueError("This is not a proper translation matrix.") super(Translation, self).__init__(matrix=matrix) diff --git a/src/compas/geometry/triangulation/__init__.py b/src/compas/geometry/triangulation/__init__.py index a344543e7624..ce563753ccd9 100644 --- a/src/compas/geometry/triangulation/__init__.py +++ b/src/compas/geometry/triangulation/__init__.py @@ -64,9 +64,7 @@ def constrained_delaunay_triangulation(boundary, polylines=None, polygons=None): @pluggable(category="triangulation") -def conforming_delaunay_triangulation( - boundary, polylines=None, polygons=None, angle=None, area=None -): +def conforming_delaunay_triangulation(boundary, polylines=None, polygons=None, angle=None, area=None): """Construct a Conforming Delaunay triangulation of set of vertices, constrained to the specified segments. Parameters diff --git a/src/compas/geometry/triangulation/delaunay.py b/src/compas/geometry/triangulation/delaunay.py index f3a1c45cc4af..4b0f8eb71058 100644 --- a/src/compas/geometry/triangulation/delaunay.py +++ b/src/compas/geometry/triangulation/delaunay.py @@ -106,9 +106,7 @@ def super_triangle(coords, ccw=True): if is_point_in_triangle_xy(point, abc, True): # generate 3 new triangles (faces) and delete surrounding triangle - key, newtris = mesh.insert_vertex( - fkey, key=key, xyz=point, return_fkeys=True - ) + key, newtris = mesh.insert_vertex(fkey, key=key, xyz=point, return_fkeys=True) break while newtris: diff --git a/src/compas/geometry/trimesh/remesh.py b/src/compas/geometry/trimesh/remesh.py index f98b62b73486..635b7b8528d5 100644 --- a/src/compas/geometry/trimesh/remesh.py +++ b/src/compas/geometry/trimesh/remesh.py @@ -44,9 +44,7 @@ def trimesh_remesh(mesh, target_edge_length, number_of_iterations=10, do_project @pluggable(category="trimesh") -def trimesh_remesh_constrained( - mesh, target_edge_length, protected_edges, number_of_iterations=10, do_project=True -): +def trimesh_remesh_constrained(mesh, target_edge_length, protected_edges, number_of_iterations=10, do_project=True): """Constrained remeshing of a triangle mesh. Parameters diff --git a/src/compas/numerical/descent/descent_numpy.py b/src/compas/numerical/descent/descent_numpy.py index c27b9e38d0e7..937c81acf9c7 100644 --- a/src/compas/numerical/descent/descent_numpy.py +++ b/src/compas/numerical/descent/descent_numpy.py @@ -22,9 +22,7 @@ __all__ = ["descent_numpy"] -def descent_numpy( - x0, fn, iterations=1000, gtol=10 ** (-6), bounds=None, limit=0, args=() -): +def descent_numpy(x0, fn, iterations=1000, gtol=10 ** (-6), bounds=None, limit=0, args=()): """A gradient descent optimisation solver. Parameters @@ -106,10 +104,6 @@ def phi(x, mu, *args): if res < gtol: break - print( - "Iteration: {0} fopt: {1:.3g} gres: {2:.3g} step: {3}".format( - i, f1, res, a - ) - ) + print("Iteration: {0} fopt: {1:.3g} gres: {2:.3g} step: {3}".format(i, f1, res, a)) return f1, x0 diff --git a/src/compas/numerical/dr/dr.py b/src/compas/numerical/dr/dr.py index 43bbe9884895..c099385c14d9 100644 --- a/src/compas/numerical/dr/dr.py +++ b/src/compas/numerical/dr/dr.py @@ -201,10 +201,7 @@ def dr( # initial values # -------------------------------------------------------------------------- Q = [1.0 for _ in range(e)] - L = [ - sum((X[i][axis] - X[j][axis]) ** 2 for axis in (0, 1, 2)) ** 0.5 - for i, j in iter(edges) - ] + L = [sum((X[i][axis] - X[j][axis]) ** 2 for axis in (0, 1, 2)) ** 0.5 for i, j in iter(edges)] F = [q * l for q, l in zip(Q, L)] M = [sum(0.5 * dt**2 * Q[ij_e[(i, j)]] for j in i_nbrs[i]) for i in range(n)] V = [[0.0, 0.0, 0.0] for _ in range(n)] @@ -241,16 +238,10 @@ def a(t, V): k0 = [[dt * a0[i][axis] for axis in (0, 1, 2)] for i in range(n)] a1 = a( K[1][0] * dt, - [ - [V0[i][axis] + K[1][1] * k0[i][axis] for axis in (0, 1, 2)] - for i in range(n) - ], + [[V0[i][axis] + K[1][1] * k0[i][axis] for axis in (0, 1, 2)] for i in range(n)], ) k1 = [[dt * a1[i][axis] for axis in (0, 1, 2)] for i in range(n)] - return [ - [B[0] * k0[i][axis] + B[1] * k1[i][axis] for axis in (0, 1, 2)] - for i in range(n) - ] + return [[B[0] * k0[i][axis] + B[1] * k1[i][axis] for axis in (0, 1, 2)] for i in range(n)] if steps == 4: B = [1.0 / 6.0, 1.0 / 3.0, 1.0 / 3.0, 1.0 / 6.0] @@ -258,31 +249,19 @@ def a(t, V): k0 = [[dt * a0[i][axis] for axis in (0, 1, 2)] for i in range(n)] a1 = a( K[1][0] * dt, - [ - [V0[i][axis] + K[1][1] * k0[i][axis] for axis in (0, 1, 2)] - for i in range(n) - ], + [[V0[i][axis] + K[1][1] * k0[i][axis] for axis in (0, 1, 2)] for i in range(n)], ) k1 = [[dt * a1[i][axis] for axis in (0, 1, 2)] for i in range(n)] a2 = a( K[2][0] * dt, - [ - [ - V0[i][axis] + K[2][1] * k0[i][axis] + K[2][2] * k1[i][axis] - for axis in (0, 1, 2) - ] - for i in range(n) - ], + [[V0[i][axis] + K[2][1] * k0[i][axis] + K[2][2] * k1[i][axis] for axis in (0, 1, 2)] for i in range(n)], ) k2 = [[dt * a2[i][axis] for axis in (0, 1, 2)] for i in range(n)] a3 = a( K[3][0] * dt, [ [ - V0[i][axis] - + K[3][1] * k0[i][axis] - + K[3][2] * k1[i][axis] - + K[3][3] * k2[i][axis] + V0[i][axis] + K[3][1] * k0[i][axis] + K[3][2] * k1[i][axis] + K[3][3] * k2[i][axis] for axis in (0, 1, 2) ] for i in range(n) @@ -291,10 +270,7 @@ def a(t, V): k3 = [[dt * a3[i][axis] for axis in (0, 1, 2)] for i in range(n)] return [ [ - B[0] * k0[i][axis] - + B[1] * k1[i][axis] - + B[2] * k2[i][axis] - + B[3] * k3[i][axis] + B[0] * k0[i][axis] + B[1] * k1[i][axis] + B[2] * k2[i][axis] + B[3] * k3[i][axis] for axis in (0, 1, 2) ] for i in range(n) @@ -324,10 +300,7 @@ def a(t, V): dX[i] = [V[i][axis] * dt for axis in (0, 1, 2)] X[i] = [X0[i][axis] + dX[i][axis] for axis in (0, 1, 2)] - L = [ - sum((X[i][axis] - X[j][axis]) ** 2 for axis in (0, 1, 2)) ** 0.5 - for i, j in iter(edges) - ] + L = [sum((X[i][axis] - X[j][axis]) ** 2 for axis in (0, 1, 2)) ** 0.5 for i, j in iter(edges)] F = [q * l for q, l in zip(Q, L)] update_R() diff --git a/src/compas/numerical/ga/ga.py b/src/compas/numerical/ga/ga.py index a79cdd1e07b2..80b45de9aa40 100644 --- a/src/compas/numerical/ga/ga.py +++ b/src/compas/numerical/ga/ga.py @@ -299,12 +299,8 @@ def ga_optimize(self): for generation in range(start_gen_number, self.num_gen): - self.current_pop["decoded"] = self.decode_binary_pop( - self.current_pop["binary"] - ) - self.current_pop["scaled"] = self.scale_population( - self.current_pop["decoded"] - ) + self.current_pop["decoded"] = self.decode_binary_pop(self.current_pop["binary"]) + self.current_pop["scaled"] = self.scale_population(self.current_pop["decoded"]) if generation == 0: num = self.num_pop @@ -317,9 +313,7 @@ def ga_optimize(self): if self.num_pop_init and generation >= self.num_gen_init_pop: self.num_pop = self.num_pop_temp - self.current_pop = self.select_elite_pop( - self.current_pop, num_elite=self.num_pop - ) + self.current_pop = self.select_elite_pop(self.current_pop, num_elite=self.num_pop) self.write_out_file(generation) if self.min_fit: @@ -357,9 +351,7 @@ def evaluate_fitness(self, index): chromo = "".join(str(y) for x in self.current_pop["binary"][index] for y in x) fit = self.ind_fit_dict.setdefault(chromo, None) if not fit: - fit = self.fit_function( - self.current_pop["scaled"][index], *self.fargs, **self.fkwargs - ) + fit = self.fit_function(self.current_pop["scaled"][index], *self.fargs, **self.fkwargs) self.ind_fit_dict[chromo] = fit return fit @@ -407,9 +399,7 @@ def generate_random_bin_pop(self): random_bin_pop = [[[]] * self.num_var for i in range(self.num_pop)] for j in range(self.num_pop): for i in range(self.num_var): - random_bin_pop[j][i] = [ - random.randint(0, 1) for u in range(self.num_bin_dig[i]) - ] + random_bin_pop[j][i] = [random.randint(0, 1) for u in range(self.num_bin_dig[i])] return random_bin_pop def scale_population(self, decoded_pop): @@ -431,10 +421,7 @@ def scale_population(self, decoded_pop): for i in range(self.num_var): maxbin = float((2 ** self.num_bin_dig[i]) - 1) scaled_pop[j][i] = ( - self.boundaries[i][0] - + (self.boundaries[i][1] - self.boundaries[i][0]) - * decoded_pop[j][i] - / maxbin + self.boundaries[i][0] + (self.boundaries[i][1] - self.boundaries[i][0]) * decoded_pop[j][i] / maxbin ) return scaled_pop @@ -476,9 +463,7 @@ def select_elite_pop(self, pop, num_elite=None): if self.fit_type == "min": sorted_ind = self.get_sorting_indices(self.current_pop["fit_value"]) elif self.fit_type == "max": - sorted_ind = self.get_sorting_indices( - self.current_pop["fit_value"], reverse=True - ) + sorted_ind = self.get_sorting_indices(self.current_pop["fit_value"], reverse=True) else: raise ValueError('User selected fit_type is wrong. Use "min" or "max" only') if not num_elite: @@ -533,9 +518,9 @@ def create_mating_pool(self): chrom_b = [] for j in range(self.num_var): chrom_a += self.current_pop["binary"][self.mp_indices[i]][j] - chrom_b += self.current_pop["binary"][ - self.mp_indices[i + (int((self.num_pop - self.num_elite) / 2))] - ][j] + chrom_b += self.current_pop["binary"][self.mp_indices[i + (int((self.num_pop - self.num_elite) / 2))]][ + j + ] self.mating_pool_a.append(chrom_a) self.mating_pool_b.append(chrom_b) @@ -559,9 +544,7 @@ def simple_crossover(self): del c[: self.num_bin_dig[i]] del d[: self.num_bin_dig[i]] self.current_pop["binary"][j][i] = variable_a - self.current_pop["binary"][ - j + (int((self.num_pop - self.num_elite) / 2)) - ][i] = variable_b + self.current_pop["binary"][j + (int((self.num_pop - self.num_elite) / 2))][i] = variable_b def npoint_crossover(self): """Performs the n-point crossover operator. Individuals in ``GA.mating_pool_a`` are @@ -573,9 +556,7 @@ def npoint_crossover(self): for j in range(int((self.num_pop - self.num_elite) / 2)): a = self.mating_pool_a[j] b = self.mating_pool_b[j] - cross_list = sorted( - random.sample(range(1, self.total_bin_dig - 1), self.n_cross) - ) + cross_list = sorted(random.sample(range(1, self.total_bin_dig - 1), self.n_cross)) for cross in cross_list: c = a[:cross] + b[cross:] d = b[:cross] + a[cross:] @@ -585,9 +566,7 @@ def npoint_crossover(self): variable_a = a[: self.num_bin_dig[i]] variable_b = b[: self.num_bin_dig[i]] self.current_pop["binary"][j][i] = variable_a - self.current_pop["binary"][ - j + (int((self.num_pop - self.num_elite) / 2)) - ][i] = variable_b + self.current_pop["binary"][j + (int((self.num_pop - self.num_elite) / 2))][i] = variable_b def random_mutation(self): """This mutation operator replaces a gene from 0 to 1 or viceversa @@ -727,18 +706,10 @@ def add_elite_to_current(self): self.current_pop["scaled"] = [[[]] * self.num_var for i in range(self.num_pop)] self.current_pop["fit_value"] = [[]] * self.num_pop for i in range(self.num_elite): - self.current_pop["binary"][ - self.num_pop - self.num_elite + i - ] = self.elite_pop["binary"][i] - self.current_pop["decoded"][ - self.num_pop - self.num_elite + i - ] = self.elite_pop["decoded"][i] - self.current_pop["scaled"][ - self.num_pop - self.num_elite + i - ] = self.elite_pop["scaled"][i] - self.current_pop["fit_value"][ - self.num_pop - self.num_elite + i - ] = self.elite_pop["fit_value"][i] + self.current_pop["binary"][self.num_pop - self.num_elite + i] = self.elite_pop["binary"][i] + self.current_pop["decoded"][self.num_pop - self.num_elite + i] = self.elite_pop["decoded"][i] + self.current_pop["scaled"][self.num_pop - self.num_elite + i] = self.elite_pop["scaled"][i] + self.current_pop["fit_value"][self.num_pop - self.num_elite + i] = self.elite_pop["fit_value"][i] def make_ga_input_data(self): """Returns a dictionary containing the most relavant genetic data present in the instance @@ -845,10 +816,7 @@ def get_best_individual_index(self): """Saves the index of the best performing individual of the current population in ``GA.best_individual_index``. """ - fit_values = [ - self.current_pop["fit_value"][i] - for i in range(len(self.current_pop["fit_value"])) - ] + fit_values = [self.current_pop["fit_value"][i] for i in range(len(self.current_pop["fit_value"]))] if self.fit_type == "min": indices = self.get_sorting_indices(fit_values) elif self.fit_type == "max": diff --git a/src/compas/numerical/ga/moga.py b/src/compas/numerical/ga/moga.py index 2d2a894dbfe9..8453378e2f9d 100644 --- a/src/compas/numerical/ga/moga.py +++ b/src/compas/numerical/ga/moga.py @@ -323,10 +323,7 @@ def __str__(self): else self.get_sorting_indices(l, reverse=True)[0] for i, l in enumerate(fitl) ] - fit = [ - min(x) if self.fit_types[i] == "min" else max(x) - for i, x in enumerate(fitl) - ] + fit = [min(x) if self.fit_types[i] == "min" else max(x) for i, x in enumerate(fitl)] except Exception: best = None fit = None @@ -347,48 +344,32 @@ def moga_optimize(self): else: start_gen_number = 0 self.parent_pop["binary"] = self.generate_random_bin_pop() - self.parent_pop["decoded"] = self.decode_binary_pop( - self.parent_pop["binary"] - ) - self.parent_pop["scaled"] = self.scale_population( - self.parent_pop["decoded"] - ) + self.parent_pop["decoded"] = self.decode_binary_pop(self.parent_pop["binary"]) + self.parent_pop["scaled"] = self.scale_population(self.parent_pop["decoded"]) if self.fixed_start_pop: for i in range(self.fixed_start_pop["num_pop"]): self.parent_pop["binary"][i] = self.fixed_start_pop["binary"][i] self.parent_pop["decoded"][i] = self.fixed_start_pop["decoded"][i] self.parent_pop["scaled"][i] = self.fixed_start_pop["scaled"][i] - self.parent_pop["fit_values"] = [ - [[]] * self.num_fit_func for i in range(self.num_pop) - ] + self.parent_pop["fit_values"] = [[[]] * self.num_fit_func for i in range(self.num_pop)] for i in range(self.num_pop): for j in range(self.num_fit_func): fit_func = self.fit_functions[j] - self.parent_pop["fit_values"][i][j] = fit_func( - self.parent_pop["scaled"][i], **self.fkwargs - ) + self.parent_pop["fit_values"][i][j] = fit_func(self.parent_pop["scaled"][i], **self.fkwargs) self.current_pop["binary"] = self.generate_random_bin_pop() for generation in range(start_gen_number, self.num_gen): print("generation ", generation) - self.current_pop["decoded"] = self.decode_binary_pop( - self.current_pop["binary"] - ) - self.current_pop["scaled"] = self.scale_population( - self.current_pop["decoded"] - ) - self.current_pop["fit_values"] = [ - [[]] * self.num_fit_func for i in range(self.num_pop) - ] + self.current_pop["decoded"] = self.decode_binary_pop(self.current_pop["binary"]) + self.current_pop["scaled"] = self.scale_population(self.current_pop["decoded"]) + self.current_pop["fit_values"] = [[[]] * self.num_fit_func for i in range(self.num_pop)] for i in range(self.num_pop): for j in range(self.num_fit_func): fit_func = self.fit_functions[j] - self.current_pop["fit_values"][i][j] = fit_func( - self.current_pop["scaled"][i], **self.fkwargs - ) + self.current_pop["fit_values"][i][j] = fit_func(self.current_pop["scaled"][i], **self.fkwargs) self.combine_populations() self.non_dom_sort() @@ -413,9 +394,7 @@ def evaluate_fitness(self, index, fit_func): chromo = "".join(str(y) for x in self.current_pop["binary"][index] for y in x) fit = self.ind_fit_dict.setdefault(chromo, None) if not fit: - fit = fit_func( - self.current_pop["scaled"][index], *self.fargs, **self.fkwargs - ) + fit = fit_func(self.current_pop["scaled"][index], *self.fargs, **self.fkwargs) self.ind_fit_dict[chromo] = fit return fit @@ -478,9 +457,7 @@ def generate_random_bin_pop(self): random_bin_pop = [[[]] * self.num_var for i in range(self.num_pop)] for j in range(self.num_pop): for i in range(self.num_var): - random_bin_pop[j][i] = [ - random.randint(0, 1) for u in range(self.num_bin_dig[i]) - ] + random_bin_pop[j][i] = [random.randint(0, 1) for u in range(self.num_bin_dig[i])] return random_bin_pop def decode_binary_pop(self, bin_pop): @@ -538,39 +515,23 @@ def combine_populations(self): to create a 2 x ``MOGA.num_pop`` long current population. """ - self.combined_pop["binary"] = [ - [[]] * self.num_var for i in range(self.num_pop * 2) - ] - self.combined_pop["decoded"] = [ - [[]] * self.num_var for i in range(self.num_pop * 2) - ] - self.combined_pop["scaled"] = [ - [[]] * self.num_var for i in range(self.num_pop * 2) - ] - self.combined_pop["fit_values"] = [ - [[]] * self.num_fit_func for i in range(self.num_pop * 2) - ] + self.combined_pop["binary"] = [[[]] * self.num_var for i in range(self.num_pop * 2)] + self.combined_pop["decoded"] = [[[]] * self.num_var for i in range(self.num_pop * 2)] + self.combined_pop["scaled"] = [[[]] * self.num_var for i in range(self.num_pop * 2)] + self.combined_pop["fit_values"] = [[[]] * self.num_fit_func for i in range(self.num_pop * 2)] for i in range(self.num_pop): self.combined_pop["binary"][i] = self.parent_pop["binary"][i] - self.combined_pop["binary"][i + self.num_pop] = self.current_pop["binary"][ - i - ] + self.combined_pop["binary"][i + self.num_pop] = self.current_pop["binary"][i] self.combined_pop["decoded"][i] = self.parent_pop["decoded"][i] - self.combined_pop["decoded"][i + self.num_pop] = self.current_pop[ - "decoded" - ][i] + self.combined_pop["decoded"][i + self.num_pop] = self.current_pop["decoded"][i] self.combined_pop["scaled"][i] = self.parent_pop["scaled"][i] - self.combined_pop["scaled"][i + self.num_pop] = self.current_pop["scaled"][ - i - ] + self.combined_pop["scaled"][i + self.num_pop] = self.current_pop["scaled"][i] self.combined_pop["fit_values"][i] = self.parent_pop["fit_values"][i] - self.combined_pop["fit_values"][i + self.num_pop] = self.current_pop[ - "fit_values" - ][i] + self.combined_pop["fit_values"][i + self.num_pop] = self.current_pop["fit_values"][i] def non_dom_sort(self): """This function performs the non dominated sorting operator of the NSGA-II @@ -593,26 +554,14 @@ def non_dom_sort(self): count_inf = 0 for j in range(self.num_fit_func): if self.fit_types[j] == "min": - if ( - self.combined_pop["fit_values"][i][j] - < self.combined_pop["fit_values"][k][j] - ): + if self.combined_pop["fit_values"][i][j] < self.combined_pop["fit_values"][k][j]: count_sup += 1 - elif ( - self.combined_pop["fit_values"][i][j] - > self.combined_pop["fit_values"][k][j] - ): + elif self.combined_pop["fit_values"][i][j] > self.combined_pop["fit_values"][k][j]: count_inf += 1 elif self.fit_types[j] == "max": - if ( - self.combined_pop["fit_values"][i][j] - > self.combined_pop["fit_values"][k][j] - ): + if self.combined_pop["fit_values"][i][j] > self.combined_pop["fit_values"][k][j]: count_sup += 1 - elif ( - self.combined_pop["fit_values"][i][j] - < self.combined_pop["fit_values"][k][j] - ): + elif self.combined_pop["fit_values"][i][j] < self.combined_pop["fit_values"][k][j]: count_inf += 1 if count_sup < 1 and count_inf >= 1: @@ -640,10 +589,7 @@ def non_dom_sort(self): for k in range(a, b): for h in range(len(self.dominating_individuals)): - if ( - self.pareto_front_individuals[k] - == self.dominating_individuals[h] - ): + if self.pareto_front_individuals[k] == self.dominating_individuals[h]: if self.domination_count[self.dominated_set[h]] >= 0: self.domination_count[self.dominated_set[h]] = ( self.domination_count[self.dominated_set[h]] - 1 @@ -669,34 +615,23 @@ def calculate_crowding_distance(self): self.crowding_distance = [0] * self.num_i_pareto_front for i in range(self.num_fit_func): - ind_fit_values_list = [ - fit_val[i] for fit_val in self.combined_pop["fit_values"] - ] + ind_fit_values_list = [fit_val[i] for fit_val in self.combined_pop["fit_values"]] delta = max(ind_fit_values_list) - min(ind_fit_values_list) for k in range(self.num_i_pareto_front): - self.pf_values[k] = self.combined_pop["fit_values"][ - self.i_pareto_front[k] - ][i] + self.pf_values[k] = self.combined_pop["fit_values"][self.i_pareto_front[k]][i] if self.fit_types[i] == "max": - self.sorted_indices = self.get_sorting_indices( - self.pf_values, reverse=True - ) + self.sorted_indices = self.get_sorting_indices(self.pf_values, reverse=True) else: - self.sorted_indices = self.get_sorting_indices( - self.pf_values, reverse=False - ) + self.sorted_indices = self.get_sorting_indices(self.pf_values, reverse=False) self.crowding_distance[self.sorted_indices[0]] = float("inf") - self.crowding_distance[ - self.sorted_indices[self.num_i_pareto_front - 1] - ] = float("inf") + self.crowding_distance[self.sorted_indices[self.num_i_pareto_front - 1]] = float("inf") for j in range(1, self.num_i_pareto_front - 1): formula = ( - self.pf_values[self.sorted_indices[j + 1]] - - self.pf_values[self.sorted_indices[j - 1]] + self.pf_values[self.sorted_indices[j + 1]] - self.pf_values[self.sorted_indices[j - 1]] ) / delta self.crowding_distance[self.sorted_indices[j]] += formula @@ -735,9 +670,7 @@ def crowding_distance_sorting(self): for i in range(self.num_i_pareto_front): cd_sorted_last_pf_index.append(self.i_pareto_front[sorting_index[i]]) - self.new_pop_cd[ - len(self.new_pop_cd) - self.num_i_pareto_front : len(self.new_pop_cd) - ] = sorted_last_pf_cd[:] + self.new_pop_cd[len(self.new_pop_cd) - self.num_i_pareto_front : len(self.new_pop_cd)] = sorted_last_pf_cd[:] self.pareto_front_individuals[ len(self.new_pop_cd) - self.num_i_pareto_front : len(self.new_pop_cd) ] = cd_sorted_last_pf_index[:] @@ -751,12 +684,8 @@ def parent_reseting(self): self.parent_combined_dict = {} for i in range(self.num_pop): - self.parent_pop["binary"][i] = self.combined_pop["binary"][ - self.pareto_front_individuals[i] - ] - self.parent_pop["fit_values"][i] = self.combined_pop["fit_values"][ - self.pareto_front_individuals[i] - ] + self.parent_pop["binary"][i] = self.combined_pop["binary"][self.pareto_front_individuals[i]] + self.parent_pop["fit_values"][i] = self.combined_pop["fit_values"][self.pareto_front_individuals[i]] self.parent_combined_dict[i] = self.pareto_front_individuals[i] self.parent_pop["decoded"] = self.decode_binary_pop(self.parent_pop["binary"]) @@ -774,9 +703,7 @@ def nsga_tournament(self): temp_pf_individuals_a = [] temp_pf_individuals_a[:] = self.pareto_front_individuals[0 : self.num_pop] - temp_pf_individuals_b = random.sample( - temp_pf_individuals_a, len(temp_pf_individuals_a) - ) + temp_pf_individuals_b = random.sample(temp_pf_individuals_a, len(temp_pf_individuals_a)) pf_individuals_2 = [] indices = [] @@ -784,21 +711,16 @@ def nsga_tournament(self): cd_a = self.new_pop_cd for i in range(self.num_pop): - while ( - temp_pf_individuals_a[i] == temp_pf_individuals_b[0] - and i != self.num_pop - 1 - ): - temp_pf_individuals_b = random.sample( - temp_pf_individuals_b, len(temp_pf_individuals_b) - ) + while temp_pf_individuals_a[i] == temp_pf_individuals_b[0] and i != self.num_pop - 1: + temp_pf_individuals_b = random.sample(temp_pf_individuals_b, len(temp_pf_individuals_b)) pf_individuals_2.append(temp_pf_individuals_b[0]) del temp_pf_individuals_b[0] for j in range(len(self.pareto_front_indices) - 1): - pf_indices_a[ - self.pareto_front_indices[j] : self.pareto_front_indices[j + 1] - ] = [j] * (self.pareto_front_indices[j + 1] - self.pareto_front_indices[j]) + pf_indices_a[self.pareto_front_indices[j] : self.pareto_front_indices[j + 1]] = [j] * ( + self.pareto_front_indices[j + 1] - self.pareto_front_indices[j] + ) for i in range(len(pf_individuals_2)): for u in range(len(temp_pf_individuals_a)): @@ -841,9 +763,7 @@ def create_mating_pool(self): chrom_b = [] for j in range(self.num_var): chrom_a += self.combined_pop["binary"][self.mp_individual_indices[i]][j] - chrom_b += self.combined_pop["binary"][ - self.mp_individual_indices[i + int(self.num_pop / 2)] - ][j] + chrom_b += self.combined_pop["binary"][self.mp_individual_indices[i + int(self.num_pop / 2)]][j] self.mating_pool_a.append(chrom_a) self.mating_pool_b.append(chrom_b) @@ -901,9 +821,7 @@ def get_pop_from_pf_file(self): "fit_values": [], "pf": [], } - filename = ( - "generation " + "%03d" % self.start_from_gen + "_pareto_front" + ".pareto" - ) + filename = "generation " + "%03d" % self.start_from_gen + "_pareto_front" + ".pareto" filename = self.output_path + filename pf_file = open(filename, "r") lines = pf_file.readlines() @@ -1032,9 +950,7 @@ def make_pop_pf_dict(self): """ pf_dict = {} for j in range(len(self.pareto_front_indices) - 1): - pf_ind = self.pareto_front_individuals[ - self.pareto_front_indices[j] : self.pareto_front_indices[j + 1] - ] + pf_ind = self.pareto_front_individuals[self.pareto_front_indices[j] : self.pareto_front_indices[j + 1]] for i in range(self.num_pop): index = self.parent_combined_dict[i] if index in pf_ind: @@ -1141,12 +1057,8 @@ def create_fixed_start_pop(self, scaled=None, binary=None): for i in range(self.fixed_start_pop["num_pop"]): self.fixed_start_pop["scaled"][i] = scaled[i] - self.fixed_start_pop["decoded"] = self.unscale_pop( - self.fixed_start_pop["scaled"] - ) - self.fixed_start_pop["binary"] = self.code_decoded( - self.fixed_start_pop["decoded"] - ) + self.fixed_start_pop["decoded"] = self.unscale_pop(self.fixed_start_pop["scaled"]) + self.fixed_start_pop["binary"] = self.code_decoded(self.fixed_start_pop["decoded"]) if binary: self.fixed_start_pop["num_pop"] = len(binary) @@ -1154,9 +1066,5 @@ def create_fixed_start_pop(self, scaled=None, binary=None): for i in range(self.fixed_start_pop["num_pop"]): self.fixed_start_pop["binary"][i] = binary[i] - self.fixed_start_pop["decoded"] = self.decode_binary_pop( - self.fixed_start_pop["binary"] - ) - self.fixed_start_pop["scaled"] = self.scale_population( - self.fixed_start_pop["decoded"] - ) + self.fixed_start_pop["decoded"] = self.decode_binary_pop(self.fixed_start_pop["binary"]) + self.fixed_start_pop["scaled"] = self.scale_population(self.fixed_start_pop["decoded"]) diff --git a/src/compas/numerical/isolines/isolines_numpy.py b/src/compas/numerical/isolines/isolines_numpy.py index 5167979f7110..12f002da9607 100644 --- a/src/compas/numerical/isolines/isolines_numpy.py +++ b/src/compas/numerical/isolines/isolines_numpy.py @@ -94,9 +94,7 @@ def scalarfield_contours_numpy(xy, s, levels=50, density=100): s = asarray(s) x = xy[:, 0] y = xy[:, 1] - X, Y = meshgrid( - linspace(amin(x), amax(x), 2 * density), linspace(amin(y), amax(y), 2 * density) - ) + X, Y = meshgrid(linspace(amin(x), amax(x), 2 * density), linspace(amin(y), amax(y), 2 * density)) S = griddata((x, y), s, (X, Y), method="cubic") fig = plt.figure() diff --git a/src/compas/numerical/matrices.py b/src/compas/numerical/matrices.py index f35cddff2b63..1b93e4deed22 100644 --- a/src/compas/numerical/matrices.py +++ b/src/compas/numerical/matrices.py @@ -83,17 +83,9 @@ def face_matrix(face_vertices, rtype="array", normalize=False): """ if normalize: - f = array( - [ - (i, j, 1.0 / len(vertices)) - for i, vertices in enumerate(face_vertices) - for j in vertices - ] - ) + f = array([(i, j, 1.0 / len(vertices)) for i, vertices in enumerate(face_vertices) for j in vertices]) else: - f = array( - [(i, j, 1.0) for i, vertices in enumerate(face_vertices) for j in vertices] - ) + f = array([(i, j, 1.0) for i, vertices in enumerate(face_vertices) for j in vertices]) F = coo_matrix((f[:, 2], (f[:, 0].astype(int), f[:, 1].astype(int)))) return _return_matrix(F, rtype) diff --git a/src/compas/numerical/topop/topop_numpy.py b/src/compas/numerical/topop/topop_numpy.py index 8274758805be..0a63adbd3b03 100644 --- a/src/compas/numerical/topop/topop_numpy.py +++ b/src/compas/numerical/topop/topop_numpy.py @@ -32,9 +32,7 @@ __all__ = ["topop_numpy"] -def topop_numpy( - nelx, nely, loads, supports, volfrac=0.5, penal=3, rmin=1.5, callback=None -): +def topop_numpy(nelx, nely, loads, supports, volfrac=0.5, penal=3, rmin=1.5, callback=None): """Topology optimisation in 2D. Parameters @@ -80,18 +78,10 @@ def topop_numpy( E = 1.0 Emin = 10 ** (-10) - A11 = array( - [[12, +3, -6, -3], [+3, 12, +3, +0], [-6, +3, 12, -3], [-3, +0, -3, 12]] - ) - A12 = array( - [[-6, -3, +0, +3], [-3, -6, -3, -6], [+0, -3, -6, +3], [+3, -6, +3, -6]] - ) - B11 = array( - [[-4, +3, -2, +9], [+3, -4, -9, +4], [-2, -9, -4, -3], [+9, +4, -3, -4]] - ) - B12 = array( - [[+2, -3, +4, -9], [-3, +2, +9, -2], [+4, +9, +2, +3], [-9, -2, +3, +2]] - ) + A11 = array([[12, +3, -6, -3], [+3, 12, +3, +0], [-6, +3, 12, -3], [-3, +0, -3, 12]]) + A12 = array([[-6, -3, +0, +3], [-3, -6, -3, -6], [+0, -3, -6, +3], [+3, -6, +3, -6]]) + B11 = array([[-4, +3, -2, +9], [+3, -4, -9, +4], [-2, -9, -4, -3], [+9, +4, -3, -4]]) + B12 = array([[+2, -3, +4, -9], [-3, +2, +9, -2], [+4, +9, +2, +3], [-9, -2, +3, +2]]) A21 = A12.transpose() B21 = B12.transpose() A = vstack([hstack([A11, A12]), hstack([A21, A11])]) @@ -191,9 +181,7 @@ def topop_numpy( xrav = ravel(xP, order="F").transpose() sK = reshape(Ker * (Emin + xrav**penal * (E - Emin)), (64 * ne), order="F") - K = coo_matrix( - (sK, (asarray(iK, dtype=int64), asarray(jK, dtype=int64))) - ).tocsr() + K = coo_matrix((sK, (asarray(iK, dtype=int64), asarray(jK, dtype=int64)))).tocsr() Kind = (K.tocsc()[:, free]).tocsr()[free, :] U[free] = spsolve(Kind, Find)[:, newaxis] @@ -207,9 +195,7 @@ def topop_numpy( c = sum(sum((Emin + xP**penal * (E - Emin)) * ce)) dc = -penal * (E - Emin) * xP ** (penal - 1) * ce xdc = squeeze(H.dot(ravel(x * dc, order="F")[:, newaxis])) - dc = reshape( - xdc / Hs / maximum(nones, ravel(x, order="F")), (nely, nelx), order="F" - ) + dc = reshape(xdc / Hs / maximum(nones, ravel(x, order="F")), (nely, nelx), order="F") # Lagrange mulipliers diff --git a/src/compas/plugins.py b/src/compas/plugins.py index 77f238c81283..f4978cf4e060 100644 --- a/src/compas/plugins.py +++ b/src/compas/plugins.py @@ -183,11 +183,7 @@ def load_plugins(self): modules_to_inspect[module_name] = module else: if self.DEBUG: - print( - "Error importing module {}, skipping entire package.".format( - module_name - ) - ) + print("Error importing module {}, skipping entire package.".format(module_name)) continue if "__all_plugins__" in dir(module): @@ -197,16 +193,10 @@ def load_plugins(self): modules_to_inspect[plugin_module_name] = plugin_module else: if self.DEBUG: - print( - "Error importing plugin {}, skipping.".format( - plugin_module_name - ) - ) + print("Error importing plugin {}, skipping.".format(plugin_module_name)) if self.DEBUG: - print( - "Will inspect modules: {}".format(list(modules_to_inspect.keys())) - ) + print("Will inspect modules: {}".format(list(modules_to_inspect.keys()))) for plugin_module in modules_to_inspect.values(): count += self.register_module(plugin_module) @@ -237,9 +227,7 @@ def register_module(self, plugin_module): if plugin_opts is not None: plugin_impl = PluginImpl(plugin_module, plugin_method, plugin_opts) - plugins_list = self._registry.setdefault( - plugin_opts["extension_point_url"], [] - ) + plugins_list = self._registry.setdefault(plugin_opts["extension_point_url"], []) plugins_list.append(plugin_impl) plugins_list.sort(key=lambda p: p.key) @@ -307,9 +295,7 @@ def pluggable( def pluggable_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): - extension_point_url = _get_extension_point_url_from_method( - domain, category, func - ) + extension_point_url = _get_extension_point_url_from_method(domain, category, func) # Select first matching plugin if selector == "first_match": @@ -331,9 +317,7 @@ def wrapper(*args, **kwargs): return results else: - raise ValueError( - "Unexpected selector type. Must be either: first_match or collect_all" - ) + raise ValueError("Unexpected selector type. Must be either: first_match or collect_all") return wrapper @@ -389,9 +373,7 @@ def plugin( def setattr_hookspec_opts(func): if tryfirst and trylast: - raise ValueError( - "You cannot set a plugin to try first and last at the same time." - ) + raise ValueError("You cannot set a plugin to try first and last at the same time.") name = pluggable_name or getattr(func, "__name__", None) extension_point_url = _get_extension_point_url_from_name(domain, category, name) @@ -482,29 +464,18 @@ def verify_requirement(self, requirement): def is_plugin_selectable(self, plugin): if plugin.opts["requires"]: - importable_requirements = ( - self.verify_requirement(requirement) - for requirement in plugin.opts["requires"] - ) + importable_requirements = (self.verify_requirement(requirement) for requirement in plugin.opts["requires"]) if not all(importable_requirements): if self.manager.DEBUG: - print( - "Requirements not satisfied. Plugin will not be used: {}".format( - plugin.id - ) - ) + print("Requirements not satisfied. Plugin will not be used: {}".format(plugin.id)) return False return True def select_plugin(self, extension_point_url): if self.manager.DEBUG: - print( - "Extension Point URL {} invoked. Will select a matching plugin".format( - extension_point_url - ) - ) + print("Extension Point URL {} invoked. Will select a matching plugin".format(extension_point_url)) plugins = self.manager.registry.get(extension_point_url) or [] for plugin in plugins: @@ -512,17 +483,11 @@ def select_plugin(self, extension_point_url): return plugin # Nothing found, raise - raise PluginNotInstalledError( - "Plugin not found for extension point URL: {}".format(extension_point_url) - ) + raise PluginNotInstalledError("Plugin not found for extension point URL: {}".format(extension_point_url)) def collect_plugins(self, extension_point_url): if self.manager.DEBUG: - print( - "Extension Point URL {} invoked. Will select a matching plugin".format( - extension_point_url - ) - ) + print("Extension Point URL {} invoked. Will select a matching plugin".format(extension_point_url)) plugins = self.manager.registry.get(extension_point_url) or [] return [plugin for plugin in plugins if self.is_plugin_selectable(plugin)] @@ -532,9 +497,7 @@ def ensure_implementations(cls): for name, value in inspect.getmembers(cls): if inspect.isfunction(value) or inspect.ismethod(value): if hasattr(value, "__isabstractmethod__"): - raise IncompletePluginImplError( - "Abstract method not implemented: {}".format(value) - ) + raise IncompletePluginImplError("Abstract method not implemented: {}".format(value)) plugin_manager = PluginManager() diff --git a/src/compas/robots/configuration.py b/src/compas/robots/configuration.py index cabb5305b64d..4f100d9f229f 100644 --- a/src/compas/robots/configuration.py +++ b/src/compas/robots/configuration.py @@ -51,9 +51,7 @@ def __init__(self, *args, **kwargs): def __setitem__(self, key, value): # included to obstruct the all too common `l[1:1] = range(100)`-type usage value_length = len(value) if hasattr(value, "__len__") else 1 - slice_length = ( - len(range(*key.indices(self.__len__()))) if isinstance(key, slice) else 1 - ) + slice_length = len(range(*key.indices(self.__len__()))) if isinstance(key, slice) else 1 if slice_length != value_length: raise TypeError("Cannot change length of FixedLengthList") if self.validator: @@ -153,9 +151,7 @@ def __init__(self, joint_values=None, joint_types=None, joint_names=None, **kwar joint_values = FixedLengthList(joint_values or []) joint_types = FixedLengthList(joint_types or []) - joint_names = FixedLengthList( - joint_names or [], validator=joint_names_validator - ) + joint_names = FixedLengthList(joint_names or [], validator=joint_names_validator) if len(joint_values) != len(joint_types): raise ValueError( @@ -232,21 +228,15 @@ def joint_names(self): def joint_names(self, names): if names and len(self._joint_values) != len(names): raise ValueError( - "joint_types must have length {}, object of length {} given".format( - len(self._joint_values), len(names) - ) + "joint_types must have length {}, object of length {} given".format(len(self._joint_values), len(names)) ) self._joint_names = FixedLengthList(names, validator=joint_names_validator) def __str__(self): """Return a human-readable string representation of the instance.""" - v_str = ( - "(" + ", ".join(["%." + self._precision] * len(self.joint_values)) + ")" - ) % tuple(self.joint_values) + v_str = ("(" + ", ".join(["%." + self._precision] * len(self.joint_values)) + ")") % tuple(self.joint_values) if len(self.joint_names): - return "Configuration({}, {}, {})".format( - v_str, tuple(self.joint_types), tuple(self.joint_names) - ) + return "Configuration({}, {}, {})".format(v_str, tuple(self.joint_types), tuple(self.joint_names)) else: return "Configuration({}, {})".format(v_str, tuple(self.joint_types)) @@ -326,9 +316,7 @@ def from_revolute_values(cls, values, joint_names=None): ) @classmethod - def from_prismatic_and_revolute_values( - cls, prismatic_values, revolute_values, joint_names=None - ): + def from_prismatic_and_revolute_values(cls, prismatic_values, revolute_values, joint_names=None): """Construct a configuration from prismatic and revolute joint values. Parameters @@ -350,9 +338,7 @@ def from_prismatic_and_revolute_values( revolute_values = list(revolute_values) joint_names = list(joint_names or []) values = prismatic_values + revolute_values - joint_types = [_JOINT_PRISMATIC] * len(prismatic_values) + [ - _JOINT_REVOLUTE - ] * len(revolute_values) + joint_types = [_JOINT_PRISMATIC] * len(prismatic_values) + [_JOINT_REVOLUTE] * len(revolute_values) return cls.from_data( { "joint_values": values, @@ -378,12 +364,8 @@ def data(self): @data.setter def data(self, data): - self._joint_values = FixedLengthList( - data.get("joint_values") or data.get("values") or [] - ) - self._joint_types = FixedLengthList( - data.get("joint_types") or data.get("types") or [] - ) + self._joint_values = FixedLengthList(data.get("joint_values") or data.get("values") or []) + self._joint_types = FixedLengthList(data.get("joint_types") or data.get("types") or []) self._joint_names = FixedLengthList(data.get("joint_names") or []) @property @@ -392,20 +374,12 @@ def prismatic_values(self): E.g. positions on the external axis system. """ - return [ - v - for i, v in enumerate(self.joint_values) - if self.joint_types[i] == _JOINT_PRISMATIC - ] + return [v for i, v in enumerate(self.joint_values) if self.joint_types[i] == _JOINT_PRISMATIC] @property def revolute_values(self): """list of float : Revolute joint values in radians.""" - return [ - v - for i, v in enumerate(self.joint_values) - if self.joint_types[i] == _JOINT_REVOLUTE - ] + return [v for i, v in enumerate(self.joint_values) if self.joint_types[i] == _JOINT_REVOLUTE] def scale(self, scale_factor): """Scales the joint positions of the current configuration. @@ -485,15 +459,11 @@ def iter_differences(self, other): if set(self.joint_names) != set(other.joint_names): raise ValueError("Configurations have different joint names.") other_value_by_name = dict(zip(other.joint_names, other.joint_values)) - sorted_other_values = [ - other_value_by_name[name] for name in self.joint_names - ] + sorted_other_values = [other_value_by_name[name] for name in self.joint_names] value_pairs = zip(self.joint_values, sorted_other_values) else: if len(self.joint_values) != len(other.joint_values): - raise ValueError( - "Can't compare configurations with different lengths of joint_values." - ) + raise ValueError("Can't compare configurations with different lengths of joint_values.") value_pairs = zip(self.joint_values, other.joint_values) for i, (v1, v2) in enumerate(value_pairs): diff --git a/src/compas/robots/model/geometry.py b/src/compas/robots/model/geometry.py index 3e401f809cb3..c2daa2a1291c 100644 --- a/src/compas/robots/model/geometry.py +++ b/src/compas/robots/model/geometry.py @@ -181,9 +181,7 @@ def data(self, data): self.filename = data["filename"] self.scale = data["scale"] self.attr = _attr_from_data(data["attr"]) if "attr" in data else {} - self.meshes = ( - [Mesh.from_data(md) for md in data["meshes"]] if "meshes" in data else [] - ) + self.meshes = [Mesh.from_data(md) for md in data["meshes"]] if "meshes" in data else [] @classmethod def from_data(cls, data): @@ -415,9 +413,7 @@ class Geometry(Data): """ - def __init__( - self, box=None, cylinder=None, sphere=None, capsule=None, mesh=None, **kwargs - ): + def __init__(self, box=None, cylinder=None, sphere=None, capsule=None, mesh=None, **kwargs): super(Geometry, self).__init__() self.shape = box or cylinder or sphere or capsule or mesh self.attr = kwargs diff --git a/src/compas/robots/model/joint.py b/src/compas/robots/model/joint.py index 9a47a0432d32..267c020c3bff 100644 --- a/src/compas/robots/model/joint.py +++ b/src/compas/robots/model/joint.py @@ -264,9 +264,7 @@ def calculate_position(self, mimicked_joint_position): class SafetyController(Data): """Safety controller properties.""" - def __init__( - self, k_velocity, k_position=0.0, soft_lower_limit=0.0, soft_upper_limit=0.0 - ): + def __init__(self, k_velocity, k_position=0.0, soft_lower_limit=0.0, soft_upper_limit=0.0): super(SafetyController, self).__init__() self.k_velocity = float(k_velocity) self.k_position = float(k_position) @@ -564,9 +562,7 @@ def data(self): "calibration": self.calibration.data if self.calibration else None, "dynamics": self.dynamics.data if self.dynamics else None, "limit": self.limit.data if self.limit else None, - "safety_controller": self.safety_controller.data - if self.safety_controller - else None, + "safety_controller": self.safety_controller.data if self.safety_controller else None, "mimic": self.mimic.data if self.mimic else None, "attr": _attr_to_data(self.attr), "position": self.position, @@ -580,17 +576,11 @@ def data(self, data): self.child = ChildLink.from_data(data["child"]) self.origin = Frame.from_data(data["origin"]) if data["origin"] else None self.axis = Axis.from_data(data["axis"]) if data["axis"] else None - self.calibration = ( - Calibration.from_data(data["calibration"]) if data["calibration"] else None - ) - self.dynamics = ( - Dynamics.from_data(data["dynamics"]) if data["dynamics"] else None - ) + self.calibration = Calibration.from_data(data["calibration"]) if data["calibration"] else None + self.dynamics = Dynamics.from_data(data["dynamics"]) if data["dynamics"] else None self.limit = Limit.from_data(data["limit"]) if data["limit"] else None self.safety_controller = ( - SafetyController.from_data(data["safety_controller"]) - if data["safety_controller"] - else None + SafetyController.from_data(data["safety_controller"]) if data["safety_controller"] else None ) self.mimic = Mimic.from_data(data["mimic"]) if data["mimic"] else None self.attr = _attr_from_data(data["attr"]) @@ -684,9 +674,7 @@ def calculate_continuous_transformation(self, position): Transformation of type rotation for the continuous joint. """ - return Rotation.from_axis_and_angle( - self.current_axis.vector, position, self.current_origin.point - ) + return Rotation.from_axis_and_angle(self.current_axis.vector, position, self.current_origin.point) def calculate_prismatic_transformation(self, position): """Returns a transformation of a prismatic joint. diff --git a/src/compas/robots/model/link.py b/src/compas/robots/model/link.py index b6559e8494a9..2017a131a275 100644 --- a/src/compas/robots/model/link.py +++ b/src/compas/robots/model/link.py @@ -223,12 +223,8 @@ def data(self): "name": self.name, "material": self.material.data if self.material else None, "attr": _attr_to_data(self.attr), - "init_transformation": self.init_transformation.data - if self.init_transformation - else None, - "current_transformation": self.current_transformation.data - if self.current_transformation - else None, + "init_transformation": self.init_transformation.data if self.init_transformation else None, + "current_transformation": self.current_transformation.data if self.current_transformation else None, } @data.setter @@ -236,19 +232,13 @@ def data(self, data): self.geometry = Geometry.from_data(data["geometry"]) self.origin = Frame.from_data(data["origin"]) if data["origin"] else None self.name = data["name"] - self.material = ( - Material.from_data(data["material"]) if data["material"] else None - ) + self.material = Material.from_data(data["material"]) if data["material"] else None self.attr = _attr_from_data(data["attr"]) self.init_transformation = ( - Transformation.from_data(data["init_transformation"]) - if data["init_transformation"] - else None + Transformation.from_data(data["init_transformation"]) if data["init_transformation"] else None ) self.current_transformation = ( - Transformation.from_data(data["current_transformation"]) - if data["current_transformation"] - else None + Transformation.from_data(data["current_transformation"]) if data["current_transformation"] else None ) @classmethod @@ -351,12 +341,8 @@ def data(self): "origin": self.origin.data if self.origin else None, "name": self.name, "attr": _attr_to_data(self.attr), - "init_transformation": self.init_transformation.data - if self.init_transformation - else None, - "current_transformation": self.current_transformation.data - if self.current_transformation - else None, + "init_transformation": self.init_transformation.data if self.init_transformation else None, + "current_transformation": self.current_transformation.data if self.current_transformation else None, } @data.setter @@ -366,14 +352,10 @@ def data(self, data): self.name = data["name"] self.attr = _attr_from_data(data["attr"]) self.init_transformation = ( - Transformation.from_data(data["init_transformation"]) - if data["init_transformation"] - else None + Transformation.from_data(data["init_transformation"]) if data["init_transformation"] else None ) self.current_transformation = ( - Transformation.from_data(data["current_transformation"]) - if data["current_transformation"] - else None + Transformation.from_data(data["current_transformation"]) if data["current_transformation"] else None ) @classmethod @@ -429,9 +411,7 @@ class Link(Data): """ - def __init__( - self, name, type=None, visual=(), collision=(), inertial=None, **kwargs - ): + def __init__(self, name, type=None, visual=(), collision=(), inertial=None, **kwargs): super(Link, self).__init__() self.name = name self.type = type @@ -470,9 +450,7 @@ def data(self, data): self.type = data["type"] self.visual = [Visual.from_data(d) for d in data["visual"]] self.collision = [Collision.from_data(d) for d in data["collision"]] - self.inertial = ( - Inertial.from_data(data["inertial"]) if data["inertial"] else None - ) + self.inertial = Inertial.from_data(data["inertial"]) if data["inertial"] else None self.attr = _attr_from_data(data["attr"]) self.joints = [Joint.from_data(d) for d in data["joints"]] @@ -498,9 +476,7 @@ def from_data(cls, data): "robot/link/collision/origin", proxy_type=FrameProxy, ) -URDFParser.install_parser( - Geometry, "robot/link/visual/geometry", "robot/link/collision/geometry" -) +URDFParser.install_parser(Geometry, "robot/link/visual/geometry", "robot/link/collision/geometry") URDFParser.install_parser( MeshDescriptor, "robot/link/visual/geometry/mesh", diff --git a/src/compas/robots/model/robot.py b/src/compas/robots/model/robot.py index c96816af9918..aea4a8efbc9c 100644 --- a/src/compas/robots/model/robot.py +++ b/src/compas/robots/model/robot.py @@ -651,10 +651,7 @@ def random_configuration(self): values = [] for joint in configurable_joints: if joint.limit: - values.append( - joint.limit.lower - + (joint.limit.upper - joint.limit.lower) * random.random() - ) + values.append(joint.limit.lower + (joint.limit.upper - joint.limit.lower) * random.random()) else: values.append(0) joint_names = self.get_configurable_joint_names() @@ -711,9 +708,7 @@ def load_geometry(self, *resource_loaders, **kwargs): break if not shape.meshes: - raise Exception( - "Unable to load meshes for {}".format(shape.filename) - ) + raise Exception("Unable to load meshes for {}".format(shape.filename)) def ensure_geometry(self): """Check if geometry has been loaded. @@ -728,9 +723,7 @@ def ensure_geometry(self): for element in itertools.chain(link.collision, link.visual): shape = element.geometry.shape if not shape.meshes: - raise Exception( - "This method is only callable once the geometry has been loaded." - ) + raise Exception("This method is only callable once the geometry has been loaded.") @property def frames(self): @@ -833,9 +826,7 @@ def scale(self, factor, link=None): self._scale_factor = factor - def compute_transformations( - self, joint_state, link=None, parent_transformation=None - ): + def compute_transformations(self, joint_state, link=None, parent_transformation=None): """Recursive function to calculate the transformations of each joint. Parameters @@ -873,26 +864,16 @@ def compute_transformations( child_joint.name in joint_state.keys() ): # if passive/mimicking joint is in the joint_state, the transformation will be calculated according to this value position = joint_state[child_joint.name] - transformation = ( - parent_transformation - * child_joint.calculate_transformation(position) - ) + transformation = parent_transformation * child_joint.calculate_transformation(position) elif child_joint.mimic and child_joint.mimic.joint in joint_state.keys(): mimicked_joint_position = joint_state[child_joint.mimic.joint] position = child_joint.mimic.calculate_position(mimicked_joint_position) - transformation = ( - parent_transformation - * child_joint.calculate_transformation(position) - ) + transformation = parent_transformation * child_joint.calculate_transformation(position) else: transformation = parent_transformation transformations.update({child_joint.name: transformation}) # call function on child - transformations.update( - self.compute_transformations( - joint_state, child_joint.child_link, transformation - ) - ) + transformations.update(self.compute_transformations(joint_state, child_joint.child_link, transformation)) return transformations @@ -921,10 +902,7 @@ def transformed_frames(self, joint_state): """ transformations = self.compute_transformations(joint_state) - return [ - j.current_origin.transformed(transformations[j.name]) - for j in self.iter_joints() - ] + return [j.current_origin.transformed(transformations[j.name]) for j in self.iter_joints()] def transformed_axes(self, joint_state): """Returns the transformed axes based on the joint_state. @@ -1007,14 +985,7 @@ def _check_link_name(self, name): if name in all_link_names: raise ValueError("Link name '%s' already used in chain." % name) - def add_link( - self, - name, - visual_meshes=None, - visual_color=None, - collision_meshes=None, - **kwargs - ): + def add_link(self, name, visual_meshes=None, visual_color=None, collision_meshes=None, **kwargs): """Adds a link to the robot model. Provides an easy way to programmatically add a link to the robot model. @@ -1055,12 +1026,8 @@ def add_link( """ self._check_link_name(name) - visual_meshes, kwargs = self._consolidate_meshes( - visual_meshes, "visual_mesh", **kwargs - ) - collision_meshes, kwargs = self._consolidate_meshes( - collision_meshes, "collision_mesh", **kwargs - ) + visual_meshes, kwargs = self._consolidate_meshes(visual_meshes, "visual_mesh", **kwargs) + collision_meshes, kwargs = self._consolidate_meshes(collision_meshes, "collision_mesh", **kwargs) if not visual_color: visual_color = (0.8, 0.8, 0.8) @@ -1076,9 +1043,7 @@ def add_link( v.material = Material(color=Color("%f %f %f 1" % visual_color)) visuals.append(v) - for ( - collision - ) in collision_meshes: # use visual_mesh as collision_mesh if none passed? + for collision in collision_meshes: # use visual_mesh as collision_mesh if none passed? if isinstance(collision, Mesh): c = Collision(Geometry(MeshDescriptor(""))) c.geometry.shape.meshes = [collision] @@ -1107,17 +1072,7 @@ def remove_link(self, name): """ self.links = [link for link in self.links if link.name != name] - def add_joint( - self, - name, - type, - parent_link, - child_link, - origin=None, - axis=None, - limit=None, - **kwargs - ): + def add_joint(self, name, type, parent_link, child_link, origin=None, axis=None, limit=None, **kwargs): """Adds a joint to the robot model. Provides an easy way to programmatically add a joint to the robot model. @@ -1178,14 +1133,7 @@ def add_joint( type_str = Joint.SUPPORTED_TYPES[type] joint = Joint( - name, - type_str, - parent_link.name, - child_link.name, - origin=origin, - axis=axis, - limit=limit, - **kwargs + name, type_str, parent_link.name, child_link.name, origin=origin, axis=axis, limit=limit, **kwargs ) self.joints.append(joint) diff --git a/src/compas/robots/model/tool.py b/src/compas/robots/model/tool.py index 5d0c90fa4578..31c75e1d4ae1 100644 --- a/src/compas/robots/model/tool.py +++ b/src/compas/robots/model/tool.py @@ -44,9 +44,7 @@ def __init__( ): collision = collision or visual super(ToolModel, self).__init__(name) - self.add_link( - "attached_tool_link", visual_mesh=visual, collision_mesh=collision - ) + self.add_link("attached_tool_link", visual_mesh=visual, collision_mesh=collision) self._rebuild_tree() self._create(self.root, Transformation()) @@ -149,10 +147,7 @@ def from_tcf_to_t0cf(self, frames_tcf): """ Te = Transformation.from_frame_to_frame(self.frame, Frame.worldXY()) - return [ - Frame.from_transformation(Transformation.from_frame(f) * Te) - for f in frames_tcf - ] + return [Frame.from_transformation(Transformation.from_frame(f) * Te) for f in frames_tcf] def from_t0cf_to_tcf(self, frames_t0cf): """Converts frames at the robot's flange (tool0 frame) to frames at the robot's tool tip (tcf frame). @@ -181,7 +176,4 @@ def from_t0cf_to_tcf(self, frames_t0cf): """ Te = Transformation.from_frame_to_frame(Frame.worldXY(), self.frame) - return [ - Frame.from_transformation(Transformation.from_frame(f) * Te) - for f in frames_t0cf - ] + return [Frame.from_transformation(Transformation.from_frame(f) * Te) for f in frames_t0cf] diff --git a/src/compas/robots/resources/github.py b/src/compas/robots/resources/github.py index 5f4257c87e3c..2dfd7490943a 100644 --- a/src/compas/robots/resources/github.py +++ b/src/compas/robots/resources/github.py @@ -56,9 +56,7 @@ def build_url(self, file): str The file's url. """ - relative_path_component = ( - None if self.relative_path == "." else self.relative_path - ) + relative_path_component = None if self.relative_path == "." else self.relative_path url_components = [ GithubPackageMeshLoader.HOST, self.repository, diff --git a/src/compas/rpc/__main__.py b/src/compas/rpc/__main__.py index 998e498090ca..1581ede4d7dd 100644 --- a/src/compas/rpc/__main__.py +++ b/src/compas/rpc/__main__.py @@ -45,9 +45,7 @@ def main(): # Command: start start_command = commands.add_parser("start", help="Start RPC server") - start_command.add_argument( - "--port", "-p", action="store", default=1753, type=int, help="RPC port number" - ) + start_command.add_argument("--port", "-p", action="store", default=1753, type=int, help="RPC port number") start_command.add_argument( "--autoreload", dest="autoreload", @@ -64,9 +62,7 @@ def main(): # Command: stop stop_command = commands.add_parser("stop", help="Try to stop a remote RPC server") - stop_command.add_argument( - "--port", "-p", action="store", default=1753, type=int, help="RPC port number" - ) + stop_command.add_argument("--port", "-p", action="store", default=1753, type=int, help="RPC port number") stop_command.set_defaults(func=stop) # Invoke diff --git a/src/compas/rpc/dispatcher.py b/src/compas/rpc/dispatcher.py index 79a790d39b8f..0204775996c9 100644 --- a/src/compas/rpc/dispatcher.py +++ b/src/compas/rpc/dispatcher.py @@ -116,9 +116,7 @@ def _dispatch(self, name, args): try: function = getattr(module, functionname) except AttributeError: - odict["error"] = "This function is not part of the API: {0}".format( - functionname - ) + odict["error"] = "This function is not part of the API: {0}".format(functionname) else: try: diff --git a/src/compas/rpc/proxy.py b/src/compas/rpc/proxy.py index 8d6d6fea2406..56f9c650cd0a 100644 --- a/src/compas/rpc/proxy.py +++ b/src/compas/rpc/proxy.py @@ -274,10 +274,8 @@ def start_server(self): self._process.StartInfo.RedirectStandardOutput = self.capture_output self._process.StartInfo.RedirectStandardError = self.capture_output self._process.StartInfo.FileName = self.python - self._process.StartInfo.Arguments = ( - "-m {0} --port {1} --{2}autoreload".format( - self.service, self._port, "" if self.autoreload else "no-" - ) + self._process.StartInfo.Arguments = "-m {0} --port {1} --{2}autoreload".format( + self.service, self._port, "" if self.autoreload else "no-" ) self._process.Start() else: @@ -308,11 +306,7 @@ def start_server(self): except Exception: time.sleep(0.1) attempt_count += 1 - print( - " {} attempts left.".format( - self.max_conn_attempts - attempt_count - ) - ) + print(" {} attempts left.".format(self.max_conn_attempts - attempt_count)) else: success = True break diff --git a/src/compas/rpc/services/default.py b/src/compas/rpc/services/default.py index c7027e535535..0e706e183a17 100644 --- a/src/compas/rpc/services/default.py +++ b/src/compas/rpc/services/default.py @@ -75,11 +75,7 @@ def start_service(port, autoreload, **kwargs): service = DefaultService() if not autoreload else FileWatcherService() server.register_instance(service) - print( - "Listening{}...".format( - " with autoreload of modules enabled" if autoreload else "" - ) - ) + print("Listening{}...".format(" with autoreload of modules enabled" if autoreload else "")) print("Press CTRL+C to abort") server.serve_forever() @@ -92,9 +88,7 @@ def start_service(port, autoreload, **kwargs): import argparse parser = argparse.ArgumentParser() - parser.add_argument( - "--port", "-p", action="store", default=1753, type=int, help="RPC port number" - ) + parser.add_argument("--port", "-p", action="store", default=1753, type=int, help="RPC port number") parser.add_argument( "--autoreload", dest="autoreload", diff --git a/src/compas/topology/traversal.py b/src/compas/topology/traversal.py index c3fa9914f3a8..ec405c2e85aa 100644 --- a/src/compas/topology/traversal.py +++ b/src/compas/topology/traversal.py @@ -432,9 +432,7 @@ def _get_coordinates(key, structure): return structure.node_attributes(key, "xyz") if hasattr(structure, "vertex_coordinates"): return structure.vertex_coordinates(key) - raise Exception( - "Coordinates cannot be found for object of type {}".format(type(structure)) - ) + raise Exception("Coordinates cannot be found for object of type {}".format(type(structure))) def _get_points(structure): @@ -442,9 +440,7 @@ def _get_points(structure): return structure.nodes() if hasattr(structure, "vertices"): return structure.vertices() - raise Exception( - "Points cannot be found for object of type {}".format(type(structure)) - ) + raise Exception("Points cannot be found for object of type {}".format(type(structure))) def astar_shortest_path(graph, root, goal): diff --git a/src/compas/utilities/azync.py b/src/compas/utilities/azync.py index 526b336a0331..b45251774fe2 100644 --- a/src/compas/utilities/azync.py +++ b/src/compas/utilities/azync.py @@ -43,9 +43,7 @@ def __exit__(self, *args): threading.Thread.__init__ = self._original_init -def await_callback( - async_func, callback_name="callback", errback_name=None, *args, **kwargs -): +def await_callback(async_func, callback_name="callback", errback_name=None, *args, **kwargs): """Wait for the completion of an asynchronous code that uses callbacks to signal completion. This helper function turns an async function into a synchronous one, diff --git a/src/compas/utilities/colors.py b/src/compas/utilities/colors.py index 8b0156111875..54362355edf8 100644 --- a/src/compas/utilities/colors.py +++ b/src/compas/utilities/colors.py @@ -487,9 +487,7 @@ def rgb_to_rgb(rgb, g=None, b=None): r = max(0, min(r, 255)) g = max(0, min(g, 255)) b = max(0, min(b, 255)) - if any(isinstance(c, float) for c in (r, g, b)) and all( - c <= 1.0 for c in (r, g, b) - ): + if any(isinstance(c, float) for c in (r, g, b)) and all(c <= 1.0 for c in (r, g, b)): r = r * 255.0 g = g * 255.0 b = b * 255.0 diff --git a/src/compas/utilities/images.py b/src/compas/utilities/images.py index 4a35d327e451..d191712e15be 100644 --- a/src/compas/utilities/images.py +++ b/src/compas/utilities/images.py @@ -50,9 +50,7 @@ def gif_from_images( files.reverse() if pingpong: files += files[::-1] - with imageio.get_writer( - gif_path, mode="I", fps=fps, loop=loop, subrectangles=subrectangles - ) as writer: + with imageio.get_writer(gif_path, mode="I", fps=fps, loop=loop, subrectangles=subrectangles) as writer: for filename in files: image = imageio.imread(filename) writer.append_data(image) diff --git a/src/compas/utilities/itertools.py b/src/compas/utilities/itertools.py index 001992942432..a776c9ec9512 100644 --- a/src/compas/utilities/itertools.py +++ b/src/compas/utilities/itertools.py @@ -62,9 +62,7 @@ def normalize_values(values, new_min=0.0, new_max=1.0): return [(((value - old_min) * new_range) / old_range) + new_min for value in values] -def remap_values( - values, target_min=0.0, target_max=1.0, original_min=None, original_max=None -): +def remap_values(values, target_min=0.0, target_max=1.0, original_min=None, original_max=None): """Maps a list of numbers from one domain to another. Parameters diff --git a/src/compas/utilities/ssh.py b/src/compas/utilities/ssh.py index f294a956688d..e926c72450c8 100644 --- a/src/compas/utilities/ssh.py +++ b/src/compas/utilities/ssh.py @@ -44,11 +44,7 @@ def create_client(self): client.set_missing_host_key_policy(AutoAddPolicy()) try: client.connect(self.server, username=self.username) - print( - "\n***** Connected to server: {0} with username: {1}".format( - self.server, self.username - ) - ) + print("\n***** Connected to server: {0} with username: {1}".format(self.server, self.username)) except Exception: print("\n***** Connection failed") return client @@ -79,9 +75,7 @@ def receive_file(self, remote_file, local_file): None """ - command = "scp {0}@{1}:{2} {3}".format( - self.username, self.server, remote_file, local_file - ) + command = "scp {0}@{1}:{2} {3}".format(self.username, self.server, remote_file, local_file) self.local_command(command) def send_file(self, local_file): @@ -131,9 +125,7 @@ def sync_folder(self, local_folder, remote_folder): None """ - command = "rsync -Pa {0} {1}@{2}:{3}".format( - local_folder, self.username, self.server, remote_folder - ) + command = "rsync -Pa {0} {1}@{2}:{3}".format(local_folder, self.username, self.server, remote_folder) self.local_command(command=command) @staticmethod diff --git a/src/compas/utilities/xfunc.py b/src/compas/utilities/xfunc.py index 7d861799aaf0..023e5a091dd6 100644 --- a/src/compas/utilities/xfunc.py +++ b/src/compas/utilities/xfunc.py @@ -389,9 +389,7 @@ def __call__(self, *args, **kwargs): process.StartInfo.RedirectStandardOutput = True process.StartInfo.RedirectStandardError = True process.StartInfo.FileName = self.python - process.StartInfo.Arguments = '-u -c "{0}" {1} {2} {3} {4} {5}'.format( - *args - ) + process.StartInfo.Arguments = '-u -c "{0}" {1} {2} {3} {4} {5}'.format(*args) process.Start() process.WaitForExit() diff --git a/src/compas_blender/__init__.py b/src/compas_blender/__init__.py index ff1403b5a469..f860bd0075f3 100644 --- a/src/compas_blender/__init__.py +++ b/src/compas_blender/__init__.py @@ -77,11 +77,7 @@ def _get_default_blender_installation_path(version): raise Exception("Unsupported platform.") if not os.path.exists(path): - raise Exception( - "The default installation folder for Blender {} doesn't exist.".format( - version - ) - ) + raise Exception("The default installation folder for Blender {} doesn't exist.".format(version)) return path @@ -91,9 +87,7 @@ def _get_default_blender_installation_path_mac(version): def _get_default_blender_installation_path_windows(version): - return os.path.expandvars( - "%PROGRAMFILES%/Blender Foundation/Blender {}/{}".format(version, version) - ) + return os.path.expandvars("%PROGRAMFILES%/Blender Foundation/Blender {}/{}".format(version, version)) __all__ = [name for name in dir() if not name.startswith("_")] diff --git a/src/compas_blender/artists/artist.py b/src/compas_blender/artists/artist.py index 0835462c8264..b535d000120c 100644 --- a/src/compas_blender/artists/artist.py +++ b/src/compas_blender/artists/artist.py @@ -26,11 +26,7 @@ class BlenderArtist(Artist): """ - def __init__( - self, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): + def __init__(self, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): # Initialize collection before even calling super because other classes depend on that self._collection = None self.collection = collection @@ -47,6 +43,4 @@ def collection(self, value: Union[str, bpy.types.Collection]): elif isinstance(value, str): self._collection = compas_blender.create_collection(value) else: - raise Exception( - "Collection must be of type `str` or `bpy.types.Collection`." - ) + raise Exception("Collection must be of type `str` or `bpy.types.Collection`.") diff --git a/src/compas_blender/artists/boxartist.py b/src/compas_blender/artists/boxartist.py index facaa9b4de1a..3aee0fee0c9f 100644 --- a/src/compas_blender/artists/boxartist.py +++ b/src/compas_blender/artists/boxartist.py @@ -53,12 +53,7 @@ class BoxArtist(BlenderArtist, ShapeArtist): """ - def __init__( - self, - box: Box, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): + def __init__(self, box: Box, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): super().__init__(shape=box, collection=collection or box.name, **kwargs) diff --git a/src/compas_blender/artists/capsuleartist.py b/src/compas_blender/artists/capsuleartist.py index ace2a3f097a3..18b003246a1c 100644 --- a/src/compas_blender/artists/capsuleartist.py +++ b/src/compas_blender/artists/capsuleartist.py @@ -54,18 +54,11 @@ class CapsuleArtist(BlenderArtist, ShapeArtist): """ - def __init__( - self, - capsule: Capsule, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): + def __init__(self, capsule: Capsule, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): super().__init__(shape=capsule, collection=collection or capsule.name, **kwargs) - def draw( - self, color: Optional[Color] = None, u: int = None, v: int = None - ) -> List[bpy.types.Object]: + def draw(self, color: Optional[Color] = None, u: int = None, v: int = None) -> List[bpy.types.Object]: """Draw the capsule associated with the artist. Parameters diff --git a/src/compas_blender/artists/circleartist.py b/src/compas_blender/artists/circleartist.py index 2080f1b33c0c..913d1b9989a4 100644 --- a/src/compas_blender/artists/circleartist.py +++ b/src/compas_blender/artists/circleartist.py @@ -55,15 +55,8 @@ class CircleArtist(BlenderArtist, PrimitiveArtist): """ - def __init__( - self, - circle: Circle, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): - super().__init__( - primitive=circle, collection=collection or circle.name, **kwargs - ) + def __init__(self, circle: Circle, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): + super().__init__(primitive=circle, collection=collection or circle.name, **kwargs) def draw( self, diff --git a/src/compas_blender/artists/coneartist.py b/src/compas_blender/artists/coneartist.py index 623b1cefb4a5..2979018999d8 100644 --- a/src/compas_blender/artists/coneartist.py +++ b/src/compas_blender/artists/coneartist.py @@ -54,18 +54,11 @@ class ConeArtist(BlenderArtist, ShapeArtist): """ - def __init__( - self, - cone: Cone, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): + def __init__(self, cone: Cone, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): super().__init__(shape=cone, collection=collection or cone.name, **kwargs) - def draw( - self, color: Optional[Color] = None, u: int = None - ) -> List[bpy.types.Object]: + def draw(self, color: Optional[Color] = None, u: int = None) -> List[bpy.types.Object]: """Draw the cone associated with the artist. Parameters diff --git a/src/compas_blender/artists/curveartist.py b/src/compas_blender/artists/curveartist.py index 8995512acb4a..a9404cca910d 100644 --- a/src/compas_blender/artists/curveartist.py +++ b/src/compas_blender/artists/curveartist.py @@ -54,12 +54,7 @@ class CurveArtist(BlenderArtist, CurveArtist): """ - def __init__( - self, - curve: Curve, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): + def __init__(self, curve: Curve, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): super().__init__(curve=curve, collection=collection or curve.name, **kwargs) diff --git a/src/compas_blender/artists/cylinderartist.py b/src/compas_blender/artists/cylinderartist.py index 16443bf1f204..e4998dadf955 100644 --- a/src/compas_blender/artists/cylinderartist.py +++ b/src/compas_blender/artists/cylinderartist.py @@ -55,19 +55,12 @@ class CylinderArtist(BlenderArtist, ShapeArtist): """ def __init__( - self, - cylinder: Cylinder, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any + self, cylinder: Cylinder, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any ): - super().__init__( - shape=cylinder, collection=collection or cylinder.name, **kwargs - ) + super().__init__(shape=cylinder, collection=collection or cylinder.name, **kwargs) - def draw( - self, color: Optional[Color] = None, u: int = None - ) -> List[bpy.types.Object]: + def draw(self, color: Optional[Color] = None, u: int = None) -> List[bpy.types.Object]: """Draw the cylinder associated with the artist. Parameters diff --git a/src/compas_blender/artists/lineartist.py b/src/compas_blender/artists/lineartist.py index c4c45686e8d9..1b15a35a62b4 100644 --- a/src/compas_blender/artists/lineartist.py +++ b/src/compas_blender/artists/lineartist.py @@ -62,9 +62,7 @@ def __init__( ): super().__init__(primitive=line, collection=collection or line.name, **kwargs) - def draw( - self, color: Optional[Color] = None, show_points: bool = False - ) -> List[bpy.types.Object]: + def draw(self, color: Optional[Color] = None, show_points: bool = False) -> List[bpy.types.Object]: """Draw the line. Parameters diff --git a/src/compas_blender/artists/meshartist.py b/src/compas_blender/artists/meshartist.py index 7bc3bcba9424..b2591cef744b 100644 --- a/src/compas_blender/artists/meshartist.py +++ b/src/compas_blender/artists/meshartist.py @@ -83,65 +83,49 @@ def __init__( @property def vertexcollection(self) -> bpy.types.Collection: if not self._vertexcollection: - self._vertexcollection = compas_blender.create_collection( - "Vertices", parent=self.collection - ) + self._vertexcollection = compas_blender.create_collection("Vertices", parent=self.collection) return self._vertexcollection @property def edgecollection(self) -> bpy.types.Collection: if not self._edgecollection: - self._edgecollection = compas_blender.create_collection( - "Edges", parent=self.collection - ) + self._edgecollection = compas_blender.create_collection("Edges", parent=self.collection) return self._edgecollection @property def facecollection(self) -> bpy.types.Collection: if not self._facecollection: - self._facecollection = compas_blender.create_collection( - "Faces", parent=self.collection - ) + self._facecollection = compas_blender.create_collection("Faces", parent=self.collection) return self._facecollection @property def vertexnormalcollection(self) -> bpy.types.Collection: if not self._vertexnormalcollection: - self._vertexnormalcollection = compas_blender.create_collection( - "VertexNormals", parent=self.collection - ) + self._vertexnormalcollection = compas_blender.create_collection("VertexNormals", parent=self.collection) return self._vertexnormalcollection @property def facenormalcollection(self) -> bpy.types.Collection: if not self._facenormalcollection: - self._facenormalcollection = compas_blender.create_collection( - "FaceNormals", parent=self.collection - ) + self._facenormalcollection = compas_blender.create_collection("FaceNormals", parent=self.collection) return self._facenormalcollection @property def vertexlabelcollection(self) -> bpy.types.Collection: if not self._vertexlabelcollection: - self._vertexlabelcollection = compas_blender.create_collection( - "VertexLabels", parent=self.collection - ) + self._vertexlabelcollection = compas_blender.create_collection("VertexLabels", parent=self.collection) return self._vertexlabelcollection @property def edgelabelcollection(self) -> bpy.types.Collection: if not self._edgelabelcollection: - self._edgelabelcollection = compas_blender.create_collection( - "EdgeLabels", parent=self.collection - ) + self._edgelabelcollection = compas_blender.create_collection("EdgeLabels", parent=self.collection) return self._edgelabelcollection @property def facelabelcollection(self) -> bpy.types.Collection: if not self._facelabelcollection: - self._facelabelcollection = compas_blender.create_collection( - "FaceLabels", parent=self.collection - ) + self._facelabelcollection = compas_blender.create_collection("FaceLabels", parent=self.collection) return self._facelabelcollection # ========================================================================== @@ -308,10 +292,7 @@ def draw_faces( for face in faces: facets.append( { - "points": [ - self.vertex_xyz[vertex] - for vertex in self.mesh.face_vertices(face) - ], + "points": [self.vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)], "name": f"{self.mesh.name}.face.{face}", "color": self.face_color[face], } @@ -387,9 +368,7 @@ def draw_facenormals( faces = faces or self.faces lines = [] for face in faces: - a = centroid_points( - [self.vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)] - ) + a = centroid_points([self.vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)]) n = self.mesh.face_normal(face) b = add_vectors(a, scale_vector(n, scale)) lines.append( @@ -406,9 +385,7 @@ def draw_facenormals( # draw labels # ========================================================================== - def draw_vertexlabels( - self, text: Optional[Dict[int, str]] = None - ) -> List[bpy.types.Object]: + def draw_vertexlabels(self, text: Optional[Dict[int, str]] = None) -> List[bpy.types.Object]: """Draw labels for a selection vertices. Parameters @@ -435,9 +412,7 @@ def draw_vertexlabels( ) return compas_blender.draw_texts(labels, collection=self.vertexlabelcollection) - def draw_edgelabels( - self, text: Optional[Dict[Tuple[int, int], str]] = None - ) -> List[bpy.types.Object]: + def draw_edgelabels(self, text: Optional[Dict[Tuple[int, int], str]] = None) -> List[bpy.types.Object]: """Draw labels for a selection of edges. Parameters @@ -465,9 +440,7 @@ def draw_edgelabels( ) return compas_blender.draw_texts(labels, collection=self.edgelabelcollection) - def draw_facelabels( - self, text: Optional[Dict[int, str]] = None - ) -> List[bpy.types.Object]: + def draw_facelabels(self, text: Optional[Dict[int, str]] = None) -> List[bpy.types.Object]: """Draw labels for a selection of faces. Parameters @@ -486,12 +459,7 @@ def draw_facelabels( for face in self.face_text: labels.append( { - "pos": centroid_points( - [ - self.vertex_xyz[vertex] - for vertex in self.mesh.face_vertices(face) - ] - ), + "pos": centroid_points([self.vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)]), "name": "{}.facelabel.{}".format(self.mesh.name, face), "text": self.face_text[face], "color": self.face_color[face], diff --git a/src/compas_blender/artists/networkartist.py b/src/compas_blender/artists/networkartist.py index 48604709ea72..51a5d33f340d 100644 --- a/src/compas_blender/artists/networkartist.py +++ b/src/compas_blender/artists/networkartist.py @@ -77,40 +77,30 @@ def __init__( **kwargs: Any, ): - super().__init__( - network=network, collection=collection or network.name, **kwargs - ) + super().__init__(network=network, collection=collection or network.name, **kwargs) @property def nodecollection(self) -> bpy.types.Collection: if not self._nodecollection: - self._nodecollection = compas_blender.create_collection( - "Nodes", parent=self.collection - ) + self._nodecollection = compas_blender.create_collection("Nodes", parent=self.collection) return self._nodecollection @property def edgecollection(self) -> bpy.types.Collection: if not self._edgecollection: - self._edgecollection = compas_blender.create_collection( - "Edges", parent=self.collection - ) + self._edgecollection = compas_blender.create_collection("Edges", parent=self.collection) return self._edgecollection @property def nodelabelcollection(self) -> bpy.types.Collection: if not self._nodelabelcollection: - self._nodelabelcollection = compas_blender.create_collection( - "NodeLabels", parent=self.collection - ) + self._nodelabelcollection = compas_blender.create_collection("NodeLabels", parent=self.collection) return self._nodelabelcollection @property def edgelabelcollection(self) -> bpy.types.Collection: if not self._edgelabelcollection: - self._edgelabelcollection = compas_blender.create_collection( - "EdgeLabels", parent=self.collection - ) + self._edgelabelcollection = compas_blender.create_collection("EdgeLabels", parent=self.collection) return self._edgelabelcollection # ========================================================================== @@ -266,9 +256,7 @@ def draw_edges( ) return compas_blender.draw_lines(lines, self.edgecollection) - def draw_nodelabels( - self, text: Optional[Dict[int, str]] = None - ) -> List[bpy.types.Object]: + def draw_nodelabels(self, text: Optional[Dict[int, str]] = None) -> List[bpy.types.Object]: """Draw labels for a selection nodes. Parameters @@ -295,9 +283,7 @@ def draw_nodelabels( ) return compas_blender.draw_texts(labels, collection=self.nodelabelcollection) - def draw_edgelabels( - self, text: Optional[Dict[Tuple[int, int], str]] = None - ) -> List[bpy.types.Object]: + def draw_edgelabels(self, text: Optional[Dict[Tuple[int, int], str]] = None) -> List[bpy.types.Object]: """Draw labels for a selection of edges. Parameters diff --git a/src/compas_blender/artists/polygonartist.py b/src/compas_blender/artists/polygonartist.py index 1f132908549d..17d5befba090 100644 --- a/src/compas_blender/artists/polygonartist.py +++ b/src/compas_blender/artists/polygonartist.py @@ -50,15 +50,8 @@ class PolygonArtist(BlenderArtist, PrimitiveArtist): """ - def __init__( - self, - polygon: Polygon, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): - super().__init__( - primitive=polygon, collection=collection or polygon.name, **kwargs - ) + def __init__(self, polygon: Polygon, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): + super().__init__(primitive=polygon, collection=collection or polygon.name, **kwargs) def draw( self, @@ -101,8 +94,7 @@ def draw( objects += compas_blender.draw_points(points, collection=self.collection) if show_edges: lines = [ - {"start": a, "end": b, "color": color, "name": self.primitive.name} - for a, b in self.primitive.lines + {"start": a, "end": b, "color": color, "name": self.primitive.name} for a, b in self.primitive.lines ] objects += compas_blender.draw_lines(lines, collection=self.collection) if show_face: diff --git a/src/compas_blender/artists/polyhedronartist.py b/src/compas_blender/artists/polyhedronartist.py index 8b19eb753aee..8aa1780e4a4e 100644 --- a/src/compas_blender/artists/polyhedronartist.py +++ b/src/compas_blender/artists/polyhedronartist.py @@ -54,15 +54,10 @@ class PolyhedronArtist(BlenderArtist, ShapeArtist): """ def __init__( - self, - polyhedron: Polyhedron, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any + self, polyhedron: Polyhedron, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any ): - super().__init__( - shape=polyhedron, collection=collection or polyhedron.name, **kwargs - ) + super().__init__(shape=polyhedron, collection=collection or polyhedron.name, **kwargs) def draw(self, color: Optional[Color] = None) -> List[bpy.types.Object]: """Draw the polyhedron associated with the artist. diff --git a/src/compas_blender/artists/polylineartist.py b/src/compas_blender/artists/polylineartist.py index ac463de0df1c..a56971effbf9 100644 --- a/src/compas_blender/artists/polylineartist.py +++ b/src/compas_blender/artists/polylineartist.py @@ -60,13 +60,9 @@ def __init__( collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any, ): - super().__init__( - primitive=polyline, collection=collection or polyline.name, **kwargs - ) + super().__init__(primitive=polyline, collection=collection or polyline.name, **kwargs) - def draw( - self, color: Optional[Color] = None, show_points: Optional[bool] = False - ) -> List[bpy.types.Object]: + def draw(self, color: Optional[Color] = None, show_points: Optional[bool] = False) -> List[bpy.types.Object]: """Draw the line. Parameters diff --git a/src/compas_blender/artists/robotmodelartist.py b/src/compas_blender/artists/robotmodelartist.py index 1bd5eba7b5a4..0cfacfddd3cc 100644 --- a/src/compas_blender/artists/robotmodelartist.py +++ b/src/compas_blender/artists/robotmodelartist.py @@ -32,19 +32,12 @@ class RobotModelArtist(BlenderArtist, RobotModelArtist): """ - def __init__( - self, - model: RobotModel, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): + def __init__(self, model: RobotModel, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): super().__init__(model=model, collection=collection or model.name, **kwargs) # this method should not be here # it has nothing to do with the current object - def transform( - self, native_mesh: bpy.types.Object, transformation: Transformation - ) -> None: + def transform(self, native_mesh: bpy.types.Object, transformation: Transformation) -> None: """Transform the mesh of a robot model. Parameters @@ -59,9 +52,7 @@ def transform( None """ - native_mesh.matrix_world = ( - mathutils.Matrix(transformation.matrix) @ native_mesh.matrix_world - ) + native_mesh.matrix_world = mathutils.Matrix(transformation.matrix) @ native_mesh.matrix_world # again # doesn't make sense to me that there is no reference to self (except for the collection) @@ -70,9 +61,7 @@ def create_geometry( self, geometry: Mesh, name: str = None, - color: Union[ - RGBColor, Tuple[int, int, int, int], Tuple[float, float, float, float] - ] = None, + color: Union[RGBColor, Tuple[int, int, int, int], Tuple[float, float, float, float]] = None, ) -> bpy.types.Object: """Create the scene objecy representing the robot geometry. diff --git a/src/compas_blender/artists/sphereartist.py b/src/compas_blender/artists/sphereartist.py index e278108852da..0292cde07f99 100644 --- a/src/compas_blender/artists/sphereartist.py +++ b/src/compas_blender/artists/sphereartist.py @@ -54,18 +54,11 @@ class SphereArtist(BlenderArtist, ShapeArtist): """ - def __init__( - self, - sphere: Sphere, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): + def __init__(self, sphere: Sphere, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): super().__init__(shape=sphere, collection=collection or sphere.name, **kwargs) - def draw( - self, color: Optional[Color] = None, u: int = None, v: int = None - ) -> List[bpy.types.Object]: + def draw(self, color: Optional[Color] = None, u: int = None, v: int = None) -> List[bpy.types.Object]: """Draw the sphere associated with the artist. Parameters diff --git a/src/compas_blender/artists/surfaceartist.py b/src/compas_blender/artists/surfaceartist.py index 5a1597e6a2d1..3ac245784a94 100644 --- a/src/compas_blender/artists/surfaceartist.py +++ b/src/compas_blender/artists/surfaceartist.py @@ -54,16 +54,9 @@ class SurfaceArtist(BlenderArtist, SurfaceArtist): """ - def __init__( - self, - surface: Surface, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): + def __init__(self, surface: Surface, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): - super().__init__( - surface=surface, collection=collection or surface.name, **kwargs - ) + super().__init__(surface=surface, collection=collection or surface.name, **kwargs) def draw(self, color: Optional[Color] = None) -> List[bpy.types.Object]: """Draw the surface. @@ -80,7 +73,5 @@ def draw(self, color: Optional[Color] = None) -> List[bpy.types.Object]: """ color = Color.coerce(color) or self.color - surfaces = [ - {"surface": self.surface, "color": color, "name": self.surface.name} - ] + surfaces = [{"surface": self.surface, "color": color, "name": self.surface.name}] return compas_blender.draw_surfaces(surfaces, collection=self.collection) diff --git a/src/compas_blender/artists/torusartist.py b/src/compas_blender/artists/torusartist.py index 3301d4aa67ae..b34f2f56cda4 100644 --- a/src/compas_blender/artists/torusartist.py +++ b/src/compas_blender/artists/torusartist.py @@ -54,12 +54,7 @@ class TorusArtist(BlenderArtist, ShapeArtist): """ - def __init__( - self, - torus: Torus, - collection: Optional[Union[str, bpy.types.Collection]] = None, - **kwargs: Any - ): + def __init__(self, torus: Torus, collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any): super().__init__(shape=torus, collection=collection or torus.name, **kwargs) diff --git a/src/compas_blender/artists/vectorartist.py b/src/compas_blender/artists/vectorartist.py index a6b55fa51c42..d637f20da866 100644 --- a/src/compas_blender/artists/vectorartist.py +++ b/src/compas_blender/artists/vectorartist.py @@ -61,9 +61,7 @@ def __init__( collection: Optional[Union[str, bpy.types.Collection]] = None, **kwargs: Any, ): - super().__init__( - primitive=vector, collection=collection or vector.name, **kwargs - ) + super().__init__(primitive=vector, collection=collection or vector.name, **kwargs) def draw( self, diff --git a/src/compas_blender/artists/volmeshartist.py b/src/compas_blender/artists/volmeshartist.py index cffa7757d9db..84eb8317075e 100644 --- a/src/compas_blender/artists/volmeshartist.py +++ b/src/compas_blender/artists/volmeshartist.py @@ -41,88 +41,66 @@ def __init__( **kwargs: Any, ): - super().__init__( - volmesh=volmesh, collection=collection or volmesh.name, **kwargs - ) + super().__init__(volmesh=volmesh, collection=collection or volmesh.name, **kwargs) @property def vertexcollection(self) -> bpy.types.Collection: if not self._vertexcollection: - self._vertexcollection = compas_blender.create_collection( - "Vertices", parent=self.collection - ) + self._vertexcollection = compas_blender.create_collection("Vertices", parent=self.collection) return self._vertexcollection @property def edgecollection(self) -> bpy.types.Collection: if not self._edgecollection: - self._edgecollection = compas_blender.create_collection( - "Edges", parent=self.collection - ) + self._edgecollection = compas_blender.create_collection("Edges", parent=self.collection) return self._edgecollection @property def facecollection(self) -> bpy.types.Collection: if not self._facecollection: - self._facecollection = compas_blender.create_collection( - "Faces", parent=self.collection - ) + self._facecollection = compas_blender.create_collection("Faces", parent=self.collection) return self._facecollection @property def cellcollection(self) -> bpy.types.Collection: if not self._cellcollection: - self._cellcollection = compas_blender.create_collection( - "Cells", parent=self.collection - ) + self._cellcollection = compas_blender.create_collection("Cells", parent=self.collection) return self._cellcollection @property def vertexnormalcollection(self) -> bpy.types.Collection: if not self._vertexnormalcollection: - self._vertexnormalcollection = compas_blender.create_collection( - "VertexNormals", parent=self.collection - ) + self._vertexnormalcollection = compas_blender.create_collection("VertexNormals", parent=self.collection) return self._vertexnormalcollection @property def facenormalcollection(self) -> bpy.types.Collection: if not self._facenormalcollection: - self._facenormalcollection = compas_blender.create_collection( - "FaceNormals", parent=self.collection - ) + self._facenormalcollection = compas_blender.create_collection("FaceNormals", parent=self.collection) return self._facenormalcollection @property def vertexlabelcollection(self) -> bpy.types.Collection: if not self._vertexlabelcollection: - self._vertexlabelcollection = compas_blender.create_collection( - "VertexLabels", parent=self.collection - ) + self._vertexlabelcollection = compas_blender.create_collection("VertexLabels", parent=self.collection) return self._vertexlabelcollection @property def edgelabelcollection(self) -> bpy.types.Collection: if not self._edgelabelcollection: - self._edgelabelcollection = compas_blender.create_collection( - "EdgeLabels", parent=self.collection - ) + self._edgelabelcollection = compas_blender.create_collection("EdgeLabels", parent=self.collection) return self._edgelabelcollection @property def facelabelcollection(self) -> bpy.types.Collection: if not self._facelabelcollection: - self._facelabelcollection = compas_blender.create_collection( - "FaceLabels", parent=self.collection - ) + self._facelabelcollection = compas_blender.create_collection("FaceLabels", parent=self.collection) return self._facelabelcollection @property def celllabelcollection(self) -> bpy.types.Collection: if not self._celllabelcollection: - self._celllabelcollection = compas_blender.create_collection( - "CellLabels", parent=self.collection - ) + self._celllabelcollection = compas_blender.create_collection("CellLabels", parent=self.collection) return self._celllabelcollection # ========================================================================== @@ -178,9 +156,7 @@ def clear_cells(self): # draw # ========================================================================== - def draw( - self, cells: Optional[List[int]] = None, color: Optional[Color] = None - ) -> List[bpy.types.Object]: + def draw(self, cells: Optional[List[int]] = None, color: Optional[Color] = None) -> List[bpy.types.Object]: """Draw a selection of cells. Parameters @@ -297,10 +273,7 @@ def draw_faces( for face in faces: facets.append( { - "points": [ - self.vertex_xyz[vertex] - for vertex in self.volmesh.face_vertices(face) - ], + "points": [self.vertex_xyz[vertex] for vertex in self.volmesh.face_vertices(face)], "name": f"{self.volmesh.name}.face.{face}", "color": self.face_color[face], } @@ -335,14 +308,9 @@ def draw_cells( for cell in cells: vertices = self.volmesh.cell_vertices(cell) faces = self.volmesh.cell_faces(cell) - vertex_index = dict( - (vertex, index) for index, vertex in enumerate(vertices) - ) + vertex_index = dict((vertex, index) for index, vertex in enumerate(vertices)) vertices = [vertex_xyz[vertex] for vertex in vertices] - faces = [ - [vertex_index[vertex] for vertex in self.halfface_vertices(face)] - for face in faces - ] + faces = [[vertex_index[vertex] for vertex in self.halfface_vertices(face)] for face in faces] obj = compas_blender.draw_mesh( vertices, faces, @@ -422,9 +390,7 @@ def draw_facenormals( faces = faces or self.faces lines = [] for face in faces: - a = centroid_points( - [self.vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)] - ) + a = centroid_points([self.vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)]) n = self.mesh.face_normal(face) b = add_vectors(a, scale_vector(n, scale)) lines.append( @@ -441,9 +407,7 @@ def draw_facenormals( # draw labels # ========================================================================== - def draw_vertexlabels( - self, text: Optional[Dict[int, str]] = None - ) -> List[bpy.types.Object]: + def draw_vertexlabels(self, text: Optional[Dict[int, str]] = None) -> List[bpy.types.Object]: """Draw labels for a selection vertices. Parameters @@ -470,9 +434,7 @@ def draw_vertexlabels( ) return compas_blender.draw_texts(labels, collection=self.vertexlabelcollection) - def draw_edgelabels( - self, text: Optional[Dict[Tuple[int, int], str]] = None - ) -> List[bpy.types.Object]: + def draw_edgelabels(self, text: Optional[Dict[Tuple[int, int], str]] = None) -> List[bpy.types.Object]: """Draw labels for a selection of edges. Parameters @@ -500,9 +462,7 @@ def draw_edgelabels( ) return compas_blender.draw_texts(labels, collection=self.edgelabelcollection) - def draw_facelabels( - self, text: Optional[Dict[int, str]] = None - ) -> List[bpy.types.Object]: + def draw_facelabels(self, text: Optional[Dict[int, str]] = None) -> List[bpy.types.Object]: """Draw labels for a selection of faces. Parameters @@ -521,12 +481,7 @@ def draw_facelabels( for face in self.face_text: labels.append( { - "pos": centroid_points( - [ - self.vertex_xyz[vertex] - for vertex in self.mesh.face_vertices(face) - ] - ), + "pos": centroid_points([self.vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)]), "name": "{}.facelabel.{}".format(self.mesh.name, face), "text": self.face_text[face], "color": self.face_color[face], diff --git a/src/compas_blender/install.py b/src/compas_blender/install.py index 078fba147f24..ee5855aabedc 100644 --- a/src/compas_blender/install.py +++ b/src/compas_blender/install.py @@ -126,18 +126,12 @@ def install(blender_path, version=None): remove(compas_bootstrapper) print("Installing current conda environment into Blender...") - print( - " Renaming bundled python folder to original_python: {} => {}".format( - blenderpython_src, blenderpython_dst - ) - ) + print(" Renaming bundled python folder to original_python: {} => {}".format(blenderpython_src, blenderpython_dst)) rename(blenderpython_src, blenderpython_dst) create_symlinks([(os.environ["CONDA_PREFIX"], blenderpython_src)]) # Take either the CONDA environment directory or the current Python executable's directory - python_directory = os.environ.get("CONDA_PREFIX", None) or os.path.dirname( - sys.executable - ) + python_directory = os.environ.get("CONDA_PREFIX", None) or os.path.dirname(sys.executable) environment_name = os.environ.get("CONDA_DEFAULT_ENV", "") # Get current sys.version value, we will override it inside Blender @@ -147,11 +141,7 @@ def install(blender_path, version=None): _handle, bootstrapper_temp_path = tempfile.mkstemp(suffix=".py", text=True) with open(bootstrapper_temp_path, "w") as f: - f.write( - BOOTSTRAPPER_TEMPLATE.format( - environment_name, python_directory, sys_version - ) - ) + f.write(BOOTSTRAPPER_TEMPLATE.format(environment_name, python_directory, sys_version)) print(" Creating bootstrap script: {}".format(compas_bootstrapper)) copy(bootstrapper_temp_path, compas_bootstrapper) diff --git a/src/compas_blender/install_windows.py b/src/compas_blender/install_windows.py index 56c6859aa4c5..5ca64f34f746 100644 --- a/src/compas_blender/install_windows.py +++ b/src/compas_blender/install_windows.py @@ -28,9 +28,7 @@ def unregister(): """ -def install_windows( - blender_path, version=None, packages=None, force_reinstall=False, no_deps=False -): +def install_windows(blender_path, version=None, packages=None, force_reinstall=False, no_deps=False): """Install COMPAS for Blender on Windows. Parameters @@ -122,9 +120,7 @@ def install_windows( blenderpython = os.path.join(blender_path, "python", "bin", "python.exe") try: - subprocess.run( - [blenderpython, "-m", "pip", "install", "--upgrade", "pip"], check=True - ) + subprocess.run([blenderpython, "-m", "pip", "install", "--upgrade", "pip"], check=True) except subprocess.CalledProcessError: print("Could not upgrade pip") sys.exit(-1) @@ -162,9 +158,7 @@ def install_windows( print() print("COMPAS for Blender {} has been installed via pip.".format(version)) - print( - "Note that functionaliy of conda-only packages has to be run via the command server (RPC)." - ) + print("Note that functionaliy of conda-only packages has to be run via the command server (RPC).") # ============================================================================== @@ -189,9 +183,7 @@ def install_windows( help="The version of Blender to install COMPAS in.", ) parser.add_argument("-p", "--packages", nargs="+", help="The packages to install.") - parser.add_argument( - "--force-reinstall", dest="force_reinstall", default=False, action="store_true" - ) + parser.add_argument("--force-reinstall", dest="force_reinstall", default=False, action="store_true") parser.add_argument("--no-deps", dest="no_deps", default=False, action="store_true") args = parser.parse_args() diff --git a/src/compas_blender/utilities/collections.py b/src/compas_blender/utilities/collections.py index 13af80500b20..f01c69c9baa5 100644 --- a/src/compas_blender/utilities/collections.py +++ b/src/compas_blender/utilities/collections.py @@ -21,9 +21,7 @@ def collection_path(collection, names=[]): return names -def create_collection( - name: Text, parent: bpy.types.Collection = None -) -> bpy.types.Collection: +def create_collection(name: Text, parent: bpy.types.Collection = None) -> bpy.types.Collection: """Create a collection with the given name. Parameters @@ -80,9 +78,7 @@ def create_collections(names: List[Text]) -> List[bpy.types.Collection]: return collections -def create_collections_from_path( - path: Text, separator: Text = "::" -) -> List[bpy.types.Collection]: +def create_collections_from_path(path: Text, separator: Text = "::") -> List[bpy.types.Collection]: """Create nested collections from a collection path string. Parameters diff --git a/src/compas_blender/utilities/drawing.py b/src/compas_blender/utilities/drawing.py index 18375a2e6989..b7e54f6d33c0 100644 --- a/src/compas_blender/utilities/drawing.py +++ b/src/compas_blender/utilities/drawing.py @@ -135,9 +135,7 @@ def draw_texts( # replace this by a custom point shader # https://docs.blender.org/api/current/gpu.html#custom-shader-for-dotted-3d-line # https://docs.blender.org/api/current/gpu.html#triangle-with-custom-shader -def draw_points( - points: List[Dict], collection: Union[Text, bpy.types.Collection] = None -) -> List[bpy.types.Object]: +def draw_points(points: List[Dict], collection: Union[Text, bpy.types.Collection] = None) -> List[bpy.types.Object]: """Draw point objects. Parameters @@ -175,9 +173,7 @@ def draw_points( # replace this by a custom pointcloud shader # https://docs.blender.org/api/current/gpu.html#custom-shader-for-dotted-3d-line # https://docs.blender.org/api/current/gpu.html#triangle-with-custom-shader -def draw_pointcloud( - points: List[Dict], collection: Union[Text, bpy.types.Collection] = None -) -> bpy.types.Object: +def draw_pointcloud(points: List[Dict], collection: Union[Text, bpy.types.Collection] = None) -> bpy.types.Object: """Draw point objects as a single cloud. Parameters @@ -194,9 +190,7 @@ def draw_pointcloud( """ P = len(points) N = len(str(P)) - bpy.ops.mesh.primitive_uv_sphere_add( - location=[0, 0, 0], radius=1.0, segments=10, ring_count=10 - ) + bpy.ops.mesh.primitive_uv_sphere_add(location=[0, 0, 0], radius=1.0, segments=10, ring_count=10) empty = bpy.context.object _link_object(empty, collection) _set_object_color(empty, [1.0, 1.0, 1.0]) @@ -343,9 +337,7 @@ def draw_polygons( raise NotImplementedError -def draw_faces( - faces: List[Dict], collection: Union[Text, bpy.types.Collection] = None -) -> List[bpy.types.Object]: +def draw_faces(faces: List[Dict], collection: Union[Text, bpy.types.Collection] = None) -> List[bpy.types.Object]: """Draw polygonal faces. Parameters @@ -379,9 +371,7 @@ def draw_faces( return objects -def draw_circles( - circles: List[Dict], collection: Union[Text, bpy.types.Collection] = None -) -> List[bpy.types.Object]: +def draw_circles(circles: List[Dict], collection: Union[Text, bpy.types.Collection] = None) -> List[bpy.types.Object]: """Draw circle objects as mesh primitives. Parameters @@ -420,9 +410,7 @@ def draw_circles( return objects -def draw_planes( - planes: List[Dict], collection: Union[Text, bpy.types.Collection] = None -) -> List[bpy.types.Object]: +def draw_planes(planes: List[Dict], collection: Union[Text, bpy.types.Collection] = None) -> List[bpy.types.Object]: """Draw plane objects as mesh primitives. Parameters @@ -486,9 +474,7 @@ def draw_cylinders( from math import acos from math import atan2 - bpy.ops.mesh.primitive_cylinder_add( - location=[0, 0, 0], radius=1, depth=1, vertices=uv - ) + bpy.ops.mesh.primitive_cylinder_add(location=[0, 0, 0], radius=1, depth=1, vertices=uv) empty = bpy.context.object _link_object(empty, collection) objects = [0] * len(cylinders) @@ -534,9 +520,7 @@ def draw_spheres( list[:blender:`bpy.types.Object`] """ - bpy.ops.mesh.primitive_uv_sphere_add( - location=[0, 0, 0], radius=1.0, segments=uv, ring_count=uv - ) + bpy.ops.mesh.primitive_uv_sphere_add(location=[0, 0, 0], radius=1.0, segments=uv, ring_count=uv) empty = bpy.context.object _link_object(empty, collection) objects = [0] * len(spheres) @@ -555,9 +539,7 @@ def draw_spheres( return objects -def draw_cubes( - cubes: List[Dict], collection: Union[Text, bpy.types.Collection] = None -) -> List[bpy.types.Object]: +def draw_cubes(cubes: List[Dict], collection: Union[Text, bpy.types.Collection] = None) -> List[bpy.types.Object]: """Draw cube objects as mesh primitives. Parameters @@ -701,9 +683,7 @@ def draw_mesh( # ============================================================================== -def draw_curves( - curves: List[Dict], collection: Union[Text, bpy.types.Collection] = None -) -> List[bpy.types.Object]: +def draw_curves(curves: List[Dict], collection: Union[Text, bpy.types.Collection] = None) -> List[bpy.types.Object]: """Draw curve objects. Parameters @@ -747,9 +727,7 @@ def draw_curves( return objects -def draw_surfaces( - surfaces: List[Dict], collection: Union[Text, bpy.types.Collection] = None -) -> List[bpy.types.Object]: +def draw_surfaces(surfaces: List[Dict], collection: Union[Text, bpy.types.Collection] = None) -> List[bpy.types.Object]: """Draw surface objects. Parameters diff --git a/src/compas_ghpython/__init__.py b/src/compas_ghpython/__init__.py index 764b07eda551..12d0992450c5 100644 --- a/src/compas_ghpython/__init__.py +++ b/src/compas_ghpython/__init__.py @@ -65,9 +65,7 @@ def get_grasshopper_managedplugin_path(version): if not os.path.exists(gh_managedplugin_path): raise Exception( - "The Grasshopper (managed) Plug-in folder does not exist in this location: {}".format( - gh_managedplugin_path - ) + "The Grasshopper (managed) Plug-in folder does not exist in this location: {}".format(gh_managedplugin_path) ) return gh_managedplugin_path @@ -103,9 +101,7 @@ def fetch_ghio_lib(target_folder="temp"): ghio_dll = "GH_IO.dll" filename = "lib/net48/" + ghio_dll - response = urllib.request.urlopen( - "https://www.nuget.org/api/v2/package/Grasshopper/" - ) + response = urllib.request.urlopen("https://www.nuget.org/api/v2/package/Grasshopper/") dst_file = os.path.join(target_folder, ghio_dll) zip_file = zipfile.ZipFile(io.BytesIO(response.read())) diff --git a/src/compas_ghpython/artists/meshartist.py b/src/compas_ghpython/artists/meshartist.py index ccbf79035b52..8e65dcd46c66 100644 --- a/src/compas_ghpython/artists/meshartist.py +++ b/src/compas_ghpython/artists/meshartist.py @@ -122,9 +122,7 @@ def draw_faces(self, faces=None, color=None, join_faces=False): for face in faces: facets.append( { - "points": [ - vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face) - ], + "points": [vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)], "name": "{}.face.{}".format(self.mesh.name, face), "color": self.face_color[face].rgb255, } diff --git a/src/compas_ghpython/artists/polygonartist.py b/src/compas_ghpython/artists/polygonartist.py index 4358b9e6b4b1..8b8f00575e61 100644 --- a/src/compas_ghpython/artists/polygonartist.py +++ b/src/compas_ghpython/artists/polygonartist.py @@ -50,10 +50,7 @@ def draw(self, color=None, show_points=False, show_edges=False, show_face=True): _points = map(list, self.primitive.points) result = [] if show_points: - points = [ - {"pos": point, "color": color, "name": self.primitive.name} - for point in _points - ] + points = [{"pos": point, "color": color, "name": self.primitive.name} for point in _points] result += compas_ghpython.draw_points(points) if show_edges: lines = [ @@ -67,8 +64,6 @@ def draw(self, color=None, show_points=False, show_edges=False, show_face=True): ] result += compas_ghpython.draw_lines(lines) if show_face: - polygons = [ - {"points": _points, "color": color, "name": self.primitive.name} - ] + polygons = [{"points": _points, "color": color, "name": self.primitive.name}] result += compas_ghpython.draw_faces(polygons) return result diff --git a/src/compas_ghpython/artists/polylineartist.py b/src/compas_ghpython/artists/polylineartist.py index 61e758e263b3..3aa599886232 100644 --- a/src/compas_ghpython/artists/polylineartist.py +++ b/src/compas_ghpython/artists/polylineartist.py @@ -39,7 +39,5 @@ def draw(self, color=None): """ color = Color.coerce(color) or self.color - polylines = [ - {"points": map(list, self.primitive.points), "color": color.rgb255} - ] + polylines = [{"points": map(list, self.primitive.points), "color": color.rgb255}] return compas_ghpython.draw_polylines(polylines)[0] diff --git a/src/compas_ghpython/artists/volmeshartist.py b/src/compas_ghpython/artists/volmeshartist.py index 0b96b6ffc8bd..4aa7e4bec077 100644 --- a/src/compas_ghpython/artists/volmeshartist.py +++ b/src/compas_ghpython/artists/volmeshartist.py @@ -134,10 +134,7 @@ def draw_faces(self, faces=None, color=None, join_faces=False): for face in faces: facets.append( { - "points": [ - vertex_xyz[vertex] - for vertex in self.volmesh.halfface_vertices(face) - ], + "points": [vertex_xyz[vertex] for vertex in self.volmesh.halfface_vertices(face)], "name": "{}.face.{}".format(self.volmesh.name, face), "color": self.face_color[face].rgb255, } @@ -168,17 +165,10 @@ def draw_cells(self, cells=None, color=None): for cell in cells: vertices = self.volmesh.cell_vertices(cell) faces = self.volmesh.cell_faces(cell) - vertex_index = dict( - (vertex, index) for index, vertex in enumerate(vertices) - ) + vertex_index = dict((vertex, index) for index, vertex in enumerate(vertices)) vertices = [vertex_xyz[vertex] for vertex in vertices] - faces = [ - [vertex_index[vertex] for vertex in self.halfface_vertices(face)] - for face in faces - ] - mesh = compas_ghpython.draw_mesh( - vertices, faces, color=self.cell_color[cell].rgb255 - ) + faces = [[vertex_index[vertex] for vertex in self.halfface_vertices(face)] for face in faces] + mesh = compas_ghpython.draw_mesh(vertices, faces, color=self.cell_color[cell].rgb255) meshes.append(mesh) return meshes diff --git a/src/compas_ghpython/install.py b/src/compas_ghpython/install.py index e7dde820e0aa..7a6d423d71b8 100644 --- a/src/compas_ghpython/install.py +++ b/src/compas_ghpython/install.py @@ -18,9 +18,7 @@ def after_rhino_install(installed_packages): if "compas_ghpython" not in installed_packages: return [] - installed_objects = install_userobjects( - os.path.join(os.path.dirname(__file__), "components", "ghuser") - ) + installed_objects = install_userobjects(os.path.join(os.path.dirname(__file__), "components", "ghuser")) return [ ( diff --git a/src/compas_ghpython/uninstall.py b/src/compas_ghpython/uninstall.py index 6ffe3b45c942..1245c1282bbe 100644 --- a/src/compas_ghpython/uninstall.py +++ b/src/compas_ghpython/uninstall.py @@ -15,25 +15,16 @@ def after_rhino_uninstall(uninstalled_packages): return [] srcdir = os.path.join(os.path.dirname(__file__), "components", "ghuser") - userobjects = [ - os.path.basename(ghuser) - for ghuser in glob.glob(os.path.join(srcdir, "*.ghuser")) - ] + userobjects = [os.path.basename(ghuser) for ghuser in glob.glob(os.path.join(srcdir, "*.ghuser"))] uninstalled_objects = uninstall_userobjects(userobjects) uninstall_errors = [uo[0] for uo in uninstalled_objects if not uo[1]] - error_msg = ( - "" - if not uninstall_errors - else "and {} failed to uninstall".format(len(uninstall_errors)) - ) + error_msg = "" if not uninstall_errors else "and {} failed to uninstall".format(len(uninstall_errors)) return [ ( "compas_ghpython", - "Uninstalled {} GH User Objects {}".format( - len(uninstalled_objects), error_msg - ), + "Uninstalled {} GH User Objects {}".format(len(uninstalled_objects), error_msg), True, ) ] diff --git a/src/compas_ghpython/utilities/drawing.py b/src/compas_ghpython/utilities/drawing.py index 85caf3ff5954..0332e531c2d9 100644 --- a/src/compas_ghpython/utilities/drawing.py +++ b/src/compas_ghpython/utilities/drawing.py @@ -339,9 +339,7 @@ def draw_spheres(spheres): return rg_sheres -def draw_mesh( - vertices, faces, color=None, vertex_normals=None, texture_coordinates=None -): +def draw_mesh(vertices, faces, color=None, vertex_normals=None, texture_coordinates=None): """Draw mesh in Grasshopper. Parameters @@ -426,9 +424,7 @@ def draw_network(network): points.append({"pos": network.node_coordinates(key)}) lines = [] for u, v in network.edges(): - lines.append( - {"start": network.node_coordinates(u), "end": network.node_coordinates(v)} - ) + lines.append({"start": network.node_coordinates(u), "end": network.node_coordinates(v)}) points_rg = draw_points(points) lines_rg = draw_lines(lines) diff --git a/src/compas_plotters/artists/lineartist.py b/src/compas_plotters/artists/lineartist.py index 9900e6b76c5b..431400b760d9 100644 --- a/src/compas_plotters/artists/lineartist.py +++ b/src/compas_plotters/artists/lineartist.py @@ -134,12 +134,8 @@ def draw(self) -> None: ) self._mpl_line = self.plotter.axes.add_line(line2d) if self.draw_points: - self._start_artist = self.plotter.add( - self.line.start, edgecolor=self.color - ) - self._end_artist = self.plotter.add( - self.line.end, edgecolor=self.color - ) + self._start_artist = self.plotter.add(self.line.start, edgecolor=self.color) + self._end_artist = self.plotter.add(self.line.end, edgecolor=self.color) def redraw(self) -> None: """Update the line using the current geometry and visualization settings. diff --git a/src/compas_plotters/artists/meshartist.py b/src/compas_plotters/artists/meshartist.py index 8249a2ce18af..1513df7ec72d 100644 --- a/src/compas_plotters/artists/meshartist.py +++ b/src/compas_plotters/artists/meshartist.py @@ -137,9 +137,7 @@ def __init__( @property def halfedges(self): if not self._halfedges: - self._halfedges = [ - (u, v) for u in self.mesh.halfedge for v in self.mesh.halfedge[u] - ] + self._halfedges = [(u, v) for u in self.mesh.halfedge for v in self.mesh.halfedge[u]] return self._halfedges @halfedges.setter @@ -149,38 +147,24 @@ def halfedges(self, halfedges): @property def vertex_size(self): if not self._vertex_size: - factor = ( - self.plotter.dpi - if self.sizepolicy == "absolute" - else self.mesh.number_of_vertices() - ) + factor = self.plotter.dpi if self.sizepolicy == "absolute" else self.mesh.number_of_vertices() size = self.default_vertexsize / factor self._vertex_size = {vertex: size for vertex in self.mesh.vertices()} return self._vertex_size @vertex_size.setter def vertex_size(self, vertexsize): - factor = ( - self.plotter.dpi - if self.sizepolicy == "absolute" - else self.mesh.number_of_vertices() - ) + factor = self.plotter.dpi if self.sizepolicy == "absolute" else self.mesh.number_of_vertices() if isinstance(vertexsize, dict): - self.vertex_size.update( - {vertex: size / factor for vertex, size in vertexsize.items()} - ) + self.vertex_size.update({vertex: size / factor for vertex, size in vertexsize.items()}) elif isinstance(vertexsize, (int, float)): - self._vertex_size = { - vertex: vertexsize / factor for vertex in self.mesh.vertices() - } + self._vertex_size = {vertex: vertexsize / factor for vertex in self.mesh.vertices()} @property def halfedge_color(self): if self._halfedge_color is None: self._halfedge_color = { - (u, v): self.default_halfedgecolor - for u in self.mesh.halfedge - for v in self.mesh.halfedge[u] + (u, v): self.default_halfedgecolor for u in self.mesh.halfedge for v in self.mesh.halfedge[u] } return self._halfedge_color @@ -189,11 +173,7 @@ def halfedge_color(self, halfedge_color): if isinstance(halfedge_color, dict): self._halfedge_color = halfedge_color elif is_color_rgb(halfedge_color): - self._halfedge_color = { - (u, v): halfedge_color - for u in self.mesh.halfedge - for v in self.mesh.halfedge[u] - } + self._halfedge_color = {(u, v): halfedge_color for u in self.mesh.halfedge for v in self.mesh.halfedge[u]} @property def zorder_faces(self): @@ -402,16 +382,8 @@ def draw_edges( for edge in self.edges: u, v = edge lines.append([self.vertex_xyz[edge[0]][:2], self.vertex_xyz[edge[1]][:2]]) - colors.append( - self.edge_color.get( - edge, self.edge_color.get((v, u), self.default_edgecolor) - ) - ) - widths.append( - self.edge_width.get( - edge, self.edge_width.get((v, u), self.default_edgewidth) - ) - ) + colors.append(self.edge_color.get(edge, self.edge_color.get((v, u), self.default_edgecolor))) + widths.append(self.edge_width.get(edge, self.edge_width.get((v, u), self.default_edgewidth))) collection = LineCollection( lines, @@ -516,9 +488,7 @@ def draw_faces( edgecolors = [] linewidths = [] for face in self.faces: - data = [ - self.vertex_xyz[vertex][:2] for vertex in self.mesh.face_vertices(face) - ] + data = [self.vertex_xyz[vertex][:2] for vertex in self.mesh.face_vertices(face)] polygons.append(PolygonPatch(data)) facecolors.append(self.face_color.get(face, self.default_facecolor)) edgecolors.append((0, 0, 0)) @@ -660,9 +630,7 @@ def draw_facelabels(self, text: Optional[Dict[int, str]] = None) -> None: if text is None: continue - x, y, _ = centroid_points_xy( - [self.vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)] - ) + x, y, _ = centroid_points_xy([self.vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)]) artist = self.plotter.axes.text( x, diff --git a/src/compas_plotters/artists/networkartist.py b/src/compas_plotters/artists/networkartist.py index ff3ce94587b0..a9a88ab66fc2 100644 --- a/src/compas_plotters/artists/networkartist.py +++ b/src/compas_plotters/artists/networkartist.py @@ -108,26 +108,16 @@ def data(self) -> List[List[float]]: @property def node_size(self): if not self._node_size: - factor = ( - self.plotter.dpi - if self.sizepolicy == "absolute" - else self.network.number_of_nodes() - ) + factor = self.plotter.dpi if self.sizepolicy == "absolute" else self.network.number_of_nodes() size = self.default_nodesize / factor self._node_size = {node: size for node in self.network.nodes()} return self._node_size @node_size.setter def node_size(self, nodesize): - factor = ( - self.plotter.dpi - if self.sizepolicy == "absolute" - else self.network.number_of_nodes() - ) + factor = self.plotter.dpi if self.sizepolicy == "absolute" else self.network.number_of_nodes() if isinstance(nodesize, dict): - self.node_size.update( - {node: size / factor for node, size in nodesize.items()} - ) + self.node_size.update({node: size / factor for node, size in nodesize.items()}) elif isinstance(nodesize, (int, float)): self._node_size = {node: nodesize / factor for node in self.network.nodes()} @@ -230,9 +220,7 @@ def draw_nodes( ) circles.append(circle) - collection = PatchCollection( - circles, match_original=True, zorder=self.zorder_nodes, alpha=1.0 - ) + collection = PatchCollection(circles, match_original=True, zorder=self.zorder_nodes, alpha=1.0) self.plotter.axes.add_collection(collection) self._nodecollection = collection diff --git a/src/compas_plotters/core/drawing.py b/src/compas_plotters/core/drawing.py index 5cec2d621d6b..14a37a8b6447 100644 --- a/src/compas_plotters/core/drawing.py +++ b/src/compas_plotters/core/drawing.py @@ -219,9 +219,7 @@ def create_axes_3d( # ============================================================================== -def draw_points_xy( - points, axes, facecolor="#ffffff", edgecolor="#000000", linewidth=0.5, radius=1.0 -): +def draw_points_xy(points, axes, facecolor="#ffffff", edgecolor="#000000", linewidth=0.5, radius=1.0): """Creates an XY point collection and adds it to the axis. Parameters @@ -387,9 +385,7 @@ def draw_points_3d(points, axes, facecolor="#ffffff", edgecolor="#000000"): # ============================================================================== -def draw_lines_xy( - lines, axes, linewidth=1.0, linestyle="-", color="#000000", alpha=1.0 -): +def draw_lines_xy(lines, axes, linewidth=1.0, linestyle="-", color="#000000", alpha=1.0): """Creates an XY line collection and adds it to the axis. Parameters @@ -762,12 +758,8 @@ def draw_xpolygons_xy(polygons, axes): text = attr.get("text") textcolor = color_to_rgb(attr.get("textcolor", "#000000"), normalize=True) - facecolors.append( - color_to_rgb(attr.get("facecolor", "#ffffff"), normalize=True) - ) - edgecolors.append( - color_to_rgb(attr.get("edgecolor", "#000000"), normalize=True) - ) + facecolors.append(color_to_rgb(attr.get("facecolor", "#ffffff"), normalize=True)) + edgecolors.append(color_to_rgb(attr.get("edgecolor", "#000000"), normalize=True)) linewidths.append(attr.get("edgewidth", 1.0)) patches.append(Polygon([point[0:2] for point in points])) diff --git a/src/compas_plotters/core/helpers.py b/src/compas_plotters/core/helpers.py index 533cf492a6ce..6650d446674c 100644 --- a/src/compas_plotters/core/helpers.py +++ b/src/compas_plotters/core/helpers.py @@ -134,9 +134,7 @@ def plot(self, axes): yspan = self.points[ymax, 1] - self.points[ymin, 1] zspan = self.points[zmax, 2] - self.points[zmin, 2] span = max(xspan, yspan, zspan) - axes.plot( - [self.points[xmin, 0]], [self.points[ymin, 1]], [self.points[zmin, 2]], "w" - ) + axes.plot([self.points[xmin, 0]], [self.points[ymin, 1]], [self.points[zmin, 2]], "w") axes.plot( [self.points[xmin, 0] + span], [self.points[ymin, 1] + span], diff --git a/src/compas_plotters/core/utilities.py b/src/compas_plotters/core/utilities.py index eb7af3381a49..48a9b56ae786 100644 --- a/src/compas_plotters/core/utilities.py +++ b/src/compas_plotters/core/utilities.py @@ -40,9 +40,7 @@ def assert_axes_dimension(axes, dim): bool True if the axes object has dim dimensions. """ - assert get_axes_dimension(axes) == dim, "The provided axes are not {0}D.".format( - dim - ) + assert get_axes_dimension(axes) == dim, "The provided axes are not {0}D.".format(dim) def width_to_dict(width, dictkeys, defval=None): diff --git a/src/compas_plotters/plotter.py b/src/compas_plotters/plotter.py index 6639364902c7..037e3decc28b 100644 --- a/src/compas_plotters/plotter.py +++ b/src/compas_plotters/plotter.py @@ -142,9 +142,7 @@ def viewbox(self, view: Tuple[Tuple[float, float], Tuple[float, float]]): @property def axes(self) -> matplotlib.axes.Axes: if not self._axes: - figure = plt.figure( - facecolor=self.bgcolor, figsize=self.figsize, dpi=self.dpi - ) + figure = plt.figure(facecolor=self.bgcolor, figsize=self.figsize, dpi=self.dpi) axes = figure.add_subplot(111, aspect="equal") if self.viewbox: xmin, xmax = self.viewbox[0] @@ -299,9 +297,7 @@ def add( if not artist: if self.zstack == "natural": zorder = 1000 + len(self._artists) * 100 - artist = PlotterArtist( - item, plotter=self, zorder=zorder, context="Plotter", **kwargs - ) + artist = PlotterArtist(item, plotter=self, zorder=zorder, context="Plotter", **kwargs) else: artist = PlotterArtist(item, plotter=self, context="Plotter", **kwargs) artist.draw() diff --git a/src/compas_rhino/__init__.py b/src/compas_rhino/__init__.py index 385f32a3427a..a650c8b1b02d 100644 --- a/src/compas_rhino/__init__.py +++ b/src/compas_rhino/__init__.py @@ -163,9 +163,7 @@ def _get_rhino_application_folder(version): raise Exception("Unsupported platform") if not os.path.exists(app): - raise Exception( - "The application folder does not exist in this location: {}".format(app) - ) + raise Exception("The application folder does not exist in this location: {}".format(app)) return app @@ -180,17 +178,13 @@ def _get_rhino_appdata_folder(): app = os.path.join(os.getenv("APPDATA"), "McNeel", "Rhinoceros") elif compas.OSX: - app = os.path.join( - os.getenv("HOME"), "Library", "Application Support", "McNeel", "Rhinoceros" - ) + app = os.path.join(os.getenv("HOME"), "Library", "Application Support", "McNeel", "Rhinoceros") else: raise Exception("Unsupported platform") if not os.path.exists(app): - raise Exception( - "The appdata folder does not exist in this location: {}".format(app) - ) + raise Exception("The appdata folder does not exist in this location: {}".format(app)) return app @@ -206,11 +200,7 @@ def _get_rhino_scripts_path(version): scripts_path = os.path.join(appdata, "{}".format(version), "scripts") if not os.path.exists(scripts_path): - raise Exception( - "The scripts folder does not exist in this location: {}".format( - scripts_path - ) - ) + raise Exception("The scripts folder does not exist in this location: {}".format(scripts_path)) return scripts_path @@ -239,11 +229,7 @@ def _get_rhino_managedplugins_path(version): ) if not os.path.exists(managedplugins_path): - raise Exception( - "The Managed Plug-ins folder does not exist in this location: {}".format( - managedplugins_path - ) - ) + raise Exception("The Managed Plug-ins folder does not exist in this location: {}".format(managedplugins_path)) return managedplugins_path @@ -267,11 +253,7 @@ def _get_rhino_plugins_path(version): plugins_path = os.path.join(appdata, "{}".format(version), "Plug-ins") if not os.path.exists(plugins_path): - raise Exception( - "The plugins folder does not exist in this location: {}".format( - plugins_path - ) - ) + raise Exception("The plugins folder does not exist in this location: {}".format(plugins_path)) return plugins_path @@ -320,9 +302,7 @@ def _get_rhino_grasshopperplugin_path(version): raise Exception("Unsupported platform") if not os.path.exists(gh_path): - raise Exception( - "The grasshopper folder does not exist in this location: {}".format(gh_path) - ) + raise Exception("The grasshopper folder does not exist in this location: {}".format(gh_path)) return gh_path @@ -356,6 +336,4 @@ def _get_rhino_ironpython_lib_path_win32(version): # For +6 we should switch to the same path as on windows # which is not in the managed plugins but in the appdata plugins def _get_rhino_ironpython_lib_path_mac(version): - return os.path.join( - _get_rhino_managedplugins_path(version), "RhinoDLR_Python.rhp", "Lib" - ) + return os.path.join(_get_rhino_managedplugins_path(version), "RhinoDLR_Python.rhp", "Lib") diff --git a/src/compas_rhino/artists/circleartist.py b/src/compas_rhino/artists/circleartist.py index ba0bb7c8d2c1..48755a94bf7d 100644 --- a/src/compas_rhino/artists/circleartist.py +++ b/src/compas_rhino/artists/circleartist.py @@ -55,9 +55,7 @@ def draw(self, color=None, show_point=False, show_normal=False): guids = [] if show_point: points = [{"pos": point, "color": color, "name": self.primitive.name}] - guids += compas_rhino.draw_points( - points, layer=self.layer, clear=False, redraw=False - ) + guids += compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False) if show_normal: lines = [ { @@ -68,9 +66,7 @@ def draw(self, color=None, show_point=False, show_normal=False): "name": self.primitive.name, } ] - guids += compas_rhino.draw_lines( - lines, layer=self.layer, clear=False, redraw=False - ) + guids += compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False) circles = [ { "plane": plane, @@ -79,7 +75,5 @@ def draw(self, color=None, show_point=False, show_normal=False): "name": self.primitive.name, } ] - guids += compas_rhino.draw_circles( - circles, layer=self.layer, clear=False, redraw=False - ) + guids += compas_rhino.draw_circles(circles, layer=self.layer, clear=False, redraw=False) return guids diff --git a/src/compas_rhino/artists/curveartist.py b/src/compas_rhino/artists/curveartist.py index ffda2765b80e..aa63a5bea685 100644 --- a/src/compas_rhino/artists/curveartist.py +++ b/src/compas_rhino/artists/curveartist.py @@ -43,6 +43,4 @@ def draw(self, color=None): """ color = Color.coerce(color) or self.color curves = [{"curve": self.curve, "color": color.rgb255, "name": self.curve.name}] - return compas_rhino.draw_curves( - curves, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_curves(curves, layer=self.layer, clear=False, redraw=False) diff --git a/src/compas_rhino/artists/frameartist.py b/src/compas_rhino/artists/frameartist.py index eb9426b8de57..2af86a83e333 100644 --- a/src/compas_rhino/artists/frameartist.py +++ b/src/compas_rhino/artists/frameartist.py @@ -83,10 +83,6 @@ def draw(self): "arrow": "end", }, ] - guids = compas_rhino.draw_points( - points, layer=self.layer, clear=False, redraw=False - ) - guids += compas_rhino.draw_lines( - lines, layer=self.layer, clear=False, redraw=False - ) + guids = compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False) + guids += compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False) return guids diff --git a/src/compas_rhino/artists/lineartist.py b/src/compas_rhino/artists/lineartist.py index 9c6307a3d650..7a1b7fd0dbb7 100644 --- a/src/compas_rhino/artists/lineartist.py +++ b/src/compas_rhino/artists/lineartist.py @@ -53,13 +53,7 @@ def draw(self, color=None, show_points=False): {"pos": start, "color": color, "name": self.primitive.name}, {"pos": end, "color": color, "name": self.primitive.name}, ] - guids += compas_rhino.draw_points( - points, layer=self.layer, clear=False, redraw=False - ) - lines = [ - {"start": start, "end": end, "color": color, "name": self.primitive.name} - ] - guids += compas_rhino.draw_lines( - lines, layer=self.layer, clear=False, redraw=False - ) + guids += compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False) + lines = [{"start": start, "end": end, "color": color, "name": self.primitive.name}] + guids += compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False) return guids diff --git a/src/compas_rhino/artists/meshartist.py b/src/compas_rhino/artists/meshartist.py index 9e2841846402..724906c6059c 100644 --- a/src/compas_rhino/artists/meshartist.py +++ b/src/compas_rhino/artists/meshartist.py @@ -86,9 +86,7 @@ def clear_vertexnormals(self): None """ - guids = compas_rhino.get_objects( - name="{}.vertexnormal.*".format(self.mesh.name) - ) + guids = compas_rhino.get_objects(name="{}.vertexnormal.*".format(self.mesh.name)) compas_rhino.delete_objects(guids, purge=True) def clear_facenormals(self): @@ -165,10 +163,7 @@ def draw(self, color=None, disjoint=False): vertex_index = self.mesh.vertex_index() vertex_xyz = self.vertex_xyz vertices = [vertex_xyz[vertex] for vertex in self.mesh.vertices()] - faces = [ - [vertex_index[vertex] for vertex in self.mesh.face_vertices(face)] - for face in self.mesh.faces() - ] + faces = [[vertex_index[vertex] for vertex in self.mesh.face_vertices(face)] for face in self.mesh.faces()] layer = self.layer name = "{}.mesh".format(self.mesh.name) guid = compas_rhino.draw_mesh( @@ -211,9 +206,7 @@ def draw_vertices(self, vertices=None, color=None): "color": self.vertex_color[vertex].rgb255, } ) - return compas_rhino.draw_points( - points, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False) def draw_edges(self, edges=None, color=None): """Draw a selection of edges. @@ -246,9 +239,7 @@ def draw_edges(self, edges=None, color=None): "name": "{}.edge.{}-{}".format(self.mesh.name, *edge), } ) - guids = compas_rhino.draw_lines( - lines, layer=self.layer, clear=False, redraw=False - ) + guids = compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False) return guids def draw_faces(self, faces=None, color=None, join_faces=False): @@ -278,16 +269,12 @@ def draw_faces(self, faces=None, color=None, join_faces=False): for face in faces: facets.append( { - "points": [ - vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face) - ], + "points": [vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)], "name": "{}.face.{}".format(self.mesh.name, face), "color": self.face_color[face].rgb255, } ) - guids = compas_rhino.draw_faces( - facets, layer=self.layer, clear=False, redraw=False - ) + guids = compas_rhino.draw_faces(facets, layer=self.layer, clear=False, redraw=False) if join_faces: guid = compas_rhino.rs.JoinMeshes(guids, delete_input=True) compas_rhino.rs.ObjectLayer(guid, self.layer) @@ -337,9 +324,7 @@ def draw_vertexnormals(self, vertices=None, color=(0, 255, 0), scale=1.0): "arrow": "end", } ) - return compas_rhino.draw_lines( - lines, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False) def draw_facenormals(self, faces=None, color=(0, 255, 255), scale=1.0): """Draw the normals of the faces. @@ -365,9 +350,7 @@ def draw_facenormals(self, faces=None, color=(0, 255, 255), scale=1.0): faces = faces or self.faces lines = [] for face in faces: - a = centroid_points( - [vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)] - ) + a = centroid_points([vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)]) n = self.mesh.face_normal(face) b = add_vectors(a, scale_vector(n, scale)) lines.append( @@ -379,9 +362,7 @@ def draw_facenormals(self, faces=None, color=(0, 255, 255), scale=1.0): "arrow": "end", } ) - return compas_rhino.draw_lines( - lines, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False) # ========================================================================== # draw labels @@ -414,9 +395,7 @@ def draw_vertexlabels(self, text=None): "text": self.vertex_text[vertex], } ) - return compas_rhino.draw_labels( - labels, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False) def draw_edgelabels(self, text=None): """Draw labels for a selection of edges. @@ -445,9 +424,7 @@ def draw_edgelabels(self, text=None): "text": self.edge_text[edge], } ) - return compas_rhino.draw_labels( - labels, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False) def draw_facelabels(self, text=None): """Draw labels for a selection of faces. @@ -470,14 +447,10 @@ def draw_facelabels(self, text=None): for face in self.face_text: labels.append( { - "pos": centroid_points( - [vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)] - ), + "pos": centroid_points([vertex_xyz[vertex] for vertex in self.mesh.face_vertices(face)]), "name": "{}.facelabel.{}".format(self.mesh.name, face), "color": self.face_color[face].rgb255, "text": self.face_text[face], } ) - return compas_rhino.draw_labels( - labels, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False) diff --git a/src/compas_rhino/artists/networkartist.py b/src/compas_rhino/artists/networkartist.py index 56425a42bccd..906cb672f0d7 100644 --- a/src/compas_rhino/artists/networkartist.py +++ b/src/compas_rhino/artists/networkartist.py @@ -72,9 +72,7 @@ def clear_nodelabels(self): None """ - guids = compas_rhino.get_objects( - name="{}.nodexlabel.*".format(self.network.name) - ) + guids = compas_rhino.get_objects(name="{}.nodexlabel.*".format(self.network.name)) compas_rhino.delete_objects(guids, purge=True) def clear_edgelabels(self): @@ -85,9 +83,7 @@ def clear_edgelabels(self): None """ - guids = compas_rhino.get_objects( - name="{}.edgelabel.*".format(self.network.name) - ) + guids = compas_rhino.get_objects(name="{}.edgelabel.*".format(self.network.name)) compas_rhino.delete_objects(guids, purge=True) # ========================================================================== @@ -153,9 +149,7 @@ def draw_nodes(self, nodes=None, color=None): "color": self.node_color[node].rgb255, } ) - return compas_rhino.draw_points( - points, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False) def draw_edges(self, edges=None, color=None): """Draw a selection of edges. @@ -189,9 +183,7 @@ def draw_edges(self, edges=None, color=None): "name": "{}.edge.{}-{}".format(self.network.name, u, v), } ) - return compas_rhino.draw_lines( - lines, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False) # ========================================================================== # draw labels @@ -224,9 +216,7 @@ def draw_nodelabels(self, text=None): "text": self.node_text[node], } ) - return compas_rhino.draw_labels( - labels, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False) def draw_edgelabels(self, text=None): """Draw labels for a selection of edges. @@ -256,6 +246,4 @@ def draw_edgelabels(self, text=None): "text": self.edge_text[edge], } ) - return compas_rhino.draw_labels( - labels, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False) diff --git a/src/compas_rhino/artists/pointartist.py b/src/compas_rhino/artists/pointartist.py index b5f2cd23b041..fb9ca67ff4ad 100644 --- a/src/compas_rhino/artists/pointartist.py +++ b/src/compas_rhino/artists/pointartist.py @@ -49,7 +49,5 @@ def draw(self, color=None): "name": self.primitive.name, } ] - guids = compas_rhino.draw_points( - points, layer=self.layer, clear=False, redraw=False - ) + guids = compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False) return guids diff --git a/src/compas_rhino/artists/polygonartist.py b/src/compas_rhino/artists/polygonartist.py index caa7da6ba19e..feefc90df938 100644 --- a/src/compas_rhino/artists/polygonartist.py +++ b/src/compas_rhino/artists/polygonartist.py @@ -52,13 +52,8 @@ def draw(self, color=None, show_points=False, show_edges=False, show_face=True): _points = map(list, self.primitive.points) guids = [] if show_points: - points = [ - {"pos": point, "color": color, "name": self.primitive.name} - for point in _points - ] - guids += compas_rhino.draw_points( - points, layer=self.layer, clear=False, redraw=False - ) + points = [{"pos": point, "color": color, "name": self.primitive.name} for point in _points] + guids += compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False) if show_edges: lines = [ { @@ -69,14 +64,8 @@ def draw(self, color=None, show_points=False, show_edges=False, show_face=True): } for a, b in self.primitive.lines ] - guids += compas_rhino.draw_lines( - lines, layer=self.layer, clear=False, redraw=False - ) + guids += compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False) if show_face: - polygons = [ - {"points": _points, "color": color, "name": self.primitive.name} - ] - guids += compas_rhino.draw_faces( - polygons, layer=self.layer, clear=False, redraw=False - ) + polygons = [{"points": _points, "color": color, "name": self.primitive.name}] + guids += compas_rhino.draw_faces(polygons, layer=self.layer, clear=False, redraw=False) return guids diff --git a/src/compas_rhino/artists/polylineartist.py b/src/compas_rhino/artists/polylineartist.py index 8d58b9cd6f66..85af4e263666 100644 --- a/src/compas_rhino/artists/polylineartist.py +++ b/src/compas_rhino/artists/polylineartist.py @@ -48,15 +48,8 @@ def draw(self, color=None, show_points=False): _points = map(list, self.primitive.points) guids = [] if show_points: - points = [ - {"pos": point, "color": color, "name": self.primitive.name} - for point in _points - ] - guids += compas_rhino.draw_points( - points, layer=self.layer, clear=False, redraw=False - ) + points = [{"pos": point, "color": color, "name": self.primitive.name} for point in _points] + guids += compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False) polylines = [{"points": _points, "color": color, "name": self.primitive.name}] - guids += compas_rhino.draw_polylines( - polylines, layer=self.layer, clear=False, redraw=False - ) + guids += compas_rhino.draw_polylines(polylines, layer=self.layer, clear=False, redraw=False) return guids diff --git a/src/compas_rhino/artists/robotmodelartist.py b/src/compas_rhino/artists/robotmodelartist.py index e9a6adfca463..8f2f1c7d5145 100644 --- a/src/compas_rhino/artists/robotmodelartist.py +++ b/src/compas_rhino/artists/robotmodelartist.py @@ -220,11 +220,7 @@ def _add_mesh_to_doc(self, mesh): mesh.UserDictionary["MeshColor.B"], mesh.UserDictionary["MeshColor.A"], ] - name = ( - mesh.UserDictionary["MeshName"] - if "MeshName" in mesh.UserDictionary - else None - ) + name = mesh.UserDictionary["MeshName"] if "MeshName" in mesh.UserDictionary else None obj = sc.doc.Objects.Find(guid) @@ -235,9 +231,7 @@ def _add_mesh_to_doc(self, mesh): attr.ObjectColor = Color.FromArgb(a, r, g, b) attr.ColorSource = ColorFromObject - material_name = "robotmodelartist.{:.2f}_{:.2f}_{:.2f}_{:.2f}".format( - r, g, b, a - ) + material_name = "robotmodelartist.{:.2f}_{:.2f}_{:.2f}_{:.2f}".format(r, g, b, a) material_index = sc.doc.Materials.Find(material_name, True) # Material does not exist, create it diff --git a/src/compas_rhino/artists/surfaceartist.py b/src/compas_rhino/artists/surfaceartist.py index 64c224217941..f267331f59fe 100644 --- a/src/compas_rhino/artists/surfaceartist.py +++ b/src/compas_rhino/artists/surfaceartist.py @@ -42,9 +42,5 @@ def draw(self, color=None): """ color = Color.coerce(color) or self.color - surfaces = [ - {"surface": self.surface, "color": color.rgb255, "name": self.surface.name} - ] - return compas_rhino.draw_surfaces( - surfaces, layer=self.layer, clear=False, redraw=False - ) + surfaces = [{"surface": self.surface, "color": color.rgb255, "name": self.surface.name}] + return compas_rhino.draw_surfaces(surfaces, layer=self.layer, clear=False, redraw=False) diff --git a/src/compas_rhino/artists/vectorartist.py b/src/compas_rhino/artists/vectorartist.py index c66210b6f892..938741b84b6a 100644 --- a/src/compas_rhino/artists/vectorartist.py +++ b/src/compas_rhino/artists/vectorartist.py @@ -57,9 +57,7 @@ def draw(self, color=None, point=None, show_point=False): guids = [] if show_point: points = [{"pos": start, "color": color, "name": self.primitive.name}] - guids += compas_rhino.draw_points( - points, layer=self.layer, clear=False, redraw=False - ) + guids += compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False) lines = [ { "start": start, @@ -69,7 +67,5 @@ def draw(self, color=None, point=None, show_point=False): "name": self.primitive.name, } ] - guids += compas_rhino.draw_lines( - lines, layer=self.layer, clear=False, redraw=False - ) + guids += compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False) return guids diff --git a/src/compas_rhino/artists/volmeshartist.py b/src/compas_rhino/artists/volmeshartist.py index 73b67bf7a14a..3772bf77eea7 100644 --- a/src/compas_rhino/artists/volmeshartist.py +++ b/src/compas_rhino/artists/volmeshartist.py @@ -93,9 +93,7 @@ def clear_vertexlabels(self): None """ - guids = compas_rhino.get_objects( - name="{}.vertexlabel.*".format(self.volmesh.name) - ) + guids = compas_rhino.get_objects(name="{}.vertexlabel.*".format(self.volmesh.name)) compas_rhino.delete_objects(guids, purge=True) def clear_edgelabels(self): @@ -106,9 +104,7 @@ def clear_edgelabels(self): None """ - guids = compas_rhino.get_objects( - name="{}.edgelabel.*".format(self.volmesh.name) - ) + guids = compas_rhino.get_objects(name="{}.edgelabel.*".format(self.volmesh.name)) compas_rhino.delete_objects(guids, purge=True) def clear_facelabels(self): @@ -119,9 +115,7 @@ def clear_facelabels(self): None """ - guids = compas_rhino.get_objects( - name="{}.facelabel.*".format(self.volmesh.name) - ) + guids = compas_rhino.get_objects(name="{}.facelabel.*".format(self.volmesh.name)) compas_rhino.delete_objects(guids, purge=True) # ========================================================================== @@ -179,9 +173,7 @@ def draw_vertices(self, vertices=None, color=None): "color": self.vertex_color[vertex].rgb255, } ) - return compas_rhino.draw_points( - points, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False) def draw_edges(self, edges=None, color=None): """Draw a selection of edges. @@ -214,9 +206,7 @@ def draw_edges(self, edges=None, color=None): "name": "{}.edge.{}-{}".format(self.volmesh.name, *edge), } ) - return compas_rhino.draw_lines( - lines, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False) def draw_faces(self, faces=None, color=None): """Draw a selection of faces. @@ -243,17 +233,12 @@ def draw_faces(self, faces=None, color=None): for face in faces: facets.append( { - "points": [ - vertex_xyz[vertex] - for vertex in self.volmesh.halfface_vertices(face) - ], + "points": [vertex_xyz[vertex] for vertex in self.volmesh.halfface_vertices(face)], "name": "{}.face.{}".format(self.volmesh.name, face), "color": self.face_color[face].rgb255, } ) - return compas_rhino.draw_faces( - facets, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_faces(facets, layer=self.layer, clear=False, redraw=False) def draw_cells(self, cells=None, color=None): """Draw a selection of cells. @@ -281,14 +266,9 @@ def draw_cells(self, cells=None, color=None): for cell in cells: vertices = self.volmesh.cell_vertices(cell) faces = self.volmesh.cell_faces(cell) - vertex_index = dict( - (vertex, index) for index, vertex in enumerate(vertices) - ) + vertex_index = dict((vertex, index) for index, vertex in enumerate(vertices)) vertices = [vertex_xyz[vertex] for vertex in vertices] - faces = [ - [vertex_index[vertex] for vertex in self.halfface_vertices(face)] - for face in faces - ] + faces = [[vertex_index[vertex] for vertex in self.halfface_vertices(face)] for face in faces] guid = compas_rhino.draw_mesh( vertices, faces, @@ -331,9 +311,7 @@ def draw_vertexlabels(self, text=None): "text": self.vertex_text[vertex], } ) - return compas_rhino.draw_labels( - labels, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False) def draw_edgelabels(self, text=None): """Draw labels for a selection of edges. @@ -362,9 +340,7 @@ def draw_edgelabels(self, text=None): "text": self.edge_text[edge], } ) - return compas_rhino.draw_labels( - labels, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False) def draw_facelabels(self, text=None): """Draw labels for a selection of faces. @@ -387,20 +363,13 @@ def draw_facelabels(self, text=None): for face in self.face_text: labels.append( { - "pos": centroid_points( - [ - vertex_xyz[vertex] - for vertex in self.volmesh.face_vertices(face) - ] - ), + "pos": centroid_points([vertex_xyz[vertex] for vertex in self.volmesh.face_vertices(face)]), "name": "{}.facelabel.{}".format(self.volmesh.name, face), "color": self.face_color[face].rgb255, "text": self.face_text[face], } ) - return compas_rhino.draw_labels( - labels, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False) def draw_celllabels(self, text=None): """Draw labels for cells. @@ -423,17 +392,10 @@ def draw_celllabels(self, text=None): for cell in self.cell_text: labels.append( { - "pos": centroid_points( - [ - vertex_xyz[vertex] - for vertex in self.volmesh.cell_vertices(cell) - ] - ), + "pos": centroid_points([vertex_xyz[vertex] for vertex in self.volmesh.cell_vertices(cell)]), "name": "{}.facelabel.{}".format(self.volmesh.name, cell), "color": self.cell_color[cell].rgb255, "text": self.cell_text[cell], } ) - return compas_rhino.draw_labels( - labels, layer=self.layer, clear=False, redraw=False - ) + return compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False) diff --git a/src/compas_rhino/conduits/faces.py b/src/compas_rhino/conduits/faces.py index a49bd92250a9..9620deca65d3 100644 --- a/src/compas_rhino/conduits/faces.py +++ b/src/compas_rhino/conduits/faces.py @@ -68,9 +68,7 @@ def color(self, color): return if not is_sequence_of_iterable(color): color = [color] - color = [ - FromArgb(*c) for c in iterable_like(self.faces, color, self.default_color) - ] + color = [FromArgb(*c) for c in iterable_like(self.faces, color, self.default_color)] self._color = color def DrawForeground(self, e): diff --git a/src/compas_rhino/conduits/labels.py b/src/compas_rhino/conduits/labels.py index 775aec3c5a39..e6733db79847 100644 --- a/src/compas_rhino/conduits/labels.py +++ b/src/compas_rhino/conduits/labels.py @@ -80,9 +80,7 @@ def color(self, color): color = [color] color = [ (FromArgb(*bg), FromArgb(*text)) - for bg, text in iterable_like( - self.labels, color, (self.default_color, self.default_textcolor) - ) + for bg, text in iterable_like(self.labels, color, (self.default_color, self.default_textcolor)) ] self._color = color @@ -103,6 +101,4 @@ def DrawForeground(self, e): color, textcolor = self.color[i] e.Display.DrawDot(Point3d(*pos), text, color, textcolor) else: - e.Display.DrawDot( - Point3d(*pos), text, self.default_color, self.default_textcolor - ) + e.Display.DrawDot(Point3d(*pos), text, self.default_color, self.default_textcolor) diff --git a/src/compas_rhino/conduits/lines.py b/src/compas_rhino/conduits/lines.py index 1c15268a88c9..4f7140a84fb9 100644 --- a/src/compas_rhino/conduits/lines.py +++ b/src/compas_rhino/conduits/lines.py @@ -91,9 +91,7 @@ def color(self, color): color = color or self.default_color if not is_sequence_of_iterable(color): color = [color] - self._color = [ - FromArgb(*c) for c in iterable_like(self.lines, color, self.default_color) - ] + self._color = [FromArgb(*c) for c in iterable_like(self.lines, color, self.default_color)] def DrawForeground(self, e): """Draw the lines. @@ -107,7 +105,5 @@ def DrawForeground(self, e): None """ - for (start, end), color, thickness in zip( - self.lines, self.color, self.thickness - ): + for (start, end), color, thickness in zip(self.lines, self.color, self.thickness): e.Display.DrawLine(Point3d(*start), Point3d(*end), color, thickness) diff --git a/src/compas_rhino/conduits/points.py b/src/compas_rhino/conduits/points.py index af22552ad45b..7aab711c6a5d 100644 --- a/src/compas_rhino/conduits/points.py +++ b/src/compas_rhino/conduits/points.py @@ -92,10 +92,7 @@ def color(self, color): color = color or self.default_color if not is_sequence_of_iterable(color): color = [color] - color = [ - FromArgb(*color_to_rgb(c)) - for c in iterable_like(self.points, color, self.default_color) - ] + color = [FromArgb(*color_to_rgb(c)) for c in iterable_like(self.points, color, self.default_color)] self._color = color def DrawForeground(self, e): diff --git a/src/compas_rhino/conversions/_primitives.py b/src/compas_rhino/conversions/_primitives.py index 7d549c47da27..301107c38854 100644 --- a/src/compas_rhino/conversions/_primitives.py +++ b/src/compas_rhino/conversions/_primitives.py @@ -172,9 +172,7 @@ def frame_to_rhino(frame): :rhino:`Rhino.Geometry.Plane` """ - return RhinoPlane( - point_to_rhino(frame[0]), vector_to_rhino(frame[1]), vector_to_rhino(frame[2]) - ) + return RhinoPlane(point_to_rhino(frame[0]), vector_to_rhino(frame[1]), vector_to_rhino(frame[2])) def circle_to_compas(circle): diff --git a/src/compas_rhino/conversions/_surfaces.py b/src/compas_rhino/conversions/_surfaces.py index 22189044a909..7b5357c0337b 100644 --- a/src/compas_rhino/conversions/_surfaces.py +++ b/src/compas_rhino/conversions/_surfaces.py @@ -86,9 +86,7 @@ def data_to_rhino_surface(data): nu = len(points[0]) nv = len(points) - nurbs = RhinoNurbsSurface.Create( - 3, False, data["u_degree"] + 1, data["v_degree"] + 1, nu, nv - ) + nurbs = RhinoNurbsSurface.Create(3, False, data["u_degree"] + 1, data["v_degree"] + 1, nu, nv) for i in range(nu): for j in range(nv): nurbs.Points.SetPoint(i, j, point_to_rhino(points[j][i])) diff --git a/src/compas_rhino/conversions/box.py b/src/compas_rhino/conversions/box.py index 2cb2302c5fe0..e197aecf73c8 100644 --- a/src/compas_rhino/conversions/box.py +++ b/src/compas_rhino/conversions/box.py @@ -1,17 +1,15 @@ -from __future__ import print_function from __future__ import absolute_import from __future__ import division +from __future__ import print_function import Rhino from compas.geometry import Box from ._exceptions import ConversionError - -from ._shapes import box_to_rhino -from ._shapes import box_to_compas - from ._geometry import RhinoGeometry +from ._shapes import box_to_compas +from ._shapes import box_to_rhino class RhinoBox(RhinoGeometry): @@ -43,9 +41,7 @@ def geometry(self, geometry): elif isinstance(geometry, Box): geometry = box_to_rhino(geometry) else: - raise ConversionError( - "Geometry object cannot be converted to a box: {}".format(geometry) - ) + raise ConversionError("Geometry object cannot be converted to a box: {}".format(geometry)) self._geometry = geometry diff --git a/src/compas_rhino/conversions/cone.py b/src/compas_rhino/conversions/cone.py index c11eb68c43a2..2488cb4127e1 100644 --- a/src/compas_rhino/conversions/cone.py +++ b/src/compas_rhino/conversions/cone.py @@ -51,9 +51,7 @@ def geometry(self, geometry): elif isinstance(geometry, Cone): geometry = cone_to_rhino(geometry) else: - raise ConversionError( - "Geometry object cannot be converted to a cone: {}".format(geometry) - ) + raise ConversionError("Geometry object cannot be converted to a cone: {}".format(geometry)) self._geometry = geometry def to_compas(self): diff --git a/src/compas_rhino/conversions/cylinder.py b/src/compas_rhino/conversions/cylinder.py index 9d8f43923ceb..6fac30e2e601 100644 --- a/src/compas_rhino/conversions/cylinder.py +++ b/src/compas_rhino/conversions/cylinder.py @@ -40,9 +40,7 @@ def geometry(self, geometry): geometry = geometry.ToBrep() if isinstance(geometry, Rhino.Geometry.Brep): if geometry.Faces.Count > 3: - raise ConversionError( - "Object brep cannot be converted to a cylinder." - ) + raise ConversionError("Object brep cannot be converted to a cylinder.") faces = geometry.Faces geometry = None for face in faces: @@ -51,17 +49,11 @@ def geometry(self, geometry): if result: break if not geometry: - raise ConversionError( - "Object brep cannot be converted to a cylinder." - ) + raise ConversionError("Object brep cannot be converted to a cylinder.") elif isinstance(geometry, Cylinder): geometry = cylinder_to_rhino(geometry) else: - raise ConversionError( - "Geometry object cannot be converted to a cylinder: {}".format( - geometry - ) - ) + raise ConversionError("Geometry object cannot be converted to a cylinder: {}".format(geometry)) self._geometry = geometry def to_compas(self): diff --git a/src/compas_rhino/conversions/mesh.py b/src/compas_rhino/conversions/mesh.py index 5702787a6194..de8dba9e14de 100644 --- a/src/compas_rhino/conversions/mesh.py +++ b/src/compas_rhino/conversions/mesh.py @@ -24,9 +24,7 @@ def vertices(self): def faces(self): if self.geometry: faces = [ - [face.A, face.B, face.C] - if face.IsTriangle - else [face.A, face.B, face.C, face.D] + [face.A, face.B, face.C] if face.IsTriangle else [face.A, face.B, face.C, face.D] for face in self.geometry.Faces ] else: @@ -38,9 +36,7 @@ def vertexnormals(self): if self.geometry: # self.geometry.ComputeNormals() # self.geometry.UnitizeNormals() - normals = [ - [vector.X, vector.Y, vector.Z] for vector in self.geometry.Normals - ] + normals = [[vector.X, vector.Y, vector.Z] for vector in self.geometry.Normals] else: normals = [] return normals @@ -50,9 +46,7 @@ def facenormals(self): if self.geometry: # self.geometry.ComputeFaceNormals() # self.geometry.UnitizeFaceNormals() - normals = [ - [vector.X, vector.Y, vector.Z] for vector in self.geometry.FaceNormals - ] + normals = [[vector.X, vector.Y, vector.Z] for vector in self.geometry.FaceNormals] else: normals = [] return normals @@ -60,9 +54,7 @@ def facenormals(self): @property def vertexcolors(self): if self.geometry: - colors = [ - [color.R, color.G, color.B] for color in self.geometry.VertexColors - ] + colors = [[color.R, color.G, color.B] for color in self.geometry.VertexColors] else: colors = [] return colors @@ -104,9 +96,7 @@ def to_compas(self, cls=None): mesh = cls() for vertex in self.geometry.Vertices: - mesh.add_vertex( - attr_dict=dict(x=float(vertex.X), y=float(vertex.Y), z=float(vertex.Z)) - ) + mesh.add_vertex(attr_dict=dict(x=float(vertex.X), y=float(vertex.Y), z=float(vertex.Z))) for face in self.geometry.Faces: if face.A == face.D or face.C == face.D: @@ -134,9 +124,7 @@ def closest_point(self, point, maxdist=0.0): list The XYZ coordinates of the closest point. """ - face, point = self.geometry.ClosestPoint( - Rhino.Geometry.Point3d(*point), maxdist - ) + face, point = self.geometry.ClosestPoint(Rhino.Geometry.Point3d(*point), maxdist) return list(point) def closest_points(self, points, maxdist=None): diff --git a/src/compas_rhino/conversions/sphere.py b/src/compas_rhino/conversions/sphere.py index 97b9c215c940..bb772c48e77b 100644 --- a/src/compas_rhino/conversions/sphere.py +++ b/src/compas_rhino/conversions/sphere.py @@ -38,27 +38,17 @@ def geometry(self, geometry): if not isinstance(geometry, Rhino.Geometry.Sphere): if isinstance(geometry, Rhino.Geometry.Brep): if geometry.Faces.Count != 1: - raise ConversionError( - "Object brep cannot be converted to a sphere." - ) + raise ConversionError("Object brep cannot be converted to a sphere.") face = geometry.Faces.Item[0] if not face.IsSphere(): - raise ConversionError( - "Object brep cannot be converted to a sphere." - ) + raise ConversionError("Object brep cannot be converted to a sphere.") result, geometry = face.TryGetSphere() if not result: - raise ConversionError( - "Object brep cannot be converted to a sphere." - ) + raise ConversionError("Object brep cannot be converted to a sphere.") elif isinstance(geometry, Sphere): geometry = sphere_to_rhino(geometry) else: - raise ConversionError( - "Geometry object cannot be converted to a sphere: {}".format( - geometry - ) - ) + raise ConversionError("Geometry object cannot be converted to a sphere: {}".format(geometry)) self._geometry = geometry def to_compas(self): diff --git a/src/compas_rhino/conversions/surface.py b/src/compas_rhino/conversions/surface.py index 5d04219ca323..52ef2710355e 100644 --- a/src/compas_rhino/conversions/surface.py +++ b/src/compas_rhino/conversions/surface.py @@ -40,9 +40,7 @@ def geometry(self, geometry): if not isinstance(geometry, Rhino.Geometry.Surface): if not isinstance(geometry, Rhino.Geometry.Brep): raise TypeError( - "Geometry cannot be interpreted as a `Rhino.Geometry.Surface`: {}".format( - type(geometry) - ) + "Geometry cannot be interpreted as a `Rhino.Geometry.Surface`: {}".format(type(geometry)) ) self._geometry = geometry @@ -63,9 +61,7 @@ def to_compas(self): brep = Rhino.Geometry.Brep.TryConvertBrep(self.geometry) if brep.Surfaces.Count > 1: - raise ConversionError( - "Conversion of a BRep with multiple underlying surface is currently not supported." - ) + raise ConversionError("Conversion of a BRep with multiple underlying surface is currently not supported.") for geometry in brep.Surfaces: return RhinoNurbsSurface.from_rhino(geometry) @@ -243,9 +239,7 @@ def closest_point(self, xyz): The XYZ coordinates of the closest point on the surface. """ - return compas_rhino.rs.EvaluateSurface( - self.guid, *compas_rhino.rs.SurfaceClosestPoint(self.guid, xyz) - ) + return compas_rhino.rs.EvaluateSurface(self.guid, *compas_rhino.rs.SurfaceClosestPoint(self.guid, xyz)) def closest_points(self, points): return [self.closest_point(point) for point in points] diff --git a/src/compas_rhino/forms/etoforms/propertylist.py b/src/compas_rhino/forms/etoforms/propertylist.py index fc38c6b565a6..bbb7b8bd9087 100644 --- a/src/compas_rhino/forms/etoforms/propertylist.py +++ b/src/compas_rhino/forms/etoforms/propertylist.py @@ -23,9 +23,7 @@ def __init__(self, names, values, title="Properties", width=400, height=600): self.table = table = Eto.Forms.GridView() table.ShowHeader = True - table.DataStore = [ - [name, value] for name, value in zip(self.names, self.values) - ] + table.DataStore = [[name, value] for name, value in zip(self.names, self.values)] c1 = Eto.Forms.GridColumn() c1.HeaderText = "Name" diff --git a/src/compas_rhino/forms/etoforms/settings.py b/src/compas_rhino/forms/etoforms/settings.py index 52001dff1216..ebeb5af7651a 100644 --- a/src/compas_rhino/forms/etoforms/settings.py +++ b/src/compas_rhino/forms/etoforms/settings.py @@ -28,9 +28,7 @@ def __init__(self, settings, title="Settings"): self.table = table = Eto.Forms.GridView() table.ShowHeader = True - table.DataStore = [ - [name, value] for name, value in zip(self.names, self.values) - ] + table.DataStore = [[name, value] for name, value in zip(self.names, self.values)] table.Height = 300 c1 = Eto.Forms.GridColumn() diff --git a/src/compas_rhino/forms/slider.py b/src/compas_rhino/forms/slider.py index ab378f4dd3e8..4813169181d5 100644 --- a/src/compas_rhino/forms/slider.py +++ b/src/compas_rhino/forms/slider.py @@ -65,9 +65,7 @@ def init(self): trackbar.Scroll += System.EventHandler(self.on_scroll) self.Controls.Add(textbox) self.Controls.Add(trackbar) - self.ClientSize = Size( - 10 + textbox.Width + 10 + trackbar.Width + 10, trackbar.Height + 10 - ) + self.ClientSize = Size(10 + textbox.Width + 10 + trackbar.Width + 10, trackbar.Height + 10) self.textbox = textbox self.trackbar = trackbar diff --git a/src/compas_rhino/geometry/booleans/__init__.py b/src/compas_rhino/geometry/booleans/__init__.py index 9d16cd984cf2..4645c4b6c0a6 100644 --- a/src/compas_rhino/geometry/booleans/__init__.py +++ b/src/compas_rhino/geometry/booleans/__init__.py @@ -35,9 +35,7 @@ def boolean_union_mesh_mesh(A, B, remesh=False): The faces of the boolean union. """ - return _boolean_operation( - A, B, lambda a, b: Rhino.Geometry.Mesh.CreateBooleanUnion([a, b]) - ) + return _boolean_operation(A, B, lambda a, b: Rhino.Geometry.Mesh.CreateBooleanUnion([a, b])) @plugin(category="booleans", requires=["Rhino"]) @@ -61,9 +59,7 @@ def boolean_difference_mesh_mesh(A, B, remesh=False): The faces of the boolean difference. """ - return _boolean_operation( - A, B, lambda a, b: Rhino.Geometry.Mesh.CreateBooleanDifference([a], [b]) - ) + return _boolean_operation(A, B, lambda a, b: Rhino.Geometry.Mesh.CreateBooleanDifference([a], [b])) @plugin(category="booleans", requires=["Rhino"]) @@ -87,9 +83,7 @@ def boolean_intersection_mesh_mesh(A, B, remesh=False): The faces of the boolean intersection. """ - return _boolean_operation( - A, B, lambda a, b: Rhino.Geometry.Mesh.CreateBooleanIntersection([a], [b]) - ) + return _boolean_operation(A, B, lambda a, b: Rhino.Geometry.Mesh.CreateBooleanIntersection([a], [b])) def _boolean_operation(A, B, method): diff --git a/src/compas_rhino/geometry/brep/brep.py b/src/compas_rhino/geometry/brep/brep.py index f8227c7f82be..37628cbb7388 100644 --- a/src/compas_rhino/geometry/brep/brep.py +++ b/src/compas_rhino/geometry/brep/brep.py @@ -279,9 +279,7 @@ def from_boolean_union(cls, breps_a, breps_b): if not isinstance(breps_b, list): breps_b = [breps_b] - resulting_breps = Rhino.Geometry.Brep.CreateBooleanUnion( - [b.native_brep for b in breps_a + breps_b], TOLERANCE - ) + resulting_breps = Rhino.Geometry.Brep.CreateBooleanUnion([b.native_brep for b in breps_a + breps_b], TOLERANCE) return [RhinoBrep.from_brep(brep) for brep in resulting_breps] @classmethod @@ -347,9 +345,7 @@ def _create_native_brep(self, faces): for face in faces: rhino_face, rhino_surface = self._create_brep_face(face) for loop in face.loops: - rhino_loop = self._brep.Loops.Add( - Rhino.Geometry.BrepLoopType.Outer, rhino_face - ) + rhino_loop = self._brep.Loops.Add(Rhino.Geometry.BrepLoopType.Outer, rhino_face) for edge in loop.edges: start_vertex, end_vertex = self._add_edge_vertices(edge) rhino_edge = self._add_edge(edge, start_vertex, end_vertex) @@ -388,21 +384,15 @@ def _create_brep_face(self, face): return brep_face, brep_surface def _add_edge_vertices(self, edge): - start_vertex = self._brep.Vertices.Add( - point_to_rhino(edge.start_vertex.point), TOLERANCE - ) - end_vertex = self._brep.Vertices.Add( - point_to_rhino(edge.end_vertex.point), TOLERANCE - ) + start_vertex = self._brep.Vertices.Add(point_to_rhino(edge.start_vertex.point), TOLERANCE) + end_vertex = self._brep.Vertices.Add(point_to_rhino(edge.end_vertex.point), TOLERANCE) return start_vertex, end_vertex def _add_edge(self, edge, start_vertex, end_vertex): # Geometry curve_index = self._brep.AddEdgeCurve(edge.curve) # Topology - rhino_edge = self._brep.Edges.Add( - start_vertex, end_vertex, curve_index, TOLERANCE - ) + rhino_edge = self._brep.Edges.Add(start_vertex, end_vertex, curve_index, TOLERANCE) return rhino_edge def _add_trim(self, rhino_trim_curve, rhino_edge, rhino_loop): diff --git a/src/compas_rhino/geometry/brep/edge.py b/src/compas_rhino/geometry/brep/edge.py index 33e7fc0acd86..58b1a1bd9b6d 100644 --- a/src/compas_rhino/geometry/brep/edge.py +++ b/src/compas_rhino/geometry/brep/edge.py @@ -71,13 +71,9 @@ def data(self): def data(self, value): curve_type = value["type"] if curve_type == "line": - self._curve = line_to_rhino_curve( - Line.from_data(value["value"]) - ) # this returns a Nurbs Curve, why? + self._curve = line_to_rhino_curve(Line.from_data(value["value"])) # this returns a Nurbs Curve, why? elif curve_type == "circle": - self._curve = circle_to_rhino_curve( - Circle.from_data(value["value"]) - ) # this returns a Nurbs Curve, why? + self._curve = circle_to_rhino_curve(Circle.from_data(value["value"])) # this returns a Nurbs Curve, why? else: self._curve = RhinoNurbsCurve.from_data(value["value"]).rhino_curve # TODO: can a single edge be defined with more than start and end vertices? diff --git a/src/compas_rhino/geometry/curves/nurbs.py b/src/compas_rhino/geometry/curves/nurbs.py index 81e4571f7ba8..fc7d0f33f77b 100644 --- a/src/compas_rhino/geometry/curves/nurbs.py +++ b/src/compas_rhino/geometry/curves/nurbs.py @@ -23,9 +23,7 @@ def rhino_curve_from_parameters(points, weights, knots, multiplicities, degree): rhino_curve = Rhino.Geometry.NurbsCurve(3, True, degree + 1, len(points)) for index, (point, weight) in enumerate(zip(points, weights)): rhino_curve.Points.SetPoint(index, point_to_rhino(point), weight) - knotvector = [ - knot for knot, mult in zip(knots, multiplicities) for _ in range(mult) - ] + knotvector = [knot for knot, mult in zip(knots, multiplicities) for _ in range(mult)] # account for superfluous knots # https://developer.rhino3d.com/guides/opennurbs/superfluous-knots/ p = len(points) @@ -110,9 +108,7 @@ def data(self, data): # is_periodic = data['is_periodic'] # have not found a way to actually set this # not sure if that is actually possible... - self.rhino_curve = rhino_curve_from_parameters( - points, weights, knots, multiplicities, degree - ) + self.rhino_curve = rhino_curve_from_parameters(points, weights, knots, multiplicities, degree) # ============================================================================== # Rhino Properties @@ -167,9 +163,7 @@ def is_rational(self): # ============================================================================== @classmethod - def from_parameters( - cls, points, weights, knots, multiplicities, degree, is_periodic=False - ): + def from_parameters(cls, points, weights, knots, multiplicities, degree, is_periodic=False): """Construct a NURBS curve from explicit curve parameters. Parameters @@ -194,9 +188,7 @@ def from_parameters( """ curve = cls() - curve.rhino_curve = rhino_curve_from_parameters( - points, weights, knots, multiplicities, degree - ) + curve.rhino_curve = rhino_curve_from_parameters(points, weights, knots, multiplicities, degree) return curve @classmethod @@ -219,9 +211,7 @@ def from_points(cls, points, degree=3, is_periodic=False): """ points[:] = [point_to_rhino(point) for point in points] curve = cls() - curve.rhino_curve = Rhino.Geometry.NurbsCurve.Create( - is_periodic, degree, points - ) + curve.rhino_curve = Rhino.Geometry.NurbsCurve.Create(is_periodic, degree, points) return curve @classmethod @@ -242,9 +232,7 @@ def from_interpolation(cls, points, precision=1e-3): """ curve = cls() - curve.rhino_curve = Rhino.Geometry.NurbsCurve.CreateHSpline( - [point_to_rhino(point) for point in points] - ) + curve.rhino_curve = Rhino.Geometry.NurbsCurve.CreateHSpline([point_to_rhino(point) for point in points]) return curve # @classmethod @@ -298,9 +286,7 @@ def from_line(cls, line): """ curve = cls() - curve.rhino_curve = Rhino.Geometry.NurbsCurve.CreateFromLine( - line_to_rhino(line) - ) + curve.rhino_curve = Rhino.Geometry.NurbsCurve.CreateFromLine(line_to_rhino(line)) return curve # ============================================================================== diff --git a/src/compas_rhino/geometry/surfaces/nurbs.py b/src/compas_rhino/geometry/surfaces/nurbs.py index 42b9c9d7d53f..925f03cda11e 100644 --- a/src/compas_rhino/geometry/surfaces/nurbs.py +++ b/src/compas_rhino/geometry/surfaces/nurbs.py @@ -25,11 +25,7 @@ def points(self): for i in range(self.rhino_surface.Points.CountU): row = [] for j in range(self.rhino_surface.Points.CountV): - row.append( - point_to_compas( - self.rhino_surface.Points.GetControlPoint(i, j).Location - ) - ) + row.append(point_to_compas(self.rhino_surface.Points.GetControlPoint(i, j).Location)) points.append(row) return points @@ -44,9 +40,7 @@ def __getitem__(self, index): def __setitem__(self, index, point): u, v = index - self.rhino_surface.Points.SetControlPoint( - u, v, Rhino.Geometry.ControlPoint(point_to_rhino(point)) - ) + self.rhino_surface.Points.SetControlPoint(u, v, Rhino.Geometry.ControlPoint(point_to_rhino(point))) def __len__(self): return self.rhino_surface.Points.CountU @@ -67,9 +61,7 @@ def rhino_surface_from_parameters( is_u_periodic=False, is_v_periodic=False, ): - rhino_surface = Rhino.Geometry.NurbsSurface.Create( - 3, True, u_degree + 1, v_degree + 1, len(points[0]), len(points) - ) + rhino_surface = Rhino.Geometry.NurbsSurface.Create(3, True, u_degree + 1, v_degree + 1, len(points[0]), len(points)) u_knotvector = [knot for knot, mult in zip(u_knots, u_mults) for _ in range(mult)] v_knotvector = [knot for knot, mult in zip(v_knots, v_mults) for _ in range(mult)] u_count = len(points[0]) @@ -90,9 +82,7 @@ def rhino_surface_from_parameters( # add control points for i in range(v_count): for j in range(u_count): - rhino_surface.Points.SetPoint( - i, j, point_to_rhino(points[i][j]), weights[i][j] - ) + rhino_surface.Points.SetPoint(i, j, point_to_rhino(points[i][j]), weights[i][j]) return rhino_surface @@ -371,9 +361,7 @@ def from_fill(cls, curve1, curve2): """ surface = cls() # these curves probably need to be processed first - surface.rhino_surface = Rhino.Geometry.NurbsSurface.CreateRuledSurface( - curve1, curve2 - ) + surface.rhino_surface = Rhino.Geometry.NurbsSurface.CreateRuledSurface(curve1, curve2) return surface # ============================================================================== diff --git a/src/compas_rhino/geometry/trimesh/curvature.py b/src/compas_rhino/geometry/trimesh/curvature.py index 145a8cc012f9..f76e008a67f9 100644 --- a/src/compas_rhino/geometry/trimesh/curvature.py +++ b/src/compas_rhino/geometry/trimesh/curvature.py @@ -186,9 +186,7 @@ def trimesh_mean_curvature(M): # (3) Main - loop over all vertices for i in range(mesh.Vertices.Count): - edges = mesh.TopologyVertices.ConnectedEdges( - mesh.TopologyVertices.TopologyVertexIndex(i) - ) + edges = mesh.TopologyVertices.ConnectedEdges(mesh.TopologyVertices.TopologyVertexIndex(i)) vertex = FromPoint3f(mesh.Vertices[i]) if edges is None: H.append(None) @@ -206,9 +204,7 @@ def trimesh_mean_curvature(M): orientation = list(orientation.Value) start_pt = mesh.TopologyEdges.EdgeLine(edge).From direction = start_pt.EpsilonEquals(vertex, doc.ModelAbsoluteTolerance) - normals = dict( - zip(orientation, [faces_normal[faces[0]], faces_normal[faces[1]]]) - ) + normals = dict(zip(orientation, [faces_normal[faces[0]], faces_normal[faces[1]]])) e = mesh.TopologyEdges.EdgeLine(edge).Direction e.Unitize() n1 = normals[True] diff --git a/src/compas_rhino/install.py b/src/compas_rhino/install.py index c38b90958dc3..28e56fc45824 100644 --- a/src/compas_rhino/install.py +++ b/src/compas_rhino/install.py @@ -119,9 +119,7 @@ def install(version=None, packages=None, clean=False): symlinks_to_uninstall.append(dict(name=package, link=symlink_path)) package_path = compas_rhino._get_package_path(importlib.import_module(package)) - symlinks_to_install.append( - dict(name=package, source_path=package_path, link=symlink_path) - ) + symlinks_to_install.append(dict(name=package, source_path=package_path, link=symlink_path)) # Handle legacy install location # This does not always work, @@ -244,11 +242,7 @@ def _run_post_execution_steps(steps_generator): print(" {} {}: {}".format(package.ljust(20), status, message)) except ValueError: post_execution_errors.append( - ValueError( - "Step ran without errors but result is wrongly formatted: {}".format( - str(item) - ) - ) + ValueError("Step ran without errors but result is wrongly formatted: {}".format(str(item))) ) if post_execution_errors: @@ -261,9 +255,7 @@ def _run_post_execution_steps(steps_generator): return all_steps_succeeded -@compas.plugins.plugin( - category="install", pluggable_name="installable_rhino_packages", tryfirst=True -) +@compas.plugins.plugin(category="install", pluggable_name="installable_rhino_packages", tryfirst=True) def default_installable_rhino_packages(): # While this list could obviously be hard-coded, I think # eating our own dogfood and using plugins to define this, just like @@ -327,9 +319,7 @@ def after_rhino_install(installed_packages): def _update_bootstrapper(install_path, packages): # Take either the CONDA environment directory or the current Python executable's directory - python_directory = os.environ.get("CONDA_PREFIX", None) or os.path.dirname( - sys.executable - ) + python_directory = os.environ.get("CONDA_PREFIX", None) or os.path.dirname(sys.executable) environment_name = os.environ.get("CONDA_DEFAULT_ENV", "") conda_exe = os.environ.get("CONDA_EXE", "") @@ -354,13 +344,9 @@ def _filter_installable_packages(version, packages): if not packages: # Flatten list of results (resulting from collect_all pluggable) - packages = sorted( - set(itertools.chain.from_iterable(installable_rhino_packages())) - ) + packages = sorted(set(itertools.chain.from_iterable(installable_rhino_packages()))) elif "compas_ghpython" in packages and ghpython_incompatible: - print( - "Skipping installation of compas_ghpython since it's not supported for Rhino 5 for Mac" - ) + print("Skipping installation of compas_ghpython since it's not supported for Rhino 5 for Mac") if ghpython_incompatible: packages.remove("compas_ghpython") diff --git a/src/compas_rhino/install_plugin.py b/src/compas_rhino/install_plugin.py index 30622c3f19e0..0f244f668cfd 100644 --- a/src/compas_rhino/install_plugin.py +++ b/src/compas_rhino/install_plugin.py @@ -146,9 +146,7 @@ def install_plugin(plugin, version=None): create_symlinks([(source, destination)]) print("\nPlugIn {} Installed.".format(plugin_name)) - print( - "\nRestart Rhino and open the Python editor at least once to make it available." - ) + print("\nRestart Rhino and open the Python editor at least once to make it available.") # ============================================================================== @@ -159,9 +157,7 @@ def install_plugin(plugin, version=None): import argparse - parser = argparse.ArgumentParser( - description="COMPAS Rhino Plugin Installation command-line utility." - ) + parser = argparse.ArgumentParser(description="COMPAS Rhino Plugin Installation command-line utility.") parser.add_argument("plugin", help="The path to the plugin directory.") parser.add_argument( diff --git a/src/compas_rhino/uninstall.py b/src/compas_rhino/uninstall.py index f611ad183a40..fbfe939f8b82 100644 --- a/src/compas_rhino/uninstall.py +++ b/src/compas_rhino/uninstall.py @@ -82,11 +82,7 @@ def uninstall(version=None, packages=None): # There is nothing to uninstall if not symlinks_to_uninstall: - print( - "\nNo packages to uninstall from Rhino {0} scripts folder: \n{1}.".format( - version, scripts_path - ) - ) + print("\nNo packages to uninstall from Rhino {0} scripts folder: \n{1}.".format(version, scripts_path)) return # ------------------------- @@ -146,11 +142,7 @@ def uninstall(version=None, packages=None): # Output results # ------------------------- - print( - "Uninstalling COMPAS packages from Rhino {0} scripts folder: \n{1}".format( - version, scripts_path - ) - ) + print("Uninstalling COMPAS packages from Rhino {0} scripts folder: \n{1}".format(version, scripts_path)) print("\nThe following packages have been detected and will be uninstalled:\n") for package, status in results: @@ -248,9 +240,7 @@ def after_rhino_uninstall(uninstalled_packages): default=compas_rhino.DEFAULT_VERSION, help="The version of Rhino to install the packages in.", ) - parser.add_argument( - "-p", "--packages", nargs="+", help="The packages to uninstall." - ) + parser.add_argument("-p", "--packages", nargs="+", help="The packages to uninstall.") args = parser.parse_args() diff --git a/src/compas_rhino/utilities/drawing.py b/src/compas_rhino/utilities/drawing.py index 0073fc4b52d9..baaa0c676ed3 100644 --- a/src/compas_rhino/utilities/drawing.py +++ b/src/compas_rhino/utilities/drawing.py @@ -503,9 +503,7 @@ def draw_breps(faces, u=10, v=10, join=False, **kwargs): geo.Add(pcurve) p = len(points) if p == 3: - brep = Brep.CreateFromCornerPoints( - Point3d(*points[0]), Point3d(*points[1]), Point3d(*points[2]), TOL - ) + brep = Brep.CreateFromCornerPoints(Point3d(*points[0]), Point3d(*points[1]), Point3d(*points[2]), TOL) elif p == 4: brep = Brep.CreateFromCornerPoints( Point3d(*points[0]), diff --git a/src/compas_rhino/utilities/layers.py b/src/compas_rhino/utilities/layers.py index e8bff0582f71..d48a6f202120 100644 --- a/src/compas_rhino/utilities/layers.py +++ b/src/compas_rhino/utilities/layers.py @@ -33,9 +33,7 @@ def show_hidden_objects_on_layer(name): - rs.ShowObjects( - [guid for guid in rs.HiddenObjects() if rs.ObjectLayer(guid) == name] - ) + rs.ShowObjects([guid for guid in rs.HiddenObjects() if rs.ObjectLayer(guid) == name]) def find_objects_on_layer(name, include_hidden=True, include_children=True): @@ -54,9 +52,7 @@ def find_objects_on_layer(name, include_hidden=True, include_children=True): return to_delete -def delete_objects_on_layer( - name, include_hidden=True, include_children=False, purge=True -): +def delete_objects_on_layer(name, include_hidden=True, include_children=False, purge=True): guids = find_objects_on_layer(name, include_hidden, include_children) if purge and purge_object: rs.EnableRedraw(False) diff --git a/src/compas_rhino/utilities/misc.py b/src/compas_rhino/utilities/misc.py index fea333e787ef..d8b58f5b8008 100644 --- a/src/compas_rhino/utilities/misc.py +++ b/src/compas_rhino/utilities/misc.py @@ -222,9 +222,7 @@ def display_html(): # ============================================================================== -def update_named_values( - names, values, message="", title="Update named values", evaluate=False -): +def update_named_values(names, values, message="", title="Update named values", evaluate=False): try: dialog = PropertyListForm(names, values) except Exception: diff --git a/src/compas_rhino/utilities/objects.py b/src/compas_rhino/utilities/objects.py index 1b9279261d40..35f746d3a6f8 100644 --- a/src/compas_rhino/utilities/objects.py +++ b/src/compas_rhino/utilities/objects.py @@ -465,9 +465,7 @@ def select_points(message="Select multiple points."): """ guids = [] - temp = rs.GetObjects( - message, preselect=True, select=True, group=False, filter=rs.filter.point - ) + temp = rs.GetObjects(message, preselect=True, select=True, group=False, filter=rs.filter.point) if temp: guids = temp return guids @@ -542,30 +540,15 @@ def is_curve_line(guid): False otherwise. """ - return ( - rs.IsCurve(guid) - and rs.IsLine(guid) - and rs.CurveDegree(guid) == 1 - and len(rs.CurvePoints(guid)) == 2 - ) + return rs.IsCurve(guid) and rs.IsLine(guid) and rs.CurveDegree(guid) == 1 and len(rs.CurvePoints(guid)) == 2 def is_curve_polyline(guid): - return ( - rs.IsCurve(guid) - and rs.IsPolyline(guid) - and rs.CurveDegree(guid) == 1 - and len(rs.CurvePoints(guid)) > 2 - ) + return rs.IsCurve(guid) and rs.IsPolyline(guid) and rs.CurveDegree(guid) == 1 and len(rs.CurvePoints(guid)) > 2 def is_curve_polygon(guid): - return ( - rs.IsCurve(guid) - and rs.IsCurveClosed(guid) - and rs.CurveDegree(guid) == 1 - and len(rs.CurvePoints(guid)) > 2 - ) + return rs.IsCurve(guid) and rs.IsCurveClosed(guid) and rs.CurveDegree(guid) == 1 and len(rs.CurvePoints(guid)) > 2 def select_curve(message="Select one curve."): @@ -600,9 +583,7 @@ def select_curves(message="Select multiple curves."): """ guids = [] - temp = rs.GetObjects( - message, preselect=True, select=True, group=False, filter=rs.filter.curve - ) + temp = rs.GetObjects(message, preselect=True, select=True, group=False, filter=rs.filter.curve) if temp: guids = temp return guids @@ -643,9 +624,7 @@ def select_lines(message="Select multiple lines."): """ guids = [] - temp = rs.GetObjects( - message, preselect=True, select=True, group=False, filter=rs.filter.curve - ) + temp = rs.GetObjects(message, preselect=True, select=True, group=False, filter=rs.filter.curve) if temp: for guid in temp: if is_curve_line(guid): @@ -692,9 +671,7 @@ def select_polylines( """ guids = [] - temp = rs.GetObjects( - message, preselect=True, select=True, group=False, filter=rs.filter.curve - ) + temp = rs.GetObjects(message, preselect=True, select=True, group=False, filter=rs.filter.curve) if temp: for guid in temp: if is_curve_polyline(guid): @@ -737,9 +714,7 @@ def select_polygons(message="Select multiple polygons (closed curves with degree """ guids = [] - temp = rs.GetObjects( - message, preselect=True, select=True, group=False, filter=rs.filter.curve - ) + temp = rs.GetObjects(message, preselect=True, select=True, group=False, filter=rs.filter.curve) if temp: for guid in temp: if is_curve_polygon(guid): @@ -1043,9 +1018,7 @@ def select_meshes(message="Select multiple meshes."): """ guids = [] - temp = rs.GetObjects( - message, preselect=True, select=True, group=False, filter=rs.filter.mesh - ) + temp = rs.GetObjects(message, preselect=True, select=True, group=False, filter=rs.filter.mesh) if temp: guids = temp return guids From c4d06d5c8f48383f808eda05195a60563ee9b2ec Mon Sep 17 00:00:00 2001 From: Gonzalo Casas Date: Tue, 4 Oct 2022 13:58:33 +0200 Subject: [PATCH 3/4] run black on tests --- tests/compas/data/test_json.py | 9 ++---- tests/compas/data/test_jsonschema.py | 16 +++------- tests/compas/datastructures/test_graph.py | 5 +--- tests/compas/datastructures/test_halfedge.py | 10 ++----- tests/compas/datastructures/test_halfface.py | 18 +++--------- tests/compas/datastructures/test_mesh_subd.py | 26 ++++------------- tests/compas/geometry/test_core.py | 8 ++--- tests/compas/geometry/test_distance.py | 4 +-- tests/compas/geometry/test_offset.py | 4 +-- tests/compas/geometry/test_polygon.py | 7 +---- tests/compas/geometry/test_polyline.py | 7 +---- tests/compas/geometry/test_queries.py | 14 ++------- .../test_transformations/test_matrices.py | 4 +-- .../test_transformation.py | 8 ++--- .../test_transformations.py | 8 ++--- tests/compas/robots/test_configuration.py | 20 ++++--------- tests/compas/robots/test_model.py | 29 ++++--------------- tests/compas/robots/test_tool.py | 8 ++--- tests/compas/stubs.py | 4 +-- tests/compas/test_api_completeness.py | 8 ++--- tests/compas/test_api_stability.py | 26 ++++------------- tests/compas/utilities/test_itertools.py | 4 +-- tests/compas/utilities/test_itertools_.py | 4 +-- 23 files changed, 56 insertions(+), 195 deletions(-) diff --git a/tests/compas/data/test_json.py b/tests/compas/data/test_json.py index 2d1bb86e629c..6159349a710b 100644 --- a/tests/compas/data/test_json.py +++ b/tests/compas/data/test_json.py @@ -69,9 +69,7 @@ def test_json_network(): def test_json_mesh(): - before = Mesh.from_vertices_and_faces( - [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], [[0, 1, 2, 3]] - ) + before = Mesh.from_vertices_and_faces([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], [[0, 1, 2, 3]]) after = compas.json_loads(compas.json_dumps(before)) assert before.dtype == after.dtype assert before.attributes == after.attributes @@ -81,10 +79,7 @@ def test_json_mesh(): assert all(after.has_face(face) for face in before.faces()) assert all(before.has_edge(edge) for edge in after.edges()) assert all(after.has_edge(edge) for edge in before.edges()) - assert all( - before.face_vertices(a) == after.face_vertices(b) - for a, b in zip(before.faces(), after.faces()) - ) + assert all(before.face_vertices(a) == after.face_vertices(b) for a, b in zip(before.faces(), after.faces())) assert before.guid == after.guid diff --git a/tests/compas/data/test_jsonschema.py b/tests/compas/data/test_jsonschema.py index 5b822ce96440..a29f248ffe2e 100644 --- a/tests/compas/data/test_jsonschema.py +++ b/tests/compas/data/test_jsonschema.py @@ -215,9 +215,7 @@ def test_schema_vector_invalid(vector_validator, vector): def test_schema_line_valid(line_validator, line): line_validator.validate(line) - @pytest.mark.parametrize( - "line", [[[0, 0, 0], [0, 0, 0]], {"START": [0, 0, 0], "END": [0, 0, 0]}] - ) + @pytest.mark.parametrize("line", [[[0, 0, 0], [0, 0, 0]], {"START": [0, 0, 0], "END": [0, 0, 0]}]) def test_schema_line_invalid(line_validator, line): with pytest.raises(jsonschema.exceptions.ValidationError): line_validator.validate(line) @@ -226,16 +224,12 @@ def test_schema_line_invalid(line_validator, line): def test_schema_plane_valid(plane_validator, plane): plane_validator.validate(plane) - @pytest.mark.parametrize( - "plane", [[[0, 0, 0], [0, 0, 1]], {"POINT": [0, 0, 0], "NORMAL": [0, 0, 1]}] - ) + @pytest.mark.parametrize("plane", [[[0, 0, 0], [0, 0, 1]], {"POINT": [0, 0, 0], "NORMAL": [0, 0, 1]}]) def test_schema_plane_invalid(plane_validator, plane): with pytest.raises(jsonschema.exceptions.ValidationError): plane_validator.validate(plane) - @pytest.mark.parametrize( - "circle", [{"plane": {"point": [0, 0, 0], "normal": [0, 0, 1]}, "radius": 1.0}] - ) + @pytest.mark.parametrize("circle", [{"plane": {"point": [0, 0, 0], "normal": [0, 0, 1]}, "radius": 1.0}]) def test_schema_circle_valid(circle_validator, circle): circle_validator.validate(circle) @@ -442,9 +436,7 @@ def test_schema_box_invalid(box_validator, box): with pytest.raises(jsonschema.exceptions.ValidationError): box_validator.validate(box) - @pytest.mark.parametrize( - "capsule", [{"line": {"start": [0, 0, 0], "end": [1, 0, 0]}, "radius": 1.0}] - ) + @pytest.mark.parametrize("capsule", [{"line": {"start": [0, 0, 0], "end": [1, 0, 0]}, "radius": 1.0}]) def test_schema_capsule_valid(capsule_validator, capsule): capsule_validator.validate(capsule) diff --git a/tests/compas/datastructures/test_graph.py b/tests/compas/datastructures/test_graph.py index 6f2e0b38ae44..2b77807cd793 100644 --- a/tests/compas/datastructures/test_graph.py +++ b/tests/compas/datastructures/test_graph.py @@ -35,10 +35,7 @@ def test_edgedata_io(graph): for index, (u, v) in enumerate(graph.edges()): graph.edge_attribute((u, v), "index", index) other = Graph.from_data(graph.data) - assert all( - other.edge_attribute(edge, "index") == index - for index, edge in enumerate(other.edges()) - ) + assert all(other.edge_attribute(edge, "index") == index for index, edge in enumerate(other.edges())) def test_data_schema(graph): diff --git a/tests/compas/datastructures/test_halfedge.py b/tests/compas/datastructures/test_halfedge.py index 5e909563a247..e017256d633a 100644 --- a/tests/compas/datastructures/test_halfedge.py +++ b/tests/compas/datastructures/test_halfedge.py @@ -71,10 +71,7 @@ def test_edgedata_nondirectionality(mesh): mesh.update_default_edge_attributes({"index": 0}) for index, (u, v) in enumerate(mesh.edges()): mesh.edge_attribute((u, v), "index", index) - assert all( - mesh.edge_attribute((u, v), "index") == mesh.edge_attribute((v, u), "index") - for u, v in mesh.edges() - ) + assert all(mesh.edge_attribute((u, v), "index") == mesh.edge_attribute((v, u), "index") for u, v in mesh.edges()) def test_edgedata_io(mesh): @@ -82,10 +79,7 @@ def test_edgedata_io(mesh): for index, (u, v) in enumerate(mesh.edges()): mesh.edge_attribute((u, v), "index", index) other = HalfEdge.from_data(mesh.data) - assert all( - other.edge_attribute(edge, "index") == index - for index, edge in enumerate(other.edges()) - ) + assert all(other.edge_attribute(edge, "index") == index for index, edge in enumerate(other.edges())) def test_data_schema(mesh): diff --git a/tests/compas/datastructures/test_halfface.py b/tests/compas/datastructures/test_halfface.py index 7bd5f25c9282..97cedbd8669f 100644 --- a/tests/compas/datastructures/test_halfface.py +++ b/tests/compas/datastructures/test_halfface.py @@ -84,9 +84,7 @@ def test_vertices_where_predicate(): hf.add_vertex(0) hf.add_vertex(1, {"a": 5, "b": 10}) hf.add_vertex(2, {"a": 15, "b": 20}) - assert list( - hf.vertices_where_predicate(lambda v, attr: attr["b"] - attr["a"] == 5) - ) == [1, 2] + assert list(hf.vertices_where_predicate(lambda v, attr: attr["b"] - attr["a"] == 5)) == [1, 2] # ============================================================================== @@ -109,9 +107,7 @@ def test_edges_where_predicate(): hf.add_vertex(vkey) hf.add_halfface([0, 1, 2]) hf.edge_attribute((0, 1), "a", 5) - assert list(hf.edges_where_predicate(lambda e, attr: attr["a"] - attr["b"] == 3))[ - 0 - ] == (0, 1) + assert list(hf.edges_where_predicate(lambda e, attr: attr["a"] - attr["b"] == 3))[0] == (0, 1) # ============================================================================== @@ -136,10 +132,7 @@ def test_faces_where_predicate(): for i in range(3): hf.add_halfface([i, i + 1, i + 2]) hf.face_attribute(1, "a", 5) - assert ( - list(hf.faces_where_predicate(lambda e, attr: attr["a"] - attr["b"] == 3))[0] - == 1 - ) + assert list(hf.faces_where_predicate(lambda e, attr: attr["a"] - attr["b"] == 3))[0] == 1 # ============================================================================== @@ -178,7 +171,4 @@ def test_cells_where_predicate(): ] ) hf.cell_attribute(1, "a", 5) - assert ( - list(hf.cells_where_predicate(lambda e, attr: attr["a"] - attr["b"] == 3))[0] - == 1 - ) + assert list(hf.cells_where_predicate(lambda e, attr: attr["a"] - attr["b"] == 3))[0] == 1 diff --git a/tests/compas/datastructures/test_mesh_subd.py b/tests/compas/datastructures/test_mesh_subd.py index 3704a51e1547..5d37a7f4b71b 100644 --- a/tests/compas/datastructures/test_mesh_subd.py +++ b/tests/compas/datastructures/test_mesh_subd.py @@ -20,9 +20,7 @@ def test_quads_subdivide(mesh_quads): subd = mesh_quads.subdivide() assert subd.number_of_faces() == 4 * mesh_quads.number_of_faces() assert subd.number_of_vertices() == ( - mesh_quads.number_of_vertices() - + mesh_quads.number_of_edges() - + mesh_quads.number_of_faces() + mesh_quads.number_of_vertices() + mesh_quads.number_of_edges() + mesh_quads.number_of_faces() ) @@ -30,37 +28,27 @@ def test_tris_subdivide(mesh_tris): subd = mesh_tris.subdivide() assert subd.number_of_faces() == 3 * mesh_tris.number_of_faces() assert subd.number_of_vertices() == ( - mesh_tris.number_of_vertices() - + mesh_tris.number_of_edges() - + mesh_tris.number_of_faces() + mesh_tris.number_of_vertices() + mesh_tris.number_of_edges() + mesh_tris.number_of_faces() ) def test_quads_subdivide_tri(mesh_quads): subd = mesh_quads.subdivide(scheme="tri") assert subd.number_of_faces() == 4 * mesh_quads.number_of_faces() - assert ( - subd.number_of_vertices() - == mesh_quads.number_of_vertices() + mesh_quads.number_of_faces() - ) + assert subd.number_of_vertices() == mesh_quads.number_of_vertices() + mesh_quads.number_of_faces() def test_tris_subdivide_tri(mesh_tris): subd = mesh_tris.subdivide(scheme="tri") assert subd.number_of_faces() == 3 * mesh_tris.number_of_faces() - assert ( - subd.number_of_vertices() - == mesh_tris.number_of_vertices() + mesh_tris.number_of_faces() - ) + assert subd.number_of_vertices() == mesh_tris.number_of_vertices() + mesh_tris.number_of_faces() def test_quads_subdivide_quad(mesh_quads): subd = mesh_quads.subdivide(scheme="quad") assert subd.number_of_faces() == 4 * mesh_quads.number_of_faces() assert subd.number_of_vertices() == ( - mesh_quads.number_of_vertices() - + mesh_quads.number_of_edges() - + mesh_quads.number_of_faces() + mesh_quads.number_of_vertices() + mesh_quads.number_of_edges() + mesh_quads.number_of_faces() ) @@ -68,7 +56,5 @@ def test_tris_subdivide_quad(mesh_tris): subd = mesh_tris.subdivide(scheme="quad") assert subd.number_of_faces() == 3 * mesh_tris.number_of_faces() assert subd.number_of_vertices() == ( - mesh_tris.number_of_vertices() - + mesh_tris.number_of_edges() - + mesh_tris.number_of_faces() + mesh_tris.number_of_vertices() + mesh_tris.number_of_edges() + mesh_tris.number_of_faces() ) diff --git a/tests/compas/geometry/test_core.py b/tests/compas/geometry/test_core.py index 1bb085b803bd..2a00aa22d504 100644 --- a/tests/compas/geometry/test_core.py +++ b/tests/compas/geometry/test_core.py @@ -197,14 +197,10 @@ def test_centroid_polyhedron(polyhedron, centroid): # ============================================================================== -@pytest.mark.parametrize( - ("polyhedron", "volume"), [(Polyhedron.from_platonicsolid(6), None)] -) +@pytest.mark.parametrize(("polyhedron", "volume"), [(Polyhedron.from_platonicsolid(6), None)]) def test_volume_polyhedron(polyhedron, volume): if volume is None: - L = length_vector( - subtract_vectors(polyhedron.vertices[0], polyhedron.vertices[1]) - ) + L = length_vector(subtract_vectors(polyhedron.vertices[0], polyhedron.vertices[1])) volume = L * L * L V = volume_polyhedron(polyhedron) assert close(V, volume) diff --git a/tests/compas/geometry/test_distance.py b/tests/compas/geometry/test_distance.py index 10da704ca188..359e8ccc8743 100644 --- a/tests/compas/geometry/test_distance.py +++ b/tests/compas/geometry/test_distance.py @@ -5,9 +5,7 @@ from compas.geometry import closest_point_on_segment_xy -@pytest.mark.parametrize( - "point,point_on_line", [[[0, 0, -10], [1, 1, 0]], [[5, 4, 80], [4.5, 4.5, 0]]] -) +@pytest.mark.parametrize("point,point_on_line", [[[0, 0, -10], [1, 1, 0]], [[5, 4, 80], [4.5, 4.5, 0]]]) def test_closest_point_segment_xy(point, point_on_line): line = Line([1, 1, -15], [10, 10, 20]) ponl = closest_point_on_segment_xy(Point(*point), line) diff --git a/tests/compas/geometry/test_offset.py b/tests/compas/geometry/test_offset.py index 19f5c39ebbe2..762b5ac7b361 100644 --- a/tests/compas/geometry/test_offset.py +++ b/tests/compas/geometry/test_offset.py @@ -79,9 +79,7 @@ def test_offset_polyline_equals_offset_line(polyline, distance, normal, tol): ) ], ) -def test_variable_offset_on_colinear_polyline( - polyline, distance, normal, tol, output_polyline -): +def test_variable_offset_on_colinear_polyline(polyline, distance, normal, tol, output_polyline): output_polyline = [v for v in output_polyline] assert allclose(offset_polyline(polyline, distance, normal, tol), output_polyline) diff --git a/tests/compas/geometry/test_polygon.py b/tests/compas/geometry/test_polygon.py index 43d918c49720..faca266b0078 100644 --- a/tests/compas/geometry/test_polygon.py +++ b/tests/compas/geometry/test_polygon.py @@ -10,12 +10,7 @@ if not compas.IPY: def test_data(): - p = Polygon( - [ - Point(random.random(), random.random(), random.random()) - for i in range(10) - ] - ) + p = Polygon([Point(random.random(), random.random(), random.random()) for i in range(10)]) assert p.data == p.validate_data() o = Polygon.from_data(p.data) assert p == o diff --git a/tests/compas/geometry/test_polyline.py b/tests/compas/geometry/test_polyline.py index 2053067814f9..53f50e588534 100644 --- a/tests/compas/geometry/test_polyline.py +++ b/tests/compas/geometry/test_polyline.py @@ -11,12 +11,7 @@ if not compas.IPY: def test_data(): - p = Polyline( - [ - Point(random.random(), random.random(), random.random()) - for i in range(10) - ] - ) + p = Polyline([Point(random.random(), random.random(), random.random()) for i in range(10)]) assert p.data == p.validate_data() o = Polyline.from_data(p.data) assert p == o diff --git a/tests/compas/geometry/test_queries.py b/tests/compas/geometry/test_queries.py index 0065a936755f..3b867327aaea 100644 --- a/tests/compas/geometry/test_queries.py +++ b/tests/compas/geometry/test_queries.py @@ -4,15 +4,5 @@ def test_is_colinear_line_line(): - assert ( - is_colinear_line_line( - Line(Point(0, 0, 0), Point(1, 1, 1)), Line(Point(3, 3, 3), Point(2, 2, 2)) - ) - is True - ) - assert ( - is_colinear_line_line( - Line(Point(0, 0, 0), Point(1, 1, 1)), Line(Point(4, 1, 0), Point(5, 2, 1)) - ) - is False - ) + assert is_colinear_line_line(Line(Point(0, 0, 0), Point(1, 1, 1)), Line(Point(3, 3, 3), Point(2, 2, 2))) is True + assert is_colinear_line_line(Line(Point(0, 0, 0), Point(1, 1, 1)), Line(Point(4, 1, 0), Point(5, 2, 1))) is False diff --git a/tests/compas/geometry/test_transformations/test_matrices.py b/tests/compas/geometry/test_transformations/test_matrices.py index a0834301d02d..b55147fbdac3 100644 --- a/tests/compas/geometry/test_transformations/test_matrices.py +++ b/tests/compas/geometry/test_transformations/test_matrices.py @@ -365,9 +365,7 @@ def test_basis_vectors_from_matrix(): R = matrix_from_frame(f) xaxis, yaxis = basis_vectors_from_matrix(R) assert allclose(xaxis, [0.6807833515407016, 0.6807833515407016, 0.2703110366411609]) - assert allclose( - yaxis, [-0.6687681911461376, 0.7282315441900513, -0.14975955581430114] - ) + assert allclose(yaxis, [-0.6687681911461376, 0.7282315441900513, -0.14975955581430114]) def test_translation_from_matrix(): diff --git a/tests/compas/geometry/test_transformations/test_transformation.py b/tests/compas/geometry/test_transformations/test_transformation.py index 8303fe85a166..2b91987aebf0 100644 --- a/tests/compas/geometry/test_transformations/test_transformation.py +++ b/tests/compas/geometry/test_transformations/test_transformation.py @@ -113,12 +113,8 @@ def test_basis_vectors(): S1 = Scale.from_factors(scale1) M = (T1 * R1) * S1 x, y = M.basis_vectors - assert allclose( - x, Vector(0.41249169135312663, -0.05897071585157175, -0.9090506362335324) - ) - assert allclose( - y, Vector(-0.8335562904208867, -0.4269749553355485, -0.35053715668381935) - ) + assert allclose(x, Vector(0.41249169135312663, -0.05897071585157175, -0.9090506362335324)) + assert allclose(y, Vector(-0.8335562904208867, -0.4269749553355485, -0.35053715668381935)) def test_list(): diff --git a/tests/compas/geometry/test_transformations/test_transformations.py b/tests/compas/geometry/test_transformations/test_transformations.py index f29297aaeba4..01b77c811e1e 100644 --- a/tests/compas/geometry/test_transformations/test_transformations.py +++ b/tests/compas/geometry/test_transformations/test_transformations.py @@ -84,9 +84,7 @@ def test_scale_points_xy(): def test_rotate_points(): - assert allclose( - rotate_points([[0, 1, 2]], 1), [[-0.8414709848078965, 0.5403023058681398, 2.0]] - ) + assert allclose(rotate_points([[0, 1, 2]], 1), [[-0.8414709848078965, 0.5403023058681398, 2.0]]) def test_rotate_points_xy(): @@ -164,9 +162,7 @@ def test_project_points_line(): def test_project_points_line_xy(): - assert project_points_line_xy([[0, 1, 2]], ([3, 4, 5], [6, 7, 8.8])) == [ - [0.0, 1.0, 0.0] - ] + assert project_points_line_xy([[0, 1, 2]], ([3, 4, 5], [6, 7, 8.8])) == [[0.0, 1.0, 0.0]] # TODO: is this correct? diff --git a/tests/compas/robots/test_configuration.py b/tests/compas/robots/test_configuration.py index 4d3028afb814..7b5badcb2abc 100644 --- a/tests/compas/robots/test_configuration.py +++ b/tests/compas/robots/test_configuration.py @@ -44,9 +44,7 @@ def test_revolute_ctor(): def test_prismatic_revolute_ctor(): - config = Configuration.from_prismatic_and_revolute_values( - [8.312], [1.5, 0.0, 0.0, 0.0, 1.0, 0.8] - ) + config = Configuration.from_prismatic_and_revolute_values([8.312], [1.5, 0.0, 0.0, 0.0, 1.0, 0.8]) assert config.joint_values == [8.312, 1.5, 0.0, 0.0, 0.0, 1.0, 0.8] assert config.joint_types == [Joint.PRISMATIC] + [Joint.REVOLUTE] * 6 @@ -69,23 +67,17 @@ def test_scale(): def test_cast_to_str(): - config = Configuration( - [math.pi / 2, 3.0, 0.1], [Joint.REVOLUTE, Joint.PRISMATIC, Joint.PLANAR] - ) + config = Configuration([math.pi / 2, 3.0, 0.1], [Joint.REVOLUTE, Joint.PRISMATIC, Joint.PLANAR]) assert str(config) == "Configuration((1.571, 3.000, 0.100), (0, 2, 5))" def test_from_data(): - config = Configuration.from_data( - dict(joint_values=[8.312, 1.5], joint_types=[Joint.PRISMATIC, Joint.REVOLUTE]) - ) + config = Configuration.from_data(dict(joint_values=[8.312, 1.5], joint_types=[Joint.PRISMATIC, Joint.REVOLUTE])) assert str(config) == "Configuration((8.312, 1.500), (2, 0))" def test_to_data(): - config = Configuration.from_prismatic_and_revolute_values( - [8.312], [1.5, 0.0, 0.0, 0.0, 1.0, 0.8] - ) + config = Configuration.from_prismatic_and_revolute_values([8.312], [1.5, 0.0, 0.0, 0.0, 1.0, 0.8]) # joint_types=[Joint.PRISMATIC, Joint.REVOLUTE])) data = config.to_data() @@ -116,9 +108,7 @@ def test_joint_names(): joint_names=["a", "a"], ) - config = Configuration( - joint_values=[1, 2], joint_types=[Joint.REVOLUTE] * 2, joint_names=["a", "b"] - ) + config = Configuration(joint_values=[1, 2], joint_types=[Joint.REVOLUTE] * 2, joint_names=["a", "b"]) with pytest.raises(ValueError): config.joint_names = ["a", "a"] diff --git a/tests/compas/robots/test_model.py b/tests/compas/robots/test_model.py index b85d61bc0b76..4b4fee07d651 100644 --- a/tests/compas/robots/test_model.py +++ b/tests/compas/robots/test_model.py @@ -79,9 +79,7 @@ def test_programmatic_robot_model(): assert ["link0", "joint1", "link1", "joint2", "link2"] == list(robot.iter_chain()) urdf = URDF.from_robot(robot) robot_reincarnated = RobotModel.from_urdf_string(urdf.to_string()) - assert ["link0", "joint1", "link1", "joint2", "link2"] == list( - robot_reincarnated.iter_chain() - ) + assert ["link0", "joint1", "link1", "joint2", "link2"] == list(robot_reincarnated.iter_chain()) robot.remove_link("link2") robot.remove_joint("joint2") assert ["link0", "joint1", "link1"] == list(robot.iter_chain()) @@ -413,10 +411,7 @@ def test_link_parser_data(urdf_file): def test_geometry_parser(urdf_file_with_shapes): r = RobotModel.from_urdf_file(urdf_file_with_shapes) - assert ( - r.links[0].visual[0].geometry.shape.filename - == "package://franka_description/meshes/visual/link0.dae" - ) + assert r.links[0].visual[0].geometry.shape.filename == "package://franka_description/meshes/visual/link0.dae" assert r.links[0].visual[0].geometry.shape.scale == [1.0, 1.0, 1.0] assert isinstance(r.links[0].collision[0].geometry.shape, (Sphere, SphereProxy)) @@ -435,10 +430,7 @@ def test_geometry_parser_to_string(urdf_file_with_shapes): urdf = URDF.from_robot(r_original) r = RobotModel.from_urdf_string(urdf.to_string()) - assert ( - r.links[0].visual[0].geometry.shape.filename - == "package://franka_description/meshes/visual/link0.dae" - ) + assert r.links[0].visual[0].geometry.shape.filename == "package://franka_description/meshes/visual/link0.dae" assert r.links[0].visual[0].geometry.shape.scale == [1.0, 1.0, 1.0] assert isinstance(r.links[0].collision[0].geometry.shape, (Sphere, SphereProxy)) @@ -456,10 +448,7 @@ def test_geometry_parser_data(urdf_file_with_shapes): r_original = RobotModel.from_urdf_file(urdf_file_with_shapes) r = RobotModel.from_data(r_original.data) - assert ( - r.links[0].visual[0].geometry.shape.filename - == "package://franka_description/meshes/visual/link0.dae" - ) + assert r.links[0].visual[0].geometry.shape.filename == "package://franka_description/meshes/visual/link0.dae" assert r.links[0].visual[0].geometry.shape.scale == [1.0, 1.0, 1.0] assert isinstance(r.links[0].collision[0].geometry.shape, (Sphere, SphereProxy)) @@ -485,9 +474,7 @@ def test_root_data(urdf_file): def test_root_getter_without_links(): - r = RobotModel.from_urdf_string( - """""" - ) + r = RobotModel.from_urdf_string("""""") assert r.root is None @@ -715,8 +702,4 @@ def test_json_serialization(urdf_file): for error in errors: print(" * File=%s, Error=%s" % error) - print( - "\nFound {} files and parsed successfully {} of them.".format( - len(all_files), len(all_files) - len(errors) - ) - ) + print("\nFound {} files and parsed successfully {} of them.".format(len(all_files), len(all_files) - len(errors))) diff --git a/tests/compas/robots/test_tool.py b/tests/compas/robots/test_tool.py index 8bbfc3d9d6e6..72ba84b54a38 100644 --- a/tests/compas/robots/test_tool.py +++ b/tests/compas/robots/test_tool.py @@ -34,9 +34,7 @@ def test_from_json(): def test_from_t0cf_to_tcf(mesh, frame): tool = ToolModel(mesh, frame) - frames_t0cf = [ - Frame((-0.363, 0.003, -0.147), (0.388, -0.351, -0.852), (0.276, 0.926, -0.256)) - ] + frames_t0cf = [Frame((-0.363, 0.003, -0.147), (0.388, -0.351, -0.852), (0.276, 0.926, -0.256))] result = tool.from_t0cf_to_tcf(frames_t0cf) expected = [ Frame( @@ -50,9 +48,7 @@ def test_from_t0cf_to_tcf(mesh, frame): def test_from_tcf_to_t0cf(mesh, frame): tool = ToolModel(mesh, frame) - frames_tcf = [ - Frame((-0.309, -0.046, -0.266), (0.276, 0.926, -0.256), (0.879, -0.136, 0.456)) - ] + frames_tcf = [Frame((-0.309, -0.046, -0.266), (0.276, 0.926, -0.256), (0.879, -0.136, 0.456))] result = tool.from_tcf_to_t0cf(frames_tcf) expected = [ Frame( diff --git a/tests/compas/stubs.py b/tests/compas/stubs.py index b0b888322c50..e1cd305fc69f 100644 --- a/tests/compas/stubs.py +++ b/tests/compas/stubs.py @@ -42,9 +42,7 @@ def compas_stubs(): if name == "compas.rst" or not name.startswith("compas."): continue stub = os.path.abspath(os.path.join(API, name)) - subprocess.call( - "sphinx-autogen -o {} {}".format(TEMP, stub), shell=True, env=env - ) + subprocess.call("sphinx-autogen -o {} {}".format(TEMP, stub), shell=True, env=env) _, _, filenames = next(os.walk(TEMP)) diff --git a/tests/compas/test_api_completeness.py b/tests/compas/test_api_completeness.py index 19368cce0d17..5b3db39da3d1 100644 --- a/tests/compas/test_api_completeness.py +++ b/tests/compas/test_api_completeness.py @@ -17,9 +17,7 @@ def get_names_in_module(module_name): [ i for i in all_names - if not i.startswith("_") - and i not in exceptions - and not inspect.ismodule(getattr(module, i)) + if not i.startswith("_") and i not in exceptions and not inspect.ismodule(getattr(module, i)) ] ) @@ -68,9 +66,7 @@ def compas_stubs(): if name == "compas.rst" or not name.startswith("compas."): continue stub = os.path.abspath(os.path.join(API, name)) - subprocess.call( - "sphinx-autogen -o {} {}".format(TEMP, stub), shell=True, env=env - ) + subprocess.call("sphinx-autogen -o {} {}".format(TEMP, stub), shell=True, env=env) _, _, filenames = next(os.walk(TEMP)) diff --git a/tests/compas/test_api_stability.py b/tests/compas/test_api_stability.py index 69e4ce2783ce..c82e8c373cf0 100644 --- a/tests/compas/test_api_stability.py +++ b/tests/compas/test_api_stability.py @@ -15,9 +15,7 @@ def test_no_removed_names_from_any_package(compas_api): # Raise to indicate the API file needs to be regenerated if current_ver["major"] != generated_ver["major"]: - raise Exception( - "The compas_api.json file needs to be regenerated for the current COMPAS major version" - ) + raise Exception("The compas_api.json file needs to be regenerated for the current COMPAS major version") mismatches = dict() for module_name in compas_api["modules"]: @@ -30,9 +28,7 @@ def test_no_removed_names_from_any_package(compas_api): mismatches[module_name] = [] mismatches[module_name].append(name) - assert len(mismatches) == 0, "The following names are missing from the API: " + str( - mismatches - ) + assert len(mismatches) == 0, "The following names are missing from the API: " + str(mismatches) @pytest.fixture @@ -62,9 +58,7 @@ def get_names_in_module(module_name): [ i for i in all_names - if not i.startswith("_") - and i not in exceptions - and not inspect.ismodule(getattr(module, i)) + if not i.startswith("_") and i not in exceptions and not inspect.ismodule(getattr(module, i)) ] ) @@ -103,21 +97,13 @@ def get_names_in_module(module_name): # but it is not supposed to be in there if compas_api["metadata"]["compas_version"] == "1.0.0": name = "compas.datastructures" - compas_api["modules"][name] = [ - m for m in compas_api["modules"][name] if m not in ("IPY") - ] + compas_api["modules"][name] = [m for m in compas_api["modules"][name] if m not in ("IPY")] name = "compas.robots" - compas_api["modules"][name] = [ - m - for m in compas_api["modules"][name] - if m not in ("Frame", "Transformation") - ] + compas_api["modules"][name] = [m for m in compas_api["modules"][name] if m not in ("Frame", "Transformation")] name = "compas.geometry" - compas_api["modules"][name] = [ - m for m in compas_api["modules"][name] if m not in ("pluggable") - ] + compas_api["modules"][name] = [m for m in compas_api["modules"][name] if m not in ("pluggable")] fname = compas_api_filename() with open(fname, "w") as f: diff --git a/tests/compas/utilities/test_itertools.py b/tests/compas/utilities/test_itertools.py index eac6cdf7762f..b5026a0d8acc 100644 --- a/tests/compas/utilities/test_itertools.py +++ b/tests/compas/utilities/test_itertools.py @@ -31,9 +31,7 @@ def test_iterable_like_generator_and_list(target, base, fillvalue): assert a == ["a", "b"] -@pytest.mark.parametrize( - ("mesh_a", "mesh_b"), [("faces.obj", "hypar.obj"), ("hypar.obj", "faces.obj")] -) +@pytest.mark.parametrize(("mesh_a", "mesh_b"), [("faces.obj", "hypar.obj"), ("hypar.obj", "faces.obj")]) def test_iterable_cap_generator(mesh_a, mesh_b): ma = Mesh.from_obj(compas.get(mesh_a)) mb = Mesh.from_obj(compas.get(mesh_b)) diff --git a/tests/compas/utilities/test_itertools_.py b/tests/compas/utilities/test_itertools_.py index eac6cdf7762f..b5026a0d8acc 100644 --- a/tests/compas/utilities/test_itertools_.py +++ b/tests/compas/utilities/test_itertools_.py @@ -31,9 +31,7 @@ def test_iterable_like_generator_and_list(target, base, fillvalue): assert a == ["a", "b"] -@pytest.mark.parametrize( - ("mesh_a", "mesh_b"), [("faces.obj", "hypar.obj"), ("hypar.obj", "faces.obj")] -) +@pytest.mark.parametrize(("mesh_a", "mesh_b"), [("faces.obj", "hypar.obj"), ("hypar.obj", "faces.obj")]) def test_iterable_cap_generator(mesh_a, mesh_b): ma = Mesh.from_obj(compas.get(mesh_a)) mb = Mesh.from_obj(compas.get(mesh_b)) From 904297e3a1ee10f2297ccacee9df395f1b49cab0 Mon Sep 17 00:00:00 2001 From: Gonzalo Casas Date: Tue, 4 Oct 2022 23:20:19 +0200 Subject: [PATCH 4/4] black reformat --- src/compas_rhino/geometry/brep/face.py | 8 ++------ src/compas_rhino/geometry/surfaces/surface.py | 8 ++------ 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/src/compas_rhino/geometry/brep/face.py b/src/compas_rhino/geometry/brep/face.py index d9ff52edd2ee..26250e22a3cf 100644 --- a/src/compas_rhino/geometry/brep/face.py +++ b/src/compas_rhino/geometry/brep/face.py @@ -75,9 +75,7 @@ def data(self, value): elif type_ == "nurbs": surface = RhinoNurbsSurface.from_data(surface) elif type_ == "torus": - raise NotImplementedError( - "Support for torus surface is not yet implemented!" - ) + raise NotImplementedError("Support for torus surface is not yet implemented!") self._surface = surface.rhino_surface # ============================================================================== @@ -121,9 +119,7 @@ def _get_surface_geometry(surface): return "cylinder", cylinder_to_compas(cast_surface) success, cast_surface = surface.TryGetTorus() if success: - raise NotImplementedError( - "Support for torus surface is not yet implemented!" - ) + raise NotImplementedError("Support for torus surface is not yet implemented!") return "nurbs", RhinoNurbsSurface.from_rhino(surface.ToNurbsSurface()) @staticmethod diff --git a/src/compas_rhino/geometry/surfaces/surface.py b/src/compas_rhino/geometry/surfaces/surface.py index 4b0b4237e1ad..1ce8f992dbf2 100644 --- a/src/compas_rhino/geometry/surfaces/surface.py +++ b/src/compas_rhino/geometry/surfaces/surface.py @@ -95,12 +95,8 @@ def from_corners(cls, corners): :class:`~compas_rhino.geometry.RhinoNurbsSurface` """ - rhino_points = [ - Rhino.Geometry.Point3d(corner.x, corner.y, corner.z) for corner in corners - ] - return cls.from_rhino( - Rhino.Geometry.NurbsSurface.CreateFromCorners(*rhino_points) - ) + rhino_points = [Rhino.Geometry.Point3d(corner.x, corner.y, corner.z) for corner in corners] + return cls.from_rhino(Rhino.Geometry.NurbsSurface.CreateFromCorners(*rhino_points)) @classmethod def from_sphere(cls, sphere):