diff --git a/Examples/RegistrationITKv4/ImageRegistration5.py b/Examples/RegistrationITKv4/ImageRegistration5.py index 7687af23a8f..5a4f9b6d5e2 100644 --- a/Examples/RegistrationITKv4/ImageRegistration5.py +++ b/Examples/RegistrationITKv4/ImageRegistration5.py @@ -126,10 +126,7 @@ ) print( "Translation: %f, %f" - % ( - initialParameters.GetElement(3), - initialParameters.GetElement(4), - ) + % (initialParameters.GetElement(3), initialParameters.GetElement(4)) ) diff --git a/Modules/Core/Mesh/wrapping/test/itkMeshArrayPixelTypeTest.py b/Modules/Core/Mesh/wrapping/test/itkMeshArrayPixelTypeTest.py index 33e708de9e6..29f82ecca67 100644 --- a/Modules/Core/Mesh/wrapping/test/itkMeshArrayPixelTypeTest.py +++ b/Modules/Core/Mesh/wrapping/test/itkMeshArrayPixelTypeTest.py @@ -28,7 +28,7 @@ # Create Vector Container and Store values in it for each Point # For windows use itk.ULL -if hasattr(itk.VectorContainer, 'ULAD'): +if hasattr(itk.VectorContainer, "ULAD"): IdentifierType = itk.UL else: IdentifierType = itk.ULL @@ -41,7 +41,7 @@ pixel_data_reference.SetSize(PixelDataSize) pixel_data_reference.Fill(0) pixel_data_reference[0] = i - pixel_data_reference[4] = i+4 + pixel_data_reference[4] = i + 4 # Set the point data container mesh.SetPointData(v) @@ -49,8 +49,8 @@ assert mesh.GetPointData().Size() == NumberOfPoints assert mesh.GetPointData().ElementAt(0)[0] == 0 assert mesh.GetPointData().ElementAt(0)[4] == 4 -assert mesh.GetPointData().ElementAt(2)[0] == 2+0 -assert mesh.GetPointData().ElementAt(2)[4] == 2+4 +assert mesh.GetPointData().ElementAt(2)[0] == 2 + 0 +assert mesh.GetPointData().ElementAt(2)[4] == 2 + 4 # resize the PixelDataSize to see if it can be altered succesfully PixelDataSize = 10 @@ -59,10 +59,10 @@ pixel_data_reference.SetSize(PixelDataSize) pixel_data_reference.Fill(0) pixel_data_reference[0] = i - pixel_data_reference[9] = i+10 + pixel_data_reference[9] = i + 10 assert mesh.GetPointData().Size() == NumberOfPoints assert mesh.GetPointData().ElementAt(0)[0] == 0 assert mesh.GetPointData().ElementAt(0)[9] == 10 -assert mesh.GetPointData().ElementAt(2)[0] == 2+0 -assert mesh.GetPointData().ElementAt(2)[9] == 2+10 +assert mesh.GetPointData().ElementAt(2)[0] == 2 + 0 +assert mesh.GetPointData().ElementAt(2)[9] == 2 + 10 diff --git a/Modules/Filtering/ImageGrid/wrapping/test/ResampleImageFilterTest.py b/Modules/Filtering/ImageGrid/wrapping/test/ResampleImageFilterTest.py index 33699e019c4..4f7e3b638f8 100644 --- a/Modules/Filtering/ImageGrid/wrapping/test/ResampleImageFilterTest.py +++ b/Modules/Filtering/ImageGrid/wrapping/test/ResampleImageFilterTest.py @@ -130,11 +130,7 @@ resample = itk.ResampleImageFilter[ImageType, ImageType].New() interpolator = itk.WindowedSincInterpolateImageFunction[ - ImageType, - 3, - itk.HammingWindowFunction[ - 3, - ], + ImageType, 3, itk.HammingWindowFunction[3,] ].New() resample.SetInterpolator(interpolator) diff --git a/Utilities/Doxygen/datetime.py b/Utilities/Doxygen/datetime.py index a6e7953733d..12a7e20079a 100755 --- a/Utilities/Doxygen/datetime.py +++ b/Utilities/Doxygen/datetime.py @@ -16,6 +16,7 @@ # Writes the date and time in RFC 2822 format to stdout -import time +import time import sys -sys.stdout.write(time.strftime('%a, %d %b %Y %H:%M:%S +0000', time.gmtime())) + +sys.stdout.write(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())) diff --git a/Utilities/Maintenance/BuildHeaderTest.py b/Utilities/Maintenance/BuildHeaderTest.py index f8ed9f7901e..cd45d175352 100755 --- a/Utilities/Maintenance/BuildHeaderTest.py +++ b/Utilities/Maintenance/BuildHeaderTest.py @@ -48,10 +48,10 @@ "itkBSplineDeformableTransform.h", # deprecated "vtkCaptureScreen.h", # these includes require VTK "itkMultiThreader.h", # Compatibility file, it should not be used - "itkEnableIf.h", # Compatibility file, it should not be used - "itkIsSame.h", # Compatibility file, it should not be used - "itkIsBaseOf.h", # Compatibility file, it should not be used - "itkIsConvertible.h", # Compatibility file, it should not be used + "itkEnableIf.h", # Compatibility file, it should not be used + "itkIsSame.h", # Compatibility file, it should not be used + "itkIsBaseOf.h", # Compatibility file, it should not be used + "itkIsConvertible.h", # Compatibility file, it should not be used "itkViewImage.h", # Depends on VTK_RENDERING_BACKEND "QuickView.h", # Depends on VTK_RENDERING_BACKEND "itkBSplineDeformableTransformInitializer.h", diff --git a/Wrapping/Generators/Python/Tests/PyImageFilterTest.py b/Wrapping/Generators/Python/Tests/PyImageFilterTest.py index 7bcf7898c55..f60ae3836ae 100644 --- a/Wrapping/Generators/Python/Tests/PyImageFilterTest.py +++ b/Wrapping/Generators/Python/Tests/PyImageFilterTest.py @@ -20,7 +20,10 @@ import numpy as np import functools -input_image = itk.image_from_array(np.random.randint(0,255,size=(6,6), dtype=np.uint8)) +input_image = itk.image_from_array( + np.random.randint(0, 255, size=(6, 6), dtype=np.uint8) +) + def constant_output(py_image_filter, constant=42): output = py_image_filter.GetOutput() @@ -28,12 +31,15 @@ def constant_output(py_image_filter, constant=42): output.Allocate() output.FillBuffer(constant) + def constant_wrapper(f, constant=42): @functools.wraps(f) def wrapper(*args): return f(*args, constant=constant) + return wrapper + py_filter = itk.PyImageFilter.New(input_image) py_filter.SetPyGenerateData(constant_output) py_filter.Update() @@ -47,8 +53,9 @@ def wrapper(*args): assert np.all(np.asarray(output_image) == 10) # Functional interface -output_image = itk.py_image_filter(input_image, - py_generate_data=constant_wrapper(constant_output, 7)) +output_image = itk.py_image_filter( + input_image, py_generate_data=constant_wrapper(constant_output, 7) +) assert np.all(np.asarray(output_image) == 7) # PyGenerateInputRequestedRegion @@ -58,6 +65,7 @@ class CheckCalled(object): def __call__(self, py_image_filter): self.called = True + check_called = CheckCalled() assert check_called.called == False @@ -79,9 +87,10 @@ def __call__(self, py_image_filter): def enlarge_output_requested_region(py_image_filter, data): data.SetRequestedRegionToLargestPossibleRegion() + py_filter = itk.PyImageFilter.New(input_image) py_filter.SetPyGenerateData(constant_output) -requested_region = itk.ImageRegion[2]([2,2], [3,3]) +requested_region = itk.ImageRegion[2]([2, 2], [3, 3]) py_filter.GetOutput().SetRequestedRegion(requested_region) py_filter.Update() region = py_filter.GetOutput().GetRequestedRegion() diff --git a/Wrapping/Generators/Python/Tests/PythonTypeTest.py b/Wrapping/Generators/Python/Tests/PythonTypeTest.py index f3a700cdb6c..167d83536a3 100644 --- a/Wrapping/Generators/Python/Tests/PythonTypeTest.py +++ b/Wrapping/Generators/Python/Tests/PythonTypeTest.py @@ -83,13 +83,7 @@ def create_and_test(t, create_method): except Exception as e: msg = ( "%s, %s: wrong Python class name: %s. " - "Exception while evaluating it: %s" - % ( - t, - actual_type, - obj_type, - e, - ) + "Exception while evaluating it: %s" % (t, actual_type, obj_type, e) ) wrongType = 1 if wrongType: diff --git a/Wrapping/Generators/Python/Tests/extras.py b/Wrapping/Generators/Python/Tests/extras.py index 96dc4284329..970ac188561 100644 --- a/Wrapping/Generators/Python/Tests/extras.py +++ b/Wrapping/Generators/Python/Tests/extras.py @@ -175,7 +175,9 @@ def custom_callback(name, progress): image.SetDirection(rotation) serialize_deserialize = pickle.loads(pickle.dumps(image)) # verify_input_information checks origin, spacing, direction consistency -comparison = itk.comparison_image_filter(image, serialize_deserialize, verify_input_information=True) +comparison = itk.comparison_image_filter( + image, serialize_deserialize, verify_input_information=True +) assert np.sum(comparison) == 0.0 # Make sure we can read unsigned short, unsigned int, and cast @@ -416,11 +418,13 @@ def custom_callback(name, progress): # and make sure that the matrix hasn't changed. assert m_itk(0, 0) == 1 # Test __repr__ -assert repr(m_itk) == "itkMatrixD33 ([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])" +assert ( + repr(m_itk) == "itkMatrixD33 ([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])" +) # Test __array__ assert np.array_equal(np.asarray(m_itk), np.eye(3)) # Test array like input -arr3 = [[0., 0.], [0., 0.]] +arr3 = [[0.0, 0.0], [0.0, 0.0]] m_itk = itk.matrix_from_array(arr3) m_itk.SetIdentity() # Test that the array like has not changed,... diff --git a/Wrapping/Generators/Python/itk/__init__.py b/Wrapping/Generators/Python/itk/__init__.py index 140ddd7e0b2..1b6c0d7af59 100644 --- a/Wrapping/Generators/Python/itk/__init__.py +++ b/Wrapping/Generators/Python/itk/__init__.py @@ -138,17 +138,22 @@ def _dedup(seq): # Check if the module installed its own init file and load it. # ITK Modules __init__.py must be renamed to __init_{module_name}__.py before packaging # the wheel to avoid overriding this file on installation. - module_init_file = os.path.join(os.path.dirname(__file__), "__init_" + module.lower() + "__.py") + module_init_file = os.path.join( + os.path.dirname(__file__), "__init_" + module.lower() + "__.py" + ) if not os.path.isfile(module_init_file): continue # Load the module definition from file path - spec = importlib.util.spec_from_file_location(f"{module}.__init__", module_init_file) + spec = importlib.util.spec_from_file_location( + f"{module}.__init__", module_init_file + ) # Import and execute the __init__ file (this call will add the module binaries to sys path) loaded_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(loaded_module) + # After 'lifting' external symbols into this itk namespace, # Now do the initialization, and conversion to LazyLoading if necessary _initialize_module() diff --git a/Wrapping/Generators/Python/itk/support/base.py b/Wrapping/Generators/Python/itk/support/base.py index 75682862098..b9c60ec8069 100644 --- a/Wrapping/Generators/Python/itk/support/base.py +++ b/Wrapping/Generators/Python/itk/support/base.py @@ -187,9 +187,7 @@ def itk_load_swig_module(name: str, namespace=None): template_feature.get_cpp_class_name(), swig_class ) setattr( - this_module, - template_feature.get_python_class_name(), - swig_class, + this_module, template_feature.get_python_class_name(), swig_class ) if namespace is not None: current_value = namespace.get( diff --git a/Wrapping/Generators/Python/itk/support/extras.py b/Wrapping/Generators/Python/itk/support/extras.py index 76633c3a5d2..3a60915c9ed 100644 --- a/Wrapping/Generators/Python/itk/support/extras.py +++ b/Wrapping/Generators/Python/itk/support/extras.py @@ -469,7 +469,7 @@ def vector_container_from_array(arr: ArrayLike, ttype=None) -> "itkt.VectorConta arr = np.asarray(arr) # Return VectorContainer with 64-bit index type - if os.name == 'nt': + if os.name == "nt": IndexType = itk.ULL else: IndexType = itk.UL @@ -825,7 +825,7 @@ def dict_from_image(image: "itkt.Image") -> Dict: spacing=tuple(image.GetSpacing()), size=tuple(image.GetBufferedRegion().GetSize()), direction=np.asarray(image.GetDirection()), - data=pixel_arr + data=pixel_arr, ) @@ -833,11 +833,11 @@ def image_from_dict(image_dict: Dict) -> "itkt.Image": """Deserialize an dictionary representing an itk.Image object.""" import itk - ImageType = image_type_from_wasm_type(image_dict['imageType']) - image = itk.PyBuffer[ImageType].GetImageViewFromArray(image_dict['data']) - image.SetOrigin(image_dict['origin']) - image.SetSpacing(image_dict['spacing']) - image.SetDirection(image_dict['direction']) + ImageType = image_type_from_wasm_type(image_dict["imageType"]) + image = itk.PyBuffer[ImageType].GetImageViewFromArray(image_dict["data"]) + image.SetOrigin(image_dict["origin"]) + image.SetSpacing(image_dict["spacing"]) + image.SetDirection(image_dict["direction"]) return image diff --git a/Wrapping/Generators/Python/itk/support/helpers.py b/Wrapping/Generators/Python/itk/support/helpers.py index 16130c69480..b2e6b55a7b0 100644 --- a/Wrapping/Generators/Python/itk/support/helpers.py +++ b/Wrapping/Generators/Python/itk/support/helpers.py @@ -183,73 +183,87 @@ def wasm_type_from_image_type(itkimage): # noqa: C901 component = itk.template(itkimage)[1][0] if component == itk.UL: - if os.name == 'nt': - return 'uint32', 'Scalar' + if os.name == "nt": + return "uint32", "Scalar" else: - return 'uint64', 'Scalar' + return "uint64", "Scalar" mangle = None - pixelType = 'Scalar' + pixelType = "Scalar" if component == itk.SL: - if os.name == 'nt': - return 'int32', 'Scalar', + if os.name == "nt": + return "int32", "Scalar" else: - return 'int64', 'Scalar', - if component in (itk.SC, itk.UC, itk.SS, itk.US, itk.SI, itk.UI, itk.F, - itk.D, itk.B, itk.SL, itk.SLL, itk.UL, itk.ULL): + return "int64", "Scalar" + if component in ( + itk.SC, + itk.UC, + itk.SS, + itk.US, + itk.SI, + itk.UI, + itk.F, + itk.D, + itk.B, + itk.SL, + itk.SLL, + itk.UL, + itk.ULL, + ): mangle = component elif component in [i[1] for i in itk.Vector.items()]: mangle = itk.template(component)[1][0] - pixelType = 'Vector' + pixelType = "Vector" elif component == itk.complex[itk.F]: - return 'float32', 'Complex' + return "float32", "Complex" elif component == itk.complex[itk.D]: - return 'float64', 'Complex' + return "float64", "Complex" elif component in [i[1] for i in itk.CovariantVector.items()]: mangle = itk.template(component)[1][0] - pixelType = 'CovariantVector', + pixelType = ("CovariantVector",) elif component in [i[1] for i in itk.Offset.items()]: - return 'int64', 'Offset' + return "int64", "Offset" elif component in [i[1] for i in itk.FixedArray.items()]: mangle = itk.template(component)[1][0] - pixelType = 'FixedArray' + pixelType = "FixedArray" elif component in [i[1] for i in itk.RGBAPixel.items()]: mangle = itk.template(component)[1][0] - pixelType = 'RGBA' + pixelType = "RGBA" elif component in [i[1] for i in itk.RGBPixel.items()]: mangle = itk.template(component)[1][0] - pixelType = 'RGB' + pixelType = "RGB" elif component in [i[1] for i in itk.SymmetricSecondRankTensor.items()]: # SymmetricSecondRankTensor mangle = itk.template(component)[1][0] - pixelType = 'SymmetrySecondRankTensor' + pixelType = "SymmetrySecondRankTensor" else: - raise RuntimeError('Unrecognized component type: {0}'.format(str(component))) + raise RuntimeError("Unrecognized component type: {0}".format(str(component))) def _long_type(): - if os.name == 'nt': - return 'int32' + if os.name == "nt": + return "int32" else: - return 'int64' + return "int64" + _python_to_js = { - itk.SC: 'int8', - itk.UC: 'uint8', - itk.SS: 'int16', - itk.US: 'uint16', - itk.SI: 'int32', - itk.UI: 'uint32', - itk.F: 'float32', - itk.D: 'float64', - itk.B: 'uint8', + itk.SC: "int8", + itk.UC: "uint8", + itk.SS: "int16", + itk.US: "uint16", + itk.SI: "int32", + itk.UI: "uint32", + itk.F: "float32", + itk.D: "float64", + itk.B: "uint8", itk.SL: _long_type(), - itk.UL: 'u' + _long_type(), - itk.SLL: 'int64', - itk.ULL: 'uint64', + itk.UL: "u" + _long_type(), + itk.SLL: "int64", + itk.ULL: "uint64", } imageType = dict( dimension=itkimage.GetImageDimension(), componentType=_python_to_js[mangle], pixelType=pixelType, - components=itkimage.GetNumberOfComponentsPerPixel() + components=itkimage.GetNumberOfComponentsPerPixel(), ) return imageType @@ -258,44 +272,45 @@ def image_type_from_wasm_type(jstype): import itk _pixelType_to_prefix = { - 'Scalar': '', - 'RGB': 'RGB', - 'RGBA': 'RGBA', - 'Offset': 'O', - 'Vector': 'V', - 'CovariantVector': 'CV', - 'SymmetricSecondRankTensor': 'SSRT', - 'FixedArray': 'FA' + "Scalar": "", + "RGB": "RGB", + "RGBA": "RGBA", + "Offset": "O", + "Vector": "V", + "CovariantVector": "CV", + "SymmetricSecondRankTensor": "SSRT", + "FixedArray": "FA", } - pixelType = jstype['pixelType'] - dimension = jstype['dimension'] - if pixelType == 'Complex': - if jstype['componentType'] == 'float32': + pixelType = jstype["pixelType"] + dimension = jstype["dimension"] + if pixelType == "Complex": + if jstype["componentType"] == "float32": return itk.Image[itk.complex, itk.F], np.float32 else: return itk.Image[itk.complex, itk.D], np.float64 def _long_type(): - if os.name == 'nt': - return 'LL' + if os.name == "nt": + return "LL" else: - return 'L' + return "L" + prefix = _pixelType_to_prefix[pixelType] _js_to_python = { - 'int8': 'SC', - 'uint8': 'UC', - 'int16': 'SS', - 'uint16': 'US', - 'int32': 'SI', - 'uint32': 'UI', - 'int64': 'S' + _long_type(), - 'uint64': 'U' + _long_type(), - 'float32': 'F', - 'float64': 'D' + "int8": "SC", + "uint8": "UC", + "int16": "SS", + "uint16": "US", + "int32": "SI", + "uint32": "UI", + "int64": "S" + _long_type(), + "uint64": "U" + _long_type(), + "float32": "F", + "float64": "D", } - if pixelType != 'Offset': - prefix += _js_to_python[jstype['componentType']] - if pixelType not in ('Scalar', 'RGB', 'RGBA', 'Complex'): + if pixelType != "Offset": + prefix += _js_to_python[jstype["componentType"]] + if pixelType not in ("Scalar", "RGB", "RGBA", "Complex"): prefix += str(dimension) prefix += str(dimension) return getattr(itk.Image, prefix) diff --git a/Wrapping/Generators/SwigInterface/igenerator.py b/Wrapping/Generators/SwigInterface/igenerator.py index e10bc090db5..886acdb556a 100755 --- a/Wrapping/Generators/SwigInterface/igenerator.py +++ b/Wrapping/Generators/SwigInterface/igenerator.py @@ -1617,17 +1617,9 @@ def create_interfacefile(self, interfaceFile, idxFile, wrappersNamespace): typedef.name.replace("_Superclass", "") ) # Skip wrapping for the following - if ( - typedef.name.endswith( - ( - "_Pointer", - "_AutoPointer", - "_ConstPointer", - "Factory", - ) - ) - or self.current_class in ["stdcomplex", "stdnumeric_limits"] - ): + if typedef.name.endswith( + ("_Pointer", "_AutoPointer", "_ConstPointer", "Factory") + ) or self.current_class in ["stdcomplex", "stdnumeric_limits"]: self.current_class = None elif self.current_class not in self.classes: self.classes[self.current_class] = ITKClass(self.current_class) @@ -1745,7 +1737,9 @@ def init_submodule_pyi_template_file(pyiFile: Path, submodule_name: str) -> None ) -def init_submodule_pyi_proxy_file(pyiFile: Path, submodule_name: str, parent_imports) -> None: +def init_submodule_pyi_proxy_file( + pyiFile: Path, submodule_name: str, parent_imports +) -> None: with open(pyiFile, "w") as pyiFile: pyiFile.write( f"""# Interface methods for submodule: {submodule_name} @@ -1758,19 +1752,17 @@ def init_submodule_pyi_proxy_file(pyiFile: Path, submodule_name: str, parent_imp ) -def write_class_template_pyi( - pyiFile: Path, class_name: str, header_code: str -) -> None: +def write_class_template_pyi(pyiFile: Path, class_name: str, header_code: str) -> None: # Write interface files to the stub directory to support editor autocompletion with open(pyiFile, "a+") as pyiFile: pyiFile.write(f"# Interface for class: {class_name}\n") - pyiFile.write(f"from ._proxies import {class_name}Proxy as _{class_name}Proxy\n") + pyiFile.write( + f"from ._proxies import {class_name}Proxy as _{class_name}Proxy\n" + ) pyiFile.write(header_code) -def write_class_proxy_pyi( - pyiFile: Path, class_name: str, interfaces_code: str -) -> None: +def write_class_proxy_pyi(pyiFile: Path, class_name: str, interfaces_code: str) -> None: # Write interface files to the stub directory to support editor autocompletion with open(pyiFile, "a+") as pyiFile: pyiFile.write(f"# Interface methods for class: {class_name}\n") @@ -2005,27 +1997,31 @@ def generate_swig_input(submoduleName, classes): Path(f"{options.pyi_dir}/{submoduleName}Template.pyi"), submoduleName ) init_submodule_pyi_proxy_file( - Path(f"{options.pyi_dir}/{submoduleName}Proxy.pyi"), submoduleName, parent_imports + Path(f"{options.pyi_dir}/{submoduleName}Proxy.pyi"), + submoduleName, + parent_imports, ) if options.pyi_dir != "": - for itk_class in classes.keys(): - outputPYIHeaderFile = StringIO() - outputPYIMethodFile = StringIO() - generate_class_pyi_def( - outputPYIHeaderFile, outputPYIMethodFile, classes[itk_class] - ) + for itk_class in classes.keys(): + outputPYIHeaderFile = StringIO() + outputPYIMethodFile = StringIO() + generate_class_pyi_def( + outputPYIHeaderFile, outputPYIMethodFile, classes[itk_class] + ) - write_class_template_pyi( - Path(f"{options.pyi_dir}/{classes[itk_class].submodule_name}Template.pyi"), - itk_class, - outputPYIHeaderFile.getvalue(), - ) - write_class_proxy_pyi( - Path(f"{options.pyi_dir}/{classes[itk_class].submodule_name}Proxy.pyi"), - itk_class, - outputPYIMethodFile.getvalue(), - ) + write_class_template_pyi( + Path( + f"{options.pyi_dir}/{classes[itk_class].submodule_name}Template.pyi" + ), + itk_class, + outputPYIHeaderFile.getvalue(), + ) + write_class_proxy_pyi( + Path(f"{options.pyi_dir}/{classes[itk_class].submodule_name}Proxy.pyi"), + itk_class, + outputPYIMethodFile.getvalue(), + ) snake_case_file = options.snake_case_file if len(snake_case_file) > 1: