diff --git a/doc/changelog.d/495.miscellaneous.md b/doc/changelog.d/495.miscellaneous.md new file mode 100644 index 000000000..691aae33c --- /dev/null +++ b/doc/changelog.d/495.miscellaneous.md @@ -0,0 +1 @@ +remove ruff E ignores \ No newline at end of file diff --git a/doc/source/_static/thumbnails/moving_car_workflow_example_using_script_layer.PNG b/doc/source/_static/thumbnails/workflow_moving_car.PNG similarity index 100% rename from doc/source/_static/thumbnails/moving_car_workflow_example_using_script_layer.PNG rename to doc/source/_static/thumbnails/workflow_moving_car.PNG diff --git a/doc/source/_static/thumbnails/how_to_open_result_using_workflow_method.png b/doc/source/_static/thumbnails/workflow_open_result.png similarity index 100% rename from doc/source/_static/thumbnails/how_to_open_result_using_workflow_method.png rename to doc/source/_static/thumbnails/workflow_open_result.png diff --git a/doc/source/conf.py b/doc/source/conf.py index faa1611bb..8a221f5d1 100755 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -132,8 +132,8 @@ "examples/kernel/object-link": "_static/thumbnails/pySpeos_520x520.png", "examples/kernel/scene-job": "_static/thumbnails/pySpeos_520x520.png", "examples/kernel/modify-scene": "_static/thumbnails/pySpeos_520x520.png", - "examples/workflow/open-result": "_static/thumbnails/how_to_open_result_using_workflow_method.png", - "examples/workflow/combine-speos": "_static/thumbnails/moving_car_workflow_example_using_script_layer.PNG", + "examples/workflow/open-result": "_static/thumbnails/workflow_open_result.png", + "examples/workflow/combine-speos": "_static/thumbnails/workflow_moving_car.PNG", } nbsphinx_prompt_width = "" nbsphinx_prolog = """ @@ -194,7 +194,13 @@ def copy_examples_to_output_dir(app: sphinx.application.Sphinx, exception: Excep OUTPUT_CORE = OUTPUT_EXAMPLES / "core" OUTPUT_KERNEL = OUTPUT_EXAMPLES / "kernel" OUTPUT_WORKFLOW = OUTPUT_EXAMPLES / "workflow" - for directory in [OUTPUT_EXAMPLES, OUTPUT_IMAGES, OUTPUT_CORE, OUTPUT_KERNEL, OUTPUT_WORKFLOW]: + for directory in [ + OUTPUT_EXAMPLES, + OUTPUT_IMAGES, + OUTPUT_CORE, + OUTPUT_KERNEL, + OUTPUT_WORKFLOW, + ]: if not directory.exists(): directory.mkdir(parents=True, exist_ok=True) diff --git a/examples/core/lpf-preview.py b/examples/core/lpf-preview.py index 14443da07..9f7d9c21f 100644 --- a/examples/core/lpf-preview.py +++ b/examples/core/lpf-preview.py @@ -26,12 +26,16 @@ # User can preview the part and mesh information. -# By providing viz_args to the preview function, project part can be viewed in a semi-transparent way. +# By providing viz_args to the preview function, project part can be viewed in a semi-transparent +# way. # It can be found there is volume conflict in this project. # + -p = Project(speos=speos, path=str(tests_data_path / "error_data.speos" / "error_data.speos")) +p = Project( + speos=speos, + path=str(tests_data_path / "error_data.speos" / "error_data.speos"), +) p.preview(viz_args={"opacity": 0.7}) # - @@ -79,7 +83,8 @@ # ## Preview the light expert result with error filter -# ray_filter option is provided in the preview function that user can filter the rays to see only rays in error. +# ray_filter option is provided in the preview function that user can filter the rays to see only +# rays in error. # In this example, error rays are generated due to a volume conflict between two solids. diff --git a/examples/core/opt-prop.py b/examples/core/opt-prop.py index 95ea0bfa2..a419c4280 100644 --- a/examples/core/opt-prop.py +++ b/examples/core/opt-prop.py @@ -90,7 +90,8 @@ # Sometimes it is needed to create property but only for surface. -# In this case, no call for set_volume_xxx function is needed, and we will select a face for the geometries. +# In this case, no call for set_volume_xxx function is needed, and we will select a face for the +# geometries. # + op3 = p.create_optical_property(name="Material.FOP") @@ -161,7 +162,8 @@ # ## Update -# Tipp: if you are manipulating an optical property already committed, don't forget to commit your changes. +# Tipp: if you are manipulating an optical property already committed, don't forget to commit your +# changes. # If you don't, you will still only watch what is committed on the server. @@ -185,7 +187,8 @@ # ## Delete -# Once the data is deleted from the server, you can still work with local data and maybe commit later. +# Once the data is deleted from the server, you can still work with local data and maybe commit +# later. # + op2.delete() diff --git a/examples/core/part.py b/examples/core/part.py index a878026f3..47d8e824b 100644 --- a/examples/core/part.py +++ b/examples/core/part.py @@ -53,7 +53,8 @@ # - # ### Create faces inside a body. -# A body can have one (example, surface/open-volume type of body) or multiple faces (close-volume type of body). +# A body can have one (example, surface/open-volume type of body) or multiple faces +# (close-volume type of body). # Each face is then defined by a number of triangles/facets. @@ -176,7 +177,8 @@ # - -# If you want to retrieve several kind of geometry features at a certain level, give feature_type=Part +# If you want to retrieve several kind of geometry features at a certain level, give +# feature_type=Part # all the geometry features at root part level: diff --git a/examples/core/project.py b/examples/core/project.py index 8e04b189f..a70dc9c2a 100644 --- a/examples/core/project.py +++ b/examples/core/project.py @@ -4,9 +4,11 @@ # ## What is a project? -# A project is a speos simulation container that includes parts, material properties, sensor, sources and simulations. +# A project is a speos simulation container that includes parts, material properties, sensor, +# sources and simulations. -# In this tutorial you will learn how to create a project from scratch or from a pre-defined .speos file. +# In this tutorial you will learn how to create a project from scratch or from a pre-defined .speos +# file. # + import os @@ -205,6 +207,7 @@ from ansys.speos.core.workflow.open_result import open_result_image open_result_image( - simulation_feature=sim_feat, result_name="ASSEMBLY1.DS (0).Dom Irradiance Sensor (0).xmp" + simulation_feature=sim_feat, + result_name="ASSEMBLY1.DS (0).Dom Irradiance Sensor (0).xmp", ) # - diff --git a/examples/core/sensor.py b/examples/core/sensor.py index 22656cdba..b4088e04c 100644 --- a/examples/core/sensor.py +++ b/examples/core/sensor.py @@ -8,7 +8,11 @@ from pathlib import Path from ansys.speos.core import Project, Speos -from ansys.speos.core.sensor import SensorCamera, SensorIrradiance, SensorRadiance +from ansys.speos.core.sensor import ( + SensorCamera, + SensorIrradiance, + SensorRadiance, +) # If using docker container tests_data_path = Path("/app") / "assets" @@ -59,7 +63,8 @@ # ## Push it to the server. -# Now that it is committed to the server, the mention "local: " is no more present when printing the sensor. +# Now that it is committed to the server, the mention "local: " is no more present when printing the +# sensor. # + sensor1.commit() @@ -146,7 +151,8 @@ # ## Delete -# Once the data is deleted from the server, you can still work with local data and maybe commit later. +# Once the data is deleted from the server, you can still work with local data and maybe commit +# later. # + sensor2.delete() diff --git a/examples/core/simulation.py b/examples/core/simulation.py index 78f8e14b6..56862e30f 100644 --- a/examples/core/simulation.py +++ b/examples/core/simulation.py @@ -37,7 +37,8 @@ # ## Prepare prerequisites -# Create the necessary elements for a simulation: Sensor, source, root part, optical property are prerequisites. +# Create the necessary elements for a simulation: Sensor, source, root part, optical property are +# prerequisites. # ### Prepare the root part @@ -63,7 +64,8 @@ # + sensor1 = p.create_sensor(name="Irradiance.1") -sensor1.set_type_colorimetric() # colorimetric or spectral so that the sensor can be used both in direct and inverse simulation +# colorimetric or spectral so that the sensor can be used both in direct and inverse simulation +sensor1.set_type_colorimetric() sensor1.commit() # - @@ -72,7 +74,8 @@ # + source1 = p.create_source(name="Surface.1") source1.set_exitance_constant(geometries=[(GeoRef.from_native_link(geopath="Body.1/Face.1"), True)]) -source1.set_spectrum().set_blackbody() # blackbody so that the source can be used both in direct and inverse simulation +# blackbody so that the source can be used both in direct and inverse simulation +source1.set_spectrum().set_blackbody() source1.commit() # - diff --git a/examples/core/source.py b/examples/core/source.py index 7c4b1c440..da82ae7de 100644 --- a/examples/core/source.py +++ b/examples/core/source.py @@ -9,7 +9,11 @@ from pathlib import Path from ansys.speos.core import GeoRef, Project, Speos -from ansys.speos.core.source import SourceLuminaire, SourceRayFile, SourceSurface +from ansys.speos.core.source import ( + SourceLuminaire, + SourceRayFile, + SourceSurface, +) # If using docker container tests_data_path = Path("/app") / "assets" @@ -48,7 +52,8 @@ # ## Push it to the server. -# Now that it is committed to the server, the mention "local: " is no more present when printing the source. +# Now that it is committed to the server, the mention "local: " is no more present when printing the +# source. # + source1.commit() @@ -110,14 +115,17 @@ # + source1.set_flux_luminous() # modify to luminous flux BUT no commit -source1.reset() # reset -> this will apply the server value to the local value (then local value will be back to halogen) +source1.reset() +# reset -> this will apply the server value to the local value the local value will be back to +# halogen source1.delete() # delete (to display the local value with the below print) print(source1) # - # ## Delete -# Once the data is deleted from the server, you can still work with local data and maybe commit later. +# Once the data is deleted from the server, you can still work with local data and maybe commit +# later. # + source2.delete() diff --git a/examples/kernel/modify-scene.py b/examples/kernel/modify-scene.py index 83d4a8b46..1a9b611e5 100644 --- a/examples/kernel/modify-scene.py +++ b/examples/kernel/modify-scene.py @@ -1,24 +1,27 @@ # # How to modify scene elements -# This tutorial demonstrates how to modify a scene. For example how to modify an existing sensor, how to add a new sensor. +# This tutorial demonstrates how to modify a scene. For example how to modify an existing sensor, +# how to add a new sensor. # The logic is the same to modify sources, simulations, materials. # ## Template vs Instance # When applicable, the speos objects are separated in two different notions: template and instance. # The template represents the feature with its inherent characteristics. -# The instance represents the completion of a template by adding properties such as spatial position, link to geometry, etc. +# The instance represents the completion of a template by adding properties such as spatial +# position, link to geometry, etc. # ### Template # The template objects are handled by a manager. -# It was explained how to interact with them in the kernel-object-link example ("How to use an ObjectLink"). -# The interesting thing about the template notion is that the same template can be used several times with different properties. +# It was explained how to interact with them in the kernel-object-link example +# ("How to use an ObjectLink"). The interesting thing about the template notion is that the same +# template can be used several times with different properties. # ### Instance -# The template objects are instantiated in the Scene object, with properties needed to place them at the wanted position, -# or attached to the wanted geometry. +# The template objects are instantiated in the Scene object, with properties needed to place them at +# the wanted position, or attached to the wanted geometry. # The Scene object will gather all features that you need to run a job (compute a simulation). # + @@ -135,28 +138,27 @@ # Create protobuf message SensorTemplate sensor_t_data = ProtoSensorTemplate(name="CameraFromScratch") -sensor_t_data.camera_sensor_template.sensor_mode_photometric.acquisition_integration = 0.01 -sensor_t_data.camera_sensor_template.sensor_mode_photometric.acquisition_lag_time = 0 -sensor_t_data.camera_sensor_template.sensor_mode_photometric.transmittance_file_uri = str( +photometric = sensor_t_data.camera_sensor_template.sensor_mode_photometric +photometric.acquisition_integration = 0.01 +photometric.acquisition_lag_time = 0 +photometric.transmittance_file_uri = str( tests_data_path / "CameraInputFiles" / "CameraTransmittance.spectrum" ) -sensor_t_data.camera_sensor_template.sensor_mode_photometric.gamma_correction = 2.2 -sensor_t_data.camera_sensor_template.sensor_mode_photometric.png_bits = ( - camera_sensor_pb2.EnumSensorCameraPNGBits.PNG_16 -) -sensor_t_data.camera_sensor_template.sensor_mode_photometric.color_mode_color.red_spectrum_file_uri = str( +photometric.gamma_correction = 2.2 +photometric.png_bits = camera_sensor_pb2.EnumSensorCameraPNGBits.PNG_16 +photometric.color_mode_color.red_spectrum_file_uri = str( tests_data_path / "CameraInputFiles" / "CameraSensitivityRed.spectrum" ) -sensor_t_data.camera_sensor_template.sensor_mode_photometric.color_mode_color.green_spectrum_file_uri = str( +photometric.color_mode_color.green_spectrum_file_uri = str( tests_data_path / "CameraInputFiles" / "CameraSensitivityGreen.spectrum" ) -sensor_t_data.camera_sensor_template.sensor_mode_photometric.color_mode_color.blue_spectrum_file_uri = str( +photometric.color_mode_color.blue_spectrum_file_uri = str( tests_data_path / "CameraInputFiles" / "CameraSensitivityBlue.spectrum" ) -sensor_t_data.camera_sensor_template.sensor_mode_photometric.color_mode_color.balance_mode_none.SetInParent() -sensor_t_data.camera_sensor_template.sensor_mode_photometric.wavelengths_range.w_start = 400 -sensor_t_data.camera_sensor_template.sensor_mode_photometric.wavelengths_range.w_end = 700 -sensor_t_data.camera_sensor_template.sensor_mode_photometric.wavelengths_range.w_sampling = 13 +photometric.color_mode_color.balance_mode_none.SetInParent() +photometric.wavelengths_range.w_start = 400 +photometric.wavelengths_range.w_end = 700 +photometric.wavelengths_range.w_sampling = 13 sensor_t_data.camera_sensor_template.focal_length = 5 sensor_t_data.camera_sensor_template.imager_distance = 10 sensor_t_data.camera_sensor_template.f_number = 20 @@ -177,7 +179,9 @@ # + camera_i_2 = ProtoScene.SensorInstance(name=sensor_t_new.get().name + ".1") -camera_i_2.sensor_guid = sensor_t_new.key # An instance has to reference a template - here we use the SensorTemplateLink's key that we got just above. +# An instance has to reference a template - here we use the SensorTemplateLink's key that we got +camera_i_2.sensor_guid = sensor_t_new.key +# just above. camera_i_2.camera_properties.axis_system.extend( [50, 50, 50, 1, 0, 0, 0, 1, 0, 0, 0, 1] ) # Choose axis system @@ -192,7 +196,8 @@ # Modify scene datamodel to add our camera instance my_scene_data.sensors.append(camera_i_2) -# We can also reference it in the first simulation, so that it will be taken into account by this simulation +# We can also reference it in the first simulation, so that it will be taken into account by this +# simulation my_scene_data.simulations[0].sensor_paths.append(camera_i_2.name) # We reference by name # Update value in db @@ -202,7 +207,8 @@ print(my_scene) # - -# When loading a speos file into a scene, this creates many objects (source templates, sensor templates, vop template, sop templates). +# When loading a speos file into a scene, this creates many objects +# (source templates, sensor templates, vop template, sop templates). # Then at the end of the example, we just clean all databases # + diff --git a/examples/kernel/object-link.py b/examples/kernel/object-link.py index b712af29a..ce32608a2 100644 --- a/examples/kernel/object-link.py +++ b/examples/kernel/object-link.py @@ -4,7 +4,8 @@ # ## What is an ObjectLink? -# The ObjectLink is an object that is created from a protobuf message and then stored in the server database. +# The ObjectLink is an object that is created from a protobuf message and then stored in the server +# database. # ## Which speos objects are used via ObjectLink? diff --git a/examples/kernel/scene-job.py b/examples/kernel/scene-job.py index cbece4a56..c41e5776a 100644 --- a/examples/kernel/scene-job.py +++ b/examples/kernel/scene-job.py @@ -49,7 +49,8 @@ # ## Job -# Create a job for the first simulation. When loaded from a speos file, there is always only one simulation in the scene. +# Create a job for the first simulation. When loaded from a speos file, there is always only one +# simulation in the scene. # + # First create the protobuf message @@ -96,8 +97,8 @@ # Retrieve results of the job -# Two results are generated : the result of irradiance sensor: ASSEMBLY1.DS (0).Dom Irradiance Sensor (0).xmp -# and the simulation report in html +# Two results are generated : the result of irradiance sensor: +# "ASSEMBLY1.DS (0).Dom Irradiance Sensor (0).xmp" and the simulation report in html # + results = job_link.get_results().results @@ -111,7 +112,8 @@ # - -# When loading a speos file into a scene, this creates many objects (source templates, sensor templates, vop template, sop templates). +# When loading a speos file into a scene, this creates many objects +# (source templates, sensor templates, vop template, sop templates). # Then at the end of the example, we just clean all databases # + diff --git a/examples/workflow/combine-speos.py b/examples/workflow/combine-speos.py index 7fd22d464..7c04e7f08 100644 --- a/examples/workflow/combine-speos.py +++ b/examples/workflow/combine-speos.py @@ -10,7 +10,10 @@ from ansys.speos.core.sensor import SensorCamera from ansys.speos.core.simulation import SimulationInverse from ansys.speos.core.source import SourceLuminaire -from ansys.speos.core.workflow.combine_speos import SpeosFileInstance, combine_speos +from ansys.speos.core.workflow.combine_speos import ( + SpeosFileInstance, + combine_speos, +) # If using docker container tests_data_path = Path("/app") / "assets" @@ -41,11 +44,37 @@ ), SpeosFileInstance( speos_file=str(tests_data_path / "BlueCar.speos" / "BlueCar.speos"), - axis_system=[2000, 0, 35000, 0.0, 0.0, -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0], + axis_system=[ + 2000, + 0, + 35000, + 0.0, + 0.0, + -1.0, + -1.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + ], ), SpeosFileInstance( speos_file=str(tests_data_path / "RedCar.speos" / "RedCar.speos"), - axis_system=[-4000, 0, 48000, 1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0], + axis_system=[ + -4000, + 0, + 48000, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 1.0, + 0.0, + ], ), ], ) diff --git a/examples/workflow/open-result.py b/examples/workflow/open-result.py index 58719f57f..45454f583 100644 --- a/examples/workflow/open-result.py +++ b/examples/workflow/open-result.py @@ -59,7 +59,8 @@ from ansys.speos.core.workflow.open_result import open_result_image open_result_image( - simulation_feature=sim, result_name="ASSEMBLY1.DS (0).Dom Irradiance Sensor (0).xmp" + simulation_feature=sim, + result_name="ASSEMBLY1.DS (0).Dom Irradiance Sensor (0).xmp", ) # - @@ -74,6 +75,7 @@ from ansys.speos.core.workflow.open_result import open_result_in_viewer open_result_in_viewer( - simulation_feature=sim, result_name="ASSEMBLY1.DS (0).Dom Irradiance Sensor (0).xmp" + simulation_feature=sim, + result_name="ASSEMBLY1.DS (0).Dom Irradiance Sensor (0).xmp", ) # - diff --git a/pyproject.toml b/pyproject.toml index a8c346dc4..e274d04eb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -87,7 +87,6 @@ extend-exclude = ["tests/assets"] quote-style = "double" indent-style = "space" docstring-code-format = true -docstring-code-line-length = "dynamic" [tool.ruff.lint] select = [ @@ -100,13 +99,6 @@ select = [ "TD", # flake8-todos, https://docs.astral.sh/ruff/rules/#flake8-todos-td ] ignore = [ - "E402", - "E501", # TODO: Line too long - "E711", - "E712", # TODO: Avoid equality comparisons to `False` - "E721", # TODO: Avoid `is` and `is not` for type comparison, use `isinstance()` instead - "E722", - "E741", # TODO: Rename ambiguous variable name "F401", "F841", # TODO: Local variable assigned but never used "N802", # TODO: Function name should be lowercase @@ -120,7 +112,8 @@ ignore = [ ] [tool.ruff.lint.per-file-ignores] -"examples/*" = ["D100"] +"examples/*" = ["D100", "E402"] + [tool.ruff.lint.pydocstyle] convention = "numpy" diff --git a/src/ansys/speos/core/__init__.py b/src/ansys/speos/core/__init__.py index 0c6480227..63c010765 100644 --- a/src/ansys/speos/core/__init__.py +++ b/src/ansys/speos/core/__init__.py @@ -20,7 +20,10 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -"""PySpeos is a Python library that gathers functionalities and tools based on Speos solver remote API.""" +"""PySpeos is a Python library based on Speos solver remote API. + +It gathers functionaties and tools of these APIs. +""" try: import importlib.metadata as importlib_metadata diff --git a/src/ansys/speos/core/body.py b/src/ansys/speos/core/body.py index bf941017c..3be692f0b 100644 --- a/src/ansys/speos/core/body.py +++ b/src/ansys/speos/core/body.py @@ -82,7 +82,10 @@ def __init__( self._geom_features = [] def create_face( - self, name: str, description: str = "", metadata: Optional[Mapping[str, str]] = None + self, + name: str, + description: str = "", + metadata: Optional[Mapping[str, str]] = None, ) -> face.Face: """Create a face in this element. @@ -210,7 +213,10 @@ def delete(self) -> Body: return self def find( - self, name: str, name_regex: bool = False, feature_type: Optional[type] = None + self, + name: str, + name_regex: bool = False, + feature_type: Optional[type] = None, ) -> List[face.Face]: """Find feature(s). In a body, only faces features can be found. diff --git a/src/ansys/speos/core/intensity.py b/src/ansys/speos/core/intensity.py index ba889b60f..0cf66d24c 100644 --- a/src/ansys/speos/core/intensity.py +++ b/src/ansys/speos/core/intensity.py @@ -51,7 +51,8 @@ class Intensity: metadata : Optional[Mapping[str, str]] Metadata of the feature. By default, ``{}``. - intensity_props_to_complete : ansys.api.speos.scene.v2.scene_pb2.Scene.SourceInstance.IntensityProperties, optional + intensity_props_to_complete : \ + ansys.api.speos.scene.v2.scene_pb2.Scene.SourceInstance.IntensityProperties, optional Intensity properties to complete. By default, ``None``. key : str @@ -72,7 +73,8 @@ class Library: ---------- library : ansys.api.speos.intensity.v1.IntensityTemplate.Library Library to complete. - library_props : ansys.api.speos.scene.v2.scene_pb2.Scene.SourceInstance.IntensityProperties.LibraryProperties + library_props : \ + ansys.api.speos.scene.v2.scene_pb2.Scene.SourceInstance.IntensityProperties.LibraryProperties Library properties to complete. default_values : bool Uses default values when True. @@ -177,14 +179,16 @@ def set_exit_geometries( class Gaussian: """Intensity of type: Gaussian. - By default, full width at half maximum following x and y are set at 30 degrees, and total angle at 180 degrees. + By default, full width at half maximum following x and y are set at 30 degrees, and total + angle at 180 degrees. By default, no axis system is chosen, that means normal to surface map. Parameters ---------- gaussian : ansys.api.speos.intensity.v1.IntensityTemplate.Gaussian Gaussian to complete. - gaussian_props : ansys.api.speos.scene.v2.scene_pb2.Scene.SourceInstance.IntensityProperties.GaussianProperties + gaussian_props : \ + ansys.api.speos.scene.v2.scene_pb2.Scene.SourceInstance.IntensityProperties.GaussianProperties Gaussian properties to complete. default_values : bool Uses default values when True. @@ -329,7 +333,7 @@ def set_library(self) -> Intensity.Library: library_props=self._intensity_properties.library_properties, default_values=False, ) - elif type(self._type) != Intensity.Library: + elif not isinstance(self._type, Intensity.Library): # if the _type is not Library then we create a new type. self._type = Intensity.Library( library=self._intensity_template.library, @@ -382,7 +386,7 @@ def set_gaussian(self) -> Intensity.Gaussian: gaussian_props=self._intensity_properties.gaussian_properties, default_values=False, ) - elif type(self._type) != Intensity.Gaussian: + elif not isinstance(self._type, Intensity.Gaussian): # if the _type is not Gaussian then we create a new type. self._type = Intensity.Gaussian( gaussian=self._intensity_template.gaussian, diff --git a/src/ansys/speos/core/kernel/__init__.py b/src/ansys/speos/core/kernel/__init__.py index a838ccaf1..dbb5f6af9 100644 --- a/src/ansys/speos/core/kernel/__init__.py +++ b/src/ansys/speos/core/kernel/__init__.py @@ -25,7 +25,10 @@ from ansys.speos.core.kernel.body import BodyLink, ProtoBody from ansys.speos.core.kernel.client import SpeosClient from ansys.speos.core.kernel.face import FaceLink, ProtoFace -from ansys.speos.core.kernel.intensity_template import IntensityTemplateLink, ProtoIntensityTemplate +from ansys.speos.core.kernel.intensity_template import ( + IntensityTemplateLink, + ProtoIntensityTemplate, +) from ansys.speos.core.kernel.job import JobLink, ProtoJob from ansys.speos.core.kernel.part import PartLink, ProtoPart from ansys.speos.core.kernel.proto_message_utils import ( @@ -33,12 +36,24 @@ protobuf_message_to_str, ) from ansys.speos.core.kernel.scene import ProtoScene, SceneLink -from ansys.speos.core.kernel.sensor_template import ProtoSensorTemplate, SensorTemplateLink +from ansys.speos.core.kernel.sensor_template import ( + ProtoSensorTemplate, + SensorTemplateLink, +) from ansys.speos.core.kernel.simulation_template import ( ProtoSimulationTemplate, SimulationTemplateLink, ) -from ansys.speos.core.kernel.sop_template import ProtoSOPTemplate, SOPTemplateLink -from ansys.speos.core.kernel.source_template import ProtoSourceTemplate, SourceTemplateLink +from ansys.speos.core.kernel.sop_template import ( + ProtoSOPTemplate, + SOPTemplateLink, +) +from ansys.speos.core.kernel.source_template import ( + ProtoSourceTemplate, + SourceTemplateLink, +) from ansys.speos.core.kernel.spectrum import ProtoSpectrum, SpectrumLink -from ansys.speos.core.kernel.vop_template import ProtoVOPTemplate, VOPTemplateLink +from ansys.speos.core.kernel.vop_template import ( + ProtoVOPTemplate, + VOPTemplateLink, +) diff --git a/src/ansys/speos/core/kernel/body.py b/src/ansys/speos/core/kernel/body.py index a08b76ec8..20c21a7c4 100644 --- a/src/ansys/speos/core/kernel/body.py +++ b/src/ansys/speos/core/kernel/body.py @@ -24,7 +24,10 @@ from typing import List -from ansys.api.speos.part.v1 import body_pb2 as messages, body_pb2_grpc as service +from ansys.api.speos.part.v1 import ( + body_pb2 as messages, + body_pb2_grpc as service, +) from ansys.speos.core.kernel.crud import CrudItem, CrudStub from ansys.speos.core.kernel.proto_message_utils import protobuf_message_to_str diff --git a/src/ansys/speos/core/kernel/client.py b/src/ansys/speos/core/kernel/client.py index ae7dd8f7b..c8d1e4ae5 100644 --- a/src/ansys/speos/core/kernel/client.py +++ b/src/ansys/speos/core/kernel/client.py @@ -33,19 +33,34 @@ from ansys.api.speos.part.v1 import body_pb2, face_pb2, part_pb2 from ansys.speos.core.kernel.body import BodyLink, BodyStub from ansys.speos.core.kernel.face import FaceLink, FaceStub -from ansys.speos.core.kernel.intensity_template import IntensityTemplateLink, IntensityTemplateStub +from ansys.speos.core.kernel.intensity_template import ( + IntensityTemplateLink, + IntensityTemplateStub, +) from ansys.speos.core.kernel.job import JobLink, JobStub from ansys.speos.core.kernel.part import PartLink, PartStub from ansys.speos.core.kernel.scene import SceneLink, SceneStub -from ansys.speos.core.kernel.sensor_template import SensorTemplateLink, SensorTemplateStub +from ansys.speos.core.kernel.sensor_template import ( + SensorTemplateLink, + SensorTemplateStub, +) from ansys.speos.core.kernel.simulation_template import ( SimulationTemplateLink, SimulationTemplateStub, ) -from ansys.speos.core.kernel.sop_template import SOPTemplateLink, SOPTemplateStub -from ansys.speos.core.kernel.source_template import SourceTemplateLink, SourceTemplateStub +from ansys.speos.core.kernel.sop_template import ( + SOPTemplateLink, + SOPTemplateStub, +) +from ansys.speos.core.kernel.source_template import ( + SourceTemplateLink, + SourceTemplateStub, +) from ansys.speos.core.kernel.spectrum import SpectrumLink, SpectrumStub -from ansys.speos.core.kernel.vop_template import VOPTemplateLink, VOPTemplateStub +from ansys.speos.core.kernel.vop_template import ( + VOPTemplateLink, + VOPTemplateStub, +) from ansys.speos.core.logger import LOG as logger, PySpeosCustomAdapter DEFAULT_HOST = "localhost" @@ -180,7 +195,7 @@ def healthy(self) -> bool: try: grpc.channel_ready_future(self.channel).result(timeout=60) return True - except: + except BaseException: return False def target(self) -> str: @@ -417,7 +432,8 @@ def get_items( List[ansys.speos.core.kernel.part.PartLink], \ List[ansys.speos.core.kernel.body.BodyLink], \ List[ansys.speos.core.kernel.face.FaceLink]] - List of Link objects corresponding to the keys - Empty if no objects corresponds to the keys. + List of Link objects corresponding to the keys - Empty if no objects corresponds to the + keys. """ if self._closed: raise ConnectionAbortedError() diff --git a/src/ansys/speos/core/kernel/face.py b/src/ansys/speos/core/kernel/face.py index 86482630a..6b91fb682 100644 --- a/src/ansys/speos/core/kernel/face.py +++ b/src/ansys/speos/core/kernel/face.py @@ -24,7 +24,10 @@ from typing import Iterator, List -from ansys.api.speos.part.v1 import face_pb2 as messages, face_pb2_grpc as service +from ansys.api.speos.part.v1 import ( + face_pb2 as messages, + face_pb2_grpc as service, +) from ansys.speos.core.kernel.crud import CrudItem, CrudStub from ansys.speos.core.kernel.proto_message_utils import protobuf_message_to_str @@ -154,7 +157,10 @@ def update(self, ref: FaceLink, data: ProtoFace) -> None: if not ref.stub == self: raise ValueError("FaceLink is not on current database") - CrudStub.update(self, messages.Update_Request(guid=ref.key, face=ProtoFace(name="tmp"))) + CrudStub.update( + self, + messages.Update_Request(guid=ref.key, face=ProtoFace(name="tmp")), + ) chunk_iterator = FaceStub._face_to_chunks(guid=ref.key, message=data, nb_items=128 * 1024) self._actions_stub.Upload(chunk_iterator) diff --git a/src/ansys/speos/core/kernel/intensity_template.py b/src/ansys/speos/core/kernel/intensity_template.py index 8f75f6051..4e2c69f3d 100644 --- a/src/ansys/speos/core/kernel/intensity_template.py +++ b/src/ansys/speos/core/kernel/intensity_template.py @@ -24,12 +24,17 @@ from typing import List -from ansys.api.speos.intensity.v1 import intensity_pb2 as messages, intensity_pb2_grpc as service +from ansys.api.speos.intensity.v1 import ( + intensity_pb2 as messages, + intensity_pb2_grpc as service, +) from ansys.speos.core.kernel.crud import CrudItem, CrudStub from ansys.speos.core.kernel.proto_message_utils import protobuf_message_to_str ProtoIntensityTemplate = messages.IntensityTemplate -"""IntensityTemplate protobuf class : ansys.api.speos.intensity.v1.intensity_pb2.IntensityTemplate""" +"""IntensityTemplate protobuf class. + +ansys.api.speos.intensity.v1.intensity_pb2.IntensityTemplate""" ProtoIntensityTemplate.__str__ = lambda self: protobuf_message_to_str(self) @@ -47,7 +52,9 @@ class IntensityTemplateLink(CrudItem): Examples -------- >>> from ansys.speos.core.speos import Speos - >>> from ansys.speos.core.kernel.intensity_template import ProtoIntensityTemplate + >>> from ansys.speos.core.kernel.intensity_template import ( + ... ProtoIntensityTemplate, + ... ) >>> speos = Speos(host="localhost", port=50098) >>> int_t_db = speos.client.intensity_templates() >>> int_t_message = ProtoIntensityTemplate(name="Cos_3_170") @@ -115,8 +122,8 @@ class IntensityTemplateStub(CrudStub): Examples -------- - The best way to get a IntensityTemplateStub is to retrieve it from SpeosClient via intensity_templates() method. - Like in the following example: + The best way to get a IntensityTemplateStub is to retrieve it from SpeosClient via + intensity_templates() method. Like in the following example: >>> from ansys.speos.core.speos import Speos >>> speos = Speos(host="localhost", port=50098) diff --git a/src/ansys/speos/core/kernel/part.py b/src/ansys/speos/core/kernel/part.py index 52eac95fe..528799ae9 100644 --- a/src/ansys/speos/core/kernel/part.py +++ b/src/ansys/speos/core/kernel/part.py @@ -24,7 +24,10 @@ from typing import List -from ansys.api.speos.part.v1 import part_pb2 as messages, part_pb2_grpc as service +from ansys.api.speos.part.v1 import ( + part_pb2 as messages, + part_pb2_grpc as service, +) from ansys.speos.core.kernel.crud import CrudItem, CrudStub from ansys.speos.core.kernel.proto_message_utils import protobuf_message_to_str diff --git a/src/ansys/speos/core/kernel/scene.py b/src/ansys/speos/core/kernel/scene.py index 3052f2d5e..f2a09607c 100644 --- a/src/ansys/speos/core/kernel/scene.py +++ b/src/ansys/speos/core/kernel/scene.py @@ -25,7 +25,10 @@ from typing import Iterator, List from ansys.api.speos.results.v1.ray_path_pb2 import RayPath -from ansys.api.speos.scene.v2 import scene_pb2 as messages, scene_pb2_grpc as service +from ansys.api.speos.scene.v2 import ( + scene_pb2 as messages, + scene_pb2_grpc as service, +) from ansys.speos.core.kernel.crud import CrudItem, CrudStub from ansys.speos.core.kernel.proto_message_utils import protobuf_message_to_str @@ -111,8 +114,9 @@ def get_source_ray_paths(self, source_path: str, rays_nb: int = 100) -> Iterator Parameters ---------- source_path : str - Path to the source in the Scene : "" for a specific source in the current scene, - or "/" for a specific source in a specific sub scene. + Path to the source in the Scene : "" for a specific source in the current + scene, or "/" for a specific source in a specific sub + scene. rays_nb : int, optional Number of rays generated by the source. By default, ``100``. diff --git a/src/ansys/speos/core/kernel/sensor_template.py b/src/ansys/speos/core/kernel/sensor_template.py index 6cb214c12..7d416074f 100644 --- a/src/ansys/speos/core/kernel/sensor_template.py +++ b/src/ansys/speos/core/kernel/sensor_template.py @@ -24,7 +24,10 @@ from typing import List -from ansys.api.speos.sensor.v1 import sensor_pb2 as messages, sensor_pb2_grpc as service +from ansys.api.speos.sensor.v1 import ( + sensor_pb2 as messages, + sensor_pb2_grpc as service, +) from ansys.speos.core.kernel.crud import CrudItem, CrudStub from ansys.speos.core.kernel.proto_message_utils import protobuf_message_to_str @@ -106,8 +109,8 @@ class SensorTemplateStub(CrudStub): Examples -------- - The best way to get a SensorTemplateStub is to retrieve it from SpeosClient via sensor_templates() method. - Like in the following example: + The best way to get a SensorTemplateStub is to retrieve it from SpeosClient via + sensor_templates() method. Like in the following example: >>> from ansys.speos.core.speos import Speos >>> speos = Speos(host="localhost", port=50098) diff --git a/src/ansys/speos/core/kernel/simulation_template.py b/src/ansys/speos/core/kernel/simulation_template.py index 4273249f3..d4a6ad3d2 100644 --- a/src/ansys/speos/core/kernel/simulation_template.py +++ b/src/ansys/speos/core/kernel/simulation_template.py @@ -32,7 +32,10 @@ from ansys.speos.core.kernel.proto_message_utils import protobuf_message_to_str ProtoSimulationTemplate = messages.SimulationTemplate -"""SimulationTemplate protobuf class : ansys.api.speos.simulation.v1.simulation_template_pb2.SimulationTemplate""" +"""SimulationTemplate protobuf class. + +ansys.api.speos.simulation.v1.simulation_template_pb2.SimulationTemplate +""" ProtoSimulationTemplate.__str__ = lambda self: protobuf_message_to_str(self) @@ -51,7 +54,9 @@ class SimulationTemplateLink(CrudItem): -------- >>> from ansys.speos.core.speos import Speos >>> from ansys.api.speos.simulation.v1 import simulation_template_pb2 - >>> from ansys.speos.core.kernel.simulation_template import ProtoSimulationTemplate + >>> from ansys.speos.core.kernel.simulation_template import ( + ... ProtoSimulationTemplate, + ... ) >>> speos = Speos(host="localhost", port=50098) >>> sim_t_db = speos.client.simulation_templates() >>> sim_t_message = ProtoSimulationTemplate(name="Direct") @@ -109,8 +114,8 @@ class SimulationTemplateStub(CrudStub): Examples -------- - The best way to get a SimulationTemplateStub is to retrieve it from SpeosClient via simulation_templates() method. - Like in the following example: + The best way to get a SimulationTemplateStub is to retrieve it from SpeosClient via + simulation_templates() method. Like in the following example: >>> from ansys.speos.core.speos import Speos >>> speos = Speos(host="localhost", port=50098) @@ -168,7 +173,10 @@ def update(self, ref: SimulationTemplateLink, data: ProtoSimulationTemplate): """ if not ref.stub == self: raise ValueError("SimulationTemplateLink is not on current database") - CrudStub.update(self, messages.Update_Request(guid=ref.key, simulation_template=data)) + CrudStub.update( + self, + messages.Update_Request(guid=ref.key, simulation_template=data), + ) def delete(self, ref: SimulationTemplateLink) -> None: """Remove an existing entry. diff --git a/src/ansys/speos/core/kernel/sop_template.py b/src/ansys/speos/core/kernel/sop_template.py index 14228e6e8..7269dc844 100644 --- a/src/ansys/speos/core/kernel/sop_template.py +++ b/src/ansys/speos/core/kernel/sop_template.py @@ -99,8 +99,8 @@ class SOPTemplateStub(CrudStub): Examples -------- - The best way to get a SOPTemplateStub is to retrieve it from SpeosClient via sop_templates() method. - Like in the following example: + The best way to get a SOPTemplateStub is to retrieve it from SpeosClient via sop_templates() + method. Like in the following example: >>> from ansys.speos.core.speos import Speos >>> speos = Speos(host="localhost", port=50098) diff --git a/src/ansys/speos/core/kernel/source_template.py b/src/ansys/speos/core/kernel/source_template.py index 2c03811aa..1ca0eacad 100644 --- a/src/ansys/speos/core/kernel/source_template.py +++ b/src/ansys/speos/core/kernel/source_template.py @@ -24,7 +24,10 @@ from typing import List -from ansys.api.speos.source.v1 import source_pb2 as messages, source_pb2_grpc as service +from ansys.api.speos.source.v1 import ( + source_pb2 as messages, + source_pb2_grpc as service, +) from ansys.speos.core.kernel.crud import CrudItem, CrudStub from ansys.speos.core.kernel.proto_message_utils import protobuf_message_to_str @@ -100,8 +103,8 @@ class SourceTemplateStub(CrudStub): Examples -------- - The best way to get a SourceTemplateStub is to retrieve it from SpeosClient via source_templates() method. - Like in the following example: + The best way to get a SourceTemplateStub is to retrieve it from SpeosClient via + source_templates() method. Like in the following example: >>> from ansys.speos.core.speos import Speos >>> speos = Speos(host="localhost", port=50098) diff --git a/src/ansys/speos/core/kernel/spectrum.py b/src/ansys/speos/core/kernel/spectrum.py index a91863374..8cb3f519c 100644 --- a/src/ansys/speos/core/kernel/spectrum.py +++ b/src/ansys/speos/core/kernel/spectrum.py @@ -24,7 +24,10 @@ from typing import List -from ansys.api.speos.spectrum.v1 import spectrum_pb2 as messages, spectrum_pb2_grpc as service +from ansys.api.speos.spectrum.v1 import ( + spectrum_pb2 as messages, + spectrum_pb2_grpc as service, +) from ansys.speos.core.kernel.crud import CrudItem, CrudStub from ansys.speos.core.kernel.proto_message_utils import protobuf_message_to_str diff --git a/src/ansys/speos/core/kernel/vop_template.py b/src/ansys/speos/core/kernel/vop_template.py index b7bdaca41..f498642d9 100644 --- a/src/ansys/speos/core/kernel/vop_template.py +++ b/src/ansys/speos/core/kernel/vop_template.py @@ -99,8 +99,8 @@ class VOPTemplateStub(CrudStub): Examples -------- - The best way to get a VOPTemplateStub is to retrieve it from SpeosClient via vop_templates() method. - Like in the following example: + The best way to get a VOPTemplateStub is to retrieve it from SpeosClient via vop_templates() + method. Like in the following example: >>> from ansys.speos.core.speos import Speos >>> speos = Speos(host="localhost", port=50098) diff --git a/src/ansys/speos/core/logger.py b/src/ansys/speos/core/logger.py index 6b5f90c17..99433b4e0 100644 --- a/src/ansys/speos/core/logger.py +++ b/src/ansys/speos/core/logger.py @@ -384,7 +384,13 @@ class Logger: _level = logging.DEBUG _instances = {} - def __init__(self, level=logging.DEBUG, to_file=False, to_stdout=True, filename=FILE_NAME): + def __init__( + self, + level=logging.DEBUG, + to_file=False, + to_stdout=True, + filename=FILE_NAME, + ): """Customize the logger class for PySpeos. Parameters @@ -535,7 +541,10 @@ def add_child_logger(self, suffix: str, level: Optional[str] = None): return self._instances[name] def add_instance_logger( - self, name: str, client_instance: "SpeosClient", level: Optional[int] = None + self, + name: str, + client_instance: "SpeosClient", + level: Optional[int] = None, ) -> PySpeosCustomAdapter: """Add a logger for a speos instance. @@ -592,7 +601,10 @@ def handle_exception(exc_type, exc_value, exc_traceback): if issubclass(exc_type, KeyboardInterrupt): sys.__excepthook__(exc_type, exc_value, exc_traceback) return - logger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)) + logger.critical( + "Uncaught exception", + exc_info=(exc_type, exc_value, exc_traceback), + ) sys.excepthook = handle_exception diff --git a/src/ansys/speos/core/lxp.py b/src/ansys/speos/core/lxp.py index 4b53b40a2..5f9b3f8d1 100644 --- a/src/ansys/speos/core/lxp.py +++ b/src/ansys/speos/core/lxp.py @@ -20,8 +20,9 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -"""The lxp module contains classes and functions to simplify the interaction with ray data (LPF file). +"""The lxp module contains classes and functions to simplify the interaction with ray data. +Ray data is provided as lpf file. LPF files contain a set of simulated rays with all their intersections and properties. """ @@ -56,7 +57,9 @@ class RayPath: """ def __init__( - self, raypath: lpf_file_reader__v2__pb2.RayPath, sensor_contribution: bool = False + self, + raypath: lpf_file_reader__v2__pb2.RayPath, + sensor_contribution: bool = False, ): self._nb_impacts = len(raypath.impacts) self._impacts = [[inter.x, inter.y, inter.z] for inter in raypath.impacts] @@ -71,7 +74,10 @@ def __init__( self._intersection_type = raypath.interaction_statuses if sensor_contribution: self._sensor_contribution = [ - {"sensor_id": sc.sensor_id, "position": [sc.coordinates.x, sc.coordinates.y]} + { + "sensor_id": sc.sensor_id, + "position": [sc.coordinates.x, sc.coordinates.y], + } for sc in raypath.sensor_contributions ] else: @@ -190,8 +196,8 @@ def sensor_contribution(self) -> Union[None, list[dict]]: Returns ------- Union[None, list[dict]] - If no sensor contribution, None will be returned. If there is sensor contribution, a dictionary with \ - the following information is returned:\ + If no sensor contribution, None will be returned. If there is sensor contribution, \ + a dictionary with the following information is returned:\ {“sensor_id”: sc.sensor_id, “position”: [sc.coordinates.x, sc.coordinates.y]} """ @@ -318,7 +324,10 @@ def __parse_traces(self) -> list[RayPath]: return raypaths def __filter_by_last_intersection_types(self, options: list[int], new=True): - """Filter ray paths based on last intersection types and populates filtered_rays property.""" + """Filter ray paths based on last intersection types. + + Populate filtered_rays property. + """ if new: self._filtered_rays = [] for ray in self._rays: @@ -496,7 +505,7 @@ def preview( def wavelength_to_rgb(wavelength: float, gamma: float = 0.8) -> [int, int, int, int]: """Convert a given wavelength of light to an approximate RGB color value. - The wavelength must be given in nanometers in the range from 380 nm to 750 nm (789 THz to 400 THz). + The wavelength must be given in nanometers in the range from 380 nm to 750 nm. Based on the code from http://www.physics.sfasu.edu/astro/color/spectra.html Parameters diff --git a/src/ansys/speos/core/opt_prop.py b/src/ansys/speos/core/opt_prop.py index add1eee92..da3dd3e8a 100644 --- a/src/ansys/speos/core/opt_prop.py +++ b/src/ansys/speos/core/opt_prop.py @@ -38,7 +38,8 @@ class OptProp: """Speos feature: optical property. - By default, a mirror 100% is chosen as surface optical property, without any volume optical property. + By default, a mirror 100% is chosen as surface optical property, + without any volume optical property. By default, the optical property is applied to no geometry. Parameters @@ -166,7 +167,10 @@ def set_volume_opaque(self) -> OptProp: return self def set_volume_optic( - self, index: float = 1.5, absorption: float = 0, constringence: Optional[float] = None + self, + index: float = 1.5, + absorption: float = 0, + constringence: Optional[float] = None, ) -> OptProp: """ Transparent colorless material without bulk scattering. @@ -203,7 +207,11 @@ def set_volume_optic( return self # Deactivated due to a bug on SpeosRPC server side - # def set_volume_nonhomogeneous(self, path: str, axis_system: Optional[List[float]] = None) -> OptProp: + # def set_volume_nonhomogeneous( + # self, + # path: str, + # axis_system: Optional[List[float]] = None + # ) -> OptProp: # """ # Material with non-homogeneous refractive index. # @@ -224,8 +232,11 @@ def set_volume_optic( # if not axis_system: # axis_system = [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1] # if self._vop_template is None: - # self._vop_template = VOPTemplate(name=self._name + ".VOP", description=self._sop_template.description, - # metadata=self._sop_template.metadata) + # self._vop_template = VOPTemplate( + # name=self._name + ".VOP", + # description=self._sop_template.description, + # metadata=self._sop_template.metadata + # ) # self._vop_template.non_homogeneous.gradedmaterial_file_uri = path # self._material_instance.non_homogeneous_properties.axis_system[:] = axis_system # return self @@ -267,7 +278,7 @@ def set_geometries(self, geometries: Optional[List[GeoRef]] = None) -> OptProp: ansys.speos.core.opt_prop.OptProp Optical property. """ - if geometries == None: + if geometries is None: self._material_instance.ClearField("geometries") else: self._material_instance.geometries.geo_paths[:] = [ @@ -282,7 +293,8 @@ def _to_dict(self) -> dict: if self._project.scene_link and self._unique_id is not None: scene_data = self._project.scene_link.get() mat_inst = next( - (x for x in scene_data.materials if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.materials if x.metadata["UniqueId"] == self._unique_id), + None, ) if mat_inst is not None: out_dict = proto_message_utils._replace_guids( @@ -290,11 +302,13 @@ def _to_dict(self) -> dict: ) else: out_dict = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._material_instance + speos_client=self._project.client, + message=self._material_instance, ) else: out_dict = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._material_instance + speos_client=self._project.client, + message=self._material_instance, ) if "vop" not in out_dict.keys(): @@ -302,11 +316,13 @@ def _to_dict(self) -> dict: if self.vop_template_link is None: if self._vop_template is not None: out_dict["vop"] = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._vop_template + speos_client=self._project.client, + message=self._vop_template, ) else: out_dict["vop"] = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self.vop_template_link.get() + speos_client=self._project.client, + message=self.vop_template_link.get(), ) if "sops" not in out_dict.keys(): @@ -315,13 +331,15 @@ def _to_dict(self) -> dict: if self._sop_template is not None: out_dict["sops"] = [ proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._sop_template + speos_client=self._project.client, + message=self._sop_template, ) ] else: out_dict["sops"] = [ proto_message_utils._replace_guids( - speos_client=self._project.client, message=self.sop_template_link.get() + speos_client=self._project.client, + message=self.sop_template_link.get(), ) ] @@ -345,7 +363,10 @@ def get(self, key: str = "") -> str | dict: info = proto_message_utils._value_finder_key_startswith(dict_var=self._to_dict(), key=key) content = list(info) if len(content) != 0: - content.sort(key=lambda x: SequenceMatcher(None, x[0], key).ratio(), reverse=True) + content.sort( + key=lambda x: SequenceMatcher(None, x[0], key).ratio(), + reverse=True, + ) return content[0][1] info = proto_message_utils._flatten_dict(dict_var=self._to_dict()) print("Used key: {} not found in key list: {}.".format(key, info.keys())) @@ -357,7 +378,8 @@ def __str__(self): if self._project.scene_link and self._unique_id is not None: scene_data = self._project.scene_link.get() mat_inst = next( - (x for x in scene_data.materials if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.materials if x.metadata["UniqueId"] == self._unique_id), + None, ) if mat_inst is None: out_str += "local: " @@ -375,7 +397,8 @@ def commit(self) -> OptProp: ansys.speos.core.opt_prop.OptProp Optical Property feature. """ - # The _unique_id will help to find correct item in the scene.materials (the list of MaterialInstance) + # The _unique_id will help to find correct item in the scene.materials: + # the list of MaterialInstance if self._unique_id is None: self._unique_id = str(uuid.uuid4()) self._material_instance.metadata["UniqueId"] = self._unique_id @@ -412,7 +435,8 @@ def commit(self) -> OptProp: # Look if an element corresponds to the _unique_id mat_inst = next( - (x for x in scene_data.materials if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.materials if x.metadata["UniqueId"] == self._unique_id), + None, ) if mat_inst is not None: if mat_inst != self._material_instance: @@ -450,7 +474,8 @@ def reset(self) -> OptProp: scene_data = self._project.scene_link.get() # retrieve scene data # Look if an element corresponds to the _unique_id mat_inst = next( - (x for x in scene_data.materials if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.materials if x.metadata["UniqueId"] == self._unique_id), + None, ) if mat_inst is not None: self._material_instance = mat_inst @@ -485,7 +510,8 @@ def delete(self) -> OptProp: # Remove the material instance from the scene scene_data = self._project.scene_link.get() # retrieve scene data mat_inst = next( - (x for x in scene_data.materials if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.materials if x.metadata["UniqueId"] == self._unique_id), + None, ) if mat_inst is not None: scene_data.materials.remove(mat_inst) diff --git a/src/ansys/speos/core/part.py b/src/ansys/speos/core/part.py index b8f389b9e..eabe4ab9c 100644 --- a/src/ansys/speos/core/part.py +++ b/src/ansys/speos/core/part.py @@ -101,7 +101,10 @@ def __init__( self._geom_features = [] def create_body( - self, name: str, description: str = "", metadata: Optional[Mapping[str, str]] = None + self, + name: str, + description: str = "", + metadata: Optional[Mapping[str, str]] = None, ) -> body.Body: """Create a body in this element. @@ -195,7 +198,8 @@ def _to_dict(self) -> dict: ) else: out_dict = proto_message_utils._replace_guids( - speos_client=self._speos_client, message=self._part_instance + speos_client=self._speos_client, + message=self._part_instance, ) else: out_dict = proto_message_utils._replace_guids( @@ -210,7 +214,8 @@ def _to_dict(self) -> dict: ) else: out_dict["part"] = proto_message_utils._replace_guids( - speos_client=self._speos_client, message=self.part_link.get() + speos_client=self._speos_client, + message=self.part_link.get(), ) return out_dict @@ -245,7 +250,8 @@ def commit(self) -> Part.SubPart: ansys.speos.core.part.Part.SubPart SubPart feature. """ - # The _unique_id will help to find correct item in the scene.materials (the list of MaterialInstance) + # The _unique_id will help to find correct item in the scene.materials: + # the list of MaterialInstance if self._unique_id is None: self._unique_id = str(uuid.uuid4()) self._part_instance.description = "UniqueId_" + self._unique_id @@ -361,7 +367,10 @@ def delete(self) -> Part.SubPart: return self def find( - self, name: str, name_regex: bool = False, feature_type: Optional[type] = None + self, + name: str, + name_regex: bool = False, + feature_type: Optional[type] = None, ) -> List[Union[body.Body, face.Face, Part.SubPart]]: """Find feature(s). @@ -375,13 +384,14 @@ def find( Allows to use regex for name parameter. By default, ``False``, means that regex is not used for name parameter. feature_type : type - Type of the wanted feature (example: ansys.speos.core.body.Body, ansys.speos.core.face.Face, - ansys.speos.core.part.Part.SubPart). + Type of the wanted feature (example: ansys.speos.core.body.Body,\ + ansys.speos.core.face.Face, ansys.speos.core.part.Part.SubPart). By default, ``None``, means that all features will be considered. Returns ------- - List[Union[ansys.speos.core.body.Body, ansys.speos.core.face.Face, ansys.speos.core.part.Part.SubPart]] + List[Union[ansys.speos.core.body.Body, ansys.speos.core.face.Face,\ + ansys.speos.core.part.Part.SubPart]] Found features. """ orig_name = name @@ -398,7 +408,7 @@ def find( [ x for x in self._geom_features - if p.match(x._name) and type(x) == feature_type + if p.match(x._name) and isinstance(x, feature_type) ] ) else: @@ -406,7 +416,7 @@ def find( [ x for x in self._geom_features - if x._name == name and type(x) == feature_type + if x._name == name and isinstance(x, feature_type) ] ) else: @@ -419,7 +429,9 @@ def find( if found_features and idx != -1: tmp = [ f.find( - name=orig_name[idx + 1 :], name_regex=name_regex, feature_type=feature_type + name=orig_name[idx + 1 :], + name_regex=name_regex, + feature_type=feature_type, ) for f in found_features ] @@ -450,7 +462,10 @@ def __init__( self._part = ProtoPart(name=name, description=description, metadata=metadata) def create_body( - self, name: str, description: str = "", metadata: Optional[Mapping[str, str]] = None + self, + name: str, + description: str = "", + metadata: Optional[Mapping[str, str]] = None, ) -> body.Body: """Create a body in this element. @@ -500,7 +515,10 @@ def create_sub_part(self, name: str, description: str = "") -> Part.SubPart: SubPart feature. """ sub_part_feat = Part.SubPart( - speos_client=self._project.client, name=name, description=description, parent_part=self + speos_client=self._project.client, + name=name, + description=description, + parent_part=self, ) self._geom_features.append(sub_part_feat) return sub_part_feat @@ -595,7 +613,10 @@ def delete(self) -> Part: return self def find( - self, name: str, name_regex: bool = False, feature_type: Optional[type] = None + self, + name: str, + name_regex: bool = False, + feature_type: Optional[type] = None, ) -> List[Union[body.Body, face.Face, Part.SubPart]]: """Find feature(s). @@ -609,13 +630,14 @@ def find( Allows to use regex for name parameter. By default, ``False``, means that regex is not used for name parameter. feature_type : type - Type of the wanted feature (example: ansys.speos.core.body.Body, ansys.speos.core.face.Face, - ansys.speos.core.part.Part.SubPart). + Type of the wanted feature (example: ansys.speos.core.body.Body,\ + ansys.speos.core.face.Face, ansys.speos.core.part.Part.SubPart). By default, ``None``, means that all features will be considered. Returns ------- - List[Union[ansys.speos.core.body.Body, ansys.speos.core.face.Face, ansys.speos.core.part.Part.SubPart]] + List[Union[ansys.speos.core.body.Body, ansys.speos.core.face.Face,\ + ansys.speos.core.part.Part.SubPart]] Found features. """ orig_name = name @@ -628,11 +650,19 @@ def find( if name_regex: p = re.compile(name) found_features.extend( - [x for x in self._geom_features if p.match(x._name) and type(x) == feature_type] + [ + x + for x in self._geom_features + if p.match(x._name) and isinstance(x, feature_type) + ] ) else: found_features.extend( - [x for x in self._geom_features if x._name == name and type(x) == feature_type] + [ + x + for x in self._geom_features + if x._name == name and isinstance(x, feature_type) + ] ) else: if name_regex: @@ -643,7 +673,11 @@ def find( if found_features and idx != -1: tmp = [ - f.find(name=orig_name[idx + 1 :], name_regex=name_regex, feature_type=feature_type) + f.find( + name=orig_name[idx + 1 :], + name_regex=name_regex, + feature_type=feature_type, + ) for f in found_features ] diff --git a/src/ansys/speos/core/project.py b/src/ansys/speos/core/project.py index 650fdca5a..ae665de5f 100644 --- a/src/ansys/speos/core/project.py +++ b/src/ansys/speos/core/project.py @@ -41,15 +41,28 @@ import ansys.speos.core.opt_prop as opt_prop import ansys.speos.core.part as part import ansys.speos.core.proto_message_utils as proto_message_utils -from ansys.speos.core.sensor import SensorCamera, SensorIrradiance, SensorRadiance -from ansys.speos.core.simulation import SimulationDirect, SimulationInteractive, SimulationInverse -from ansys.speos.core.source import SourceLuminaire, SourceRayFile, SourceSurface +from ansys.speos.core.sensor import ( + SensorCamera, + SensorIrradiance, + SensorRadiance, +) +from ansys.speos.core.simulation import ( + SimulationDirect, + SimulationInteractive, + SimulationInverse, +) +from ansys.speos.core.source import ( + SourceLuminaire, + SourceRayFile, + SourceSurface, +) from ansys.speos.core.speos import Speos class Project: - """A project describes all Speos features (optical properties, sources, sensors, simulations) that user can fill in. + """A project describes all Speos features. + This includes optical properties, sources, sensors, simulations that user can fill in. Project provides functions to create new feature, find a feature. It can be created from empty or loaded from a specific file. @@ -78,11 +91,17 @@ def __init__(self, speos: Speos, path: str = ""): self._fill_features() # def list(self): - # """Return all feature key as a tree, can be used to list all features- Not yet implemented""" + # """Return all feature key as a tree. + # + # Can be used to list all features- Not yet implemented. + # """ # pass def create_optical_property( - self, name: str, description: str = "", metadata: Optional[Mapping[str, str]] = None + self, + name: str, + description: str = "", + metadata: Optional[Mapping[str, str]] = None, ) -> opt_prop.OptProp: """Create a new Optical Property feature. @@ -145,7 +164,8 @@ def create_source( Returns ------- - Union[ansys.speos.core.source.SourceSurface, ansys.speos.core.source.SourceRayFile, ansys.speos.core.source.SourceLuminaire] + Union[ansys.speos.core.source.SourceSurface,ansys.speos.core.source.SourceRayFile,\ + ansys.speos.core.source.SourceLuminaire] Source class instance. """ if metadata is None: @@ -160,15 +180,24 @@ def create_source( feature = None if feature_type == SourceSurface: feature = SourceSurface( - project=self, name=name, description=description, metadata=metadata + project=self, + name=name, + description=description, + metadata=metadata, ) elif feature_type == SourceRayFile: feature = SourceRayFile( - project=self, name=name, description=description, metadata=metadata + project=self, + name=name, + description=description, + metadata=metadata, ) elif feature_type == SourceLuminaire: feature = SourceLuminaire( - project=self, name=name, description=description, metadata=metadata + project=self, + name=name, + description=description, + metadata=metadata, ) else: msg = "Requested feature {} does not exist in supported list {}".format( @@ -198,14 +227,17 @@ def create_simulation( Simulation type to be created. By default, ``ansys.speos.core.simulation.SimulationDirect``. Allowed types: Union[ansys.speos.core.simulation.SimulationDirect, \ - ansys.speos.core.simulation.SimulationInteractive, ansys.speos.core.simulation.SimulationInverse]. + ansys.speos.core.simulation.SimulationInteractive, \ + ansys.speos.core.simulation.SimulationInverse]. metadata : Optional[Mapping[str, str]] Metadata of the feature. By default, ``{}``. Returns ------- - Union[ansys.speos.core.simulation.SimulationDirect, ansys.speos.core.simulation.SimulationInteractive, ansys.speos.core.simulation.SimulationInverse] + Union[ansys.speos.core.simulation.SimulationDirect,\ + ansys.speos.core.simulation.SimulationInteractive,\ + ansys.speos.core.simulation.SimulationInverse] Simulation class instance """ if metadata is None: @@ -220,15 +252,24 @@ def create_simulation( feature = None if feature_type == SimulationDirect: feature = SimulationDirect( - project=self, name=name, description=description, metadata=metadata + project=self, + name=name, + description=description, + metadata=metadata, ) elif feature_type == SimulationInverse: feature = SimulationInverse( - project=self, name=name, description=description, metadata=metadata + project=self, + name=name, + description=description, + metadata=metadata, ) elif feature_type == SimulationInteractive: feature = SimulationInteractive( - project=self, name=name, description=description, metadata=metadata + project=self, + name=name, + description=description, + metadata=metadata, ) else: msg = "Requested feature {} does not exist in supported list {}".format( @@ -262,7 +303,8 @@ def create_sensor( feature_type: type Sensor type to be created. By default, ``ansys.speos.core.sensor.SensorIrradiance``. - Allowed types: Union[ansys.speos.core.sensor.SensorCamera, ansys.speos.core.sensor.SensorRadiance, \ + Allowed types: Union[ansys.speos.core.sensor.SensorCamera,\ + ansys.speos.core.sensor.SensorRadiance, \ ansys.speos.core.sensor.SensorIrradiance]. metadata : Optional[Mapping[str, str]] Metadata of the feature. @@ -270,7 +312,8 @@ def create_sensor( Returns ------- - Union[ansys.speos.core.sensor.SensorCamera, ansys.speos.core.sensor.SensorRadiance, ansys.speos.core.sensor.SensorIrradiance] + Union[ansys.speos.core.sensor.SensorCamera,\ + ansys.speos.core.sensor.SensorRadiance, ansys.speos.core.sensor.SensorIrradiance] Sensor class instance. """ if metadata is None: @@ -285,15 +328,24 @@ def create_sensor( feature = None if feature_type == SensorIrradiance: feature = SensorIrradiance( - project=self, name=name, description=description, metadata=metadata + project=self, + name=name, + description=description, + metadata=metadata, ) elif feature_type == SensorRadiance: feature = SensorRadiance( - project=self, name=name, description=description, metadata=metadata + project=self, + name=name, + description=description, + metadata=metadata, ) elif feature_type == SensorCamera: feature = SensorCamera( - project=self, name=name, description=description, metadata=metadata + project=self, + name=name, + description=description, + metadata=metadata, ) else: msg = "Requested feature {} does not exist in supported list {}".format( @@ -304,9 +356,13 @@ def create_sensor( return feature def create_root_part( - self, description: str = "", metadata: Optional[Mapping[str, str]] = None + self, + description: str = "", + metadata: Optional[Mapping[str, str]] = None, ) -> part.Part: - """Create the project root part feature. If a root part is already created in the project, it is returned. + """Create the project root part feature. + + If a root part is already created in the project, it is returned. Parameters ---------- @@ -335,7 +391,10 @@ def create_root_part( return feature def find( - self, name: str, name_regex: bool = False, feature_type: Optional[type] = None + self, + name: str, + name_regex: bool = False, + feature_type: Optional[type] = None, ) -> List[ Union[ opt_prop.OptProp, @@ -366,15 +425,18 @@ def find( feature_type : type Type of the wanted features. Mandatory to fill for geometry features. - By default, ``None``, means that all features will be considered (except geometry features). + By default, ``None``, means that all features will be considered + (except geometry features). Returns ------- List[Union[ansys.speos.core.opt_prop.OptProp, ansys.speos.core.source.Surface, \ - ansys.speos.core.source.RayFile, ansys.speos.core.source.Luminaire, ansys.speos.core.sensor.Camera, \ + ansys.speos.core.source.RayFile, ansys.speos.core.source.Luminaire, \ + ansys.speos.core.sensor.Camera, \ ansys.speos.core.sensor.Radiance, ansys.speos.core.sensor.Irradiance, \ ansys.speos.core.simulation.Direct, ansys.speos.core.simulation.Interactive, \ - ansys.speos.core.simulation.Inverse, ansys.speos.core.part.Part, ansys.speos.core.body.Body, \ + ansys.speos.core.simulation.Inverse, ansys.speos.core.part.Part, \ + ansys.speos.core.body.Body, \ ansys.speos.core.face.Face, ansys.speos.core.part.Part.SubPart]] Found features. @@ -385,8 +447,11 @@ def find( >>> # Specify feature type >>> find(name="Camera.1", feature_type=ansys.speos.core.sensor.SensorCamera) >>> # Using regex - >>> find(name="Camera.*", name_regex=True, feature_type=ansys.speos.core.sensor.SensorCamera) - + >>> find( + >>> name="Camera.*", + >>> name_regex=True, + >>> feature_type=ansys.speos.core.sensor.SensorCamera, + >>> ) Here some examples when looking for a geometry feature: (always precise feature_type) @@ -443,8 +508,8 @@ def find( x for x in self._features if ( - type(x) == feature_type - or (type(x._type) == feature_type if hasattr(x, "_type") else False) + isinstance(x, feature_type) + or (isinstance(x._type, feature_type) if hasattr(x, "_type") else False) ) and p.match(x._name) ] @@ -455,8 +520,8 @@ def find( x for x in self._features if ( - type(x) == feature_type - or (type(x._type) == feature_type if hasattr(x, "_type") else False) + isinstance(x, feature_type) + or (isinstance(x._type, feature_type) if hasattr(x, "_type") else False) ) and x._name == name ] @@ -465,7 +530,9 @@ def find( if found_features and idx != -1: tmp = [ f.find( - name=orig_name[idx + 1 :], name_regex=name_regex, feature_type=orig_feature_type + name=orig_name[idx + 1 :], + name_regex=name_regex, + feature_type=orig_feature_type, ) for f in found_features ] @@ -508,7 +575,9 @@ def delete(self) -> Project: def _to_dict(self) -> dict: # Replace all guids by content of objects in the dict output_dict = proto_message_utils._replace_guids( - speos_client=self.client, message=self.scene_link.get(), ignore_simple_key="part_guid" + speos_client=self.client, + message=self.scene_link.get(), + ignore_simple_key="part_guid", ) # For each feature, replace properties by putting them at correct place @@ -517,11 +586,13 @@ def _to_dict(self) -> dict: for inside_dict in v: if k == "simulations": sim_feat = self.find( - name=inside_dict["name"], feature_type=SimulationDirect + name=inside_dict["name"], + feature_type=SimulationDirect, ) if len(sim_feat) == 0: sim_feat = self.find( - name=inside_dict["name"], feature_type=SimulationInverse + name=inside_dict["name"], + feature_type=SimulationInverse, ) if len(sim_feat) == 0: sim_feat = self.find( @@ -572,7 +643,11 @@ def __str__(self): """Return the string representation of the project's scene.""" return proto_message_utils.dict_to_str(dict=self._to_dict()) - def _fill_bodies(self, body_guids: List[str], feat_host: Union[part.Part, part.Part.SubPart]): + def _fill_bodies( + self, + body_guids: List[str], + feat_host: Union[part.Part, part.Part.SubPart], + ): """Fill part of sub part features from a list of body guids.""" for b_link in self.client.get_items(keys=body_guids, item_type=BodyLink): b_data = b_link.get() @@ -595,7 +670,7 @@ def _add_unique_ids(self): root_part = root_part_link.get() update_rp = False for sub_part in root_part.parts: - if sub_part.description.startswith("UniqueId_") == False: + if sub_part.description.startswith("UniqueId_") is False: sub_part.description = "UniqueId_" + str(uuid.uuid4()) update_rp = True if update_rp: @@ -638,7 +713,8 @@ def _fill_features(self): root_part_feat = root_part_feats[0] root_part_feat.part_link = root_part_link - root_part_feat._part = root_part_data # instead of root_part_feat.reset() - this avoid a useless read in server + root_part_feat._part = root_part_data + # instead of root_part_feat.reset() - this avoid a useless read in server for sp in root_part_data.parts: sp_feat = root_part_feat.create_sub_part(name=sp.name, description=sp.description) @@ -661,30 +737,48 @@ def _fill_features(self): for src_inst in scene_data.sources: if src_inst.HasField("rayfile_properties"): src_feat = SourceRayFile( - project=self, name=src_inst.name, source_instance=src_inst, default_values=False + project=self, + name=src_inst.name, + source_instance=src_inst, + default_values=False, ) elif src_inst.HasField("luminaire_properties"): src_feat = SourceLuminaire( - project=self, name=src_inst.name, source_instance=src_inst, default_values=False + project=self, + name=src_inst.name, + source_instance=src_inst, + default_values=False, ) elif src_inst.HasField("surface_properties"): src_feat = SourceSurface( - project=self, name=src_inst.name, source_instance=src_inst, default_values=False + project=self, + name=src_inst.name, + source_instance=src_inst, + default_values=False, ) self._features.append(src_feat) for ssr_inst in scene_data.sensors: if ssr_inst.HasField("irradiance_properties"): ssr_feat = SensorIrradiance( - project=self, name=ssr_inst.name, sensor_instance=ssr_inst, default_values=False + project=self, + name=ssr_inst.name, + sensor_instance=ssr_inst, + default_values=False, ) elif ssr_inst.HasField("radiance_properties"): ssr_feat = SensorRadiance( - project=self, name=ssr_inst.name, sensor_instance=ssr_inst, default_values=False + project=self, + name=ssr_inst.name, + sensor_instance=ssr_inst, + default_values=False, ) elif ssr_inst.HasField("camera_properties"): ssr_feat = SensorCamera( - project=self, name=ssr_inst.name, sensor_instance=ssr_inst, default_values=False + project=self, + name=ssr_inst.name, + sensor_instance=ssr_inst, + default_values=False, ) self._features.append(ssr_feat) @@ -714,7 +808,9 @@ def _fill_features(self): self._features.append(sim_feat) def __extract_part_mesh_info( - self, part_data: ProtoPart, part_coordinate_info: RepeatedScalarFieldContainer = None + self, + part_data: ProtoPart, + part_coordinate_info: RepeatedScalarFieldContainer = None, ) -> pv.PolyData: """Extract mesh data info from a part. @@ -753,7 +849,20 @@ def local2absolute(local_vertice: np.ndarray, coordinates) -> np.ndarray: global_z = np.array(coordinates[9:]) * local_vertice[2] return global_origin + global_x + global_y + global_z - part_coordinate = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + part_coordinate = [ + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 1.0, + ] if part_coordinate_info is not None: part_coordinate = part_coordinate_info part_mesh_info = None @@ -801,7 +910,8 @@ def _create_preview(self, viz_args=None) -> pv.Plotter: for part_idx, part_item in enumerate(root_part_data.parts): part_item_data = self.client[part_item.part_guid].get() poly_data = self.__extract_part_mesh_info( - part_data=part_item_data, part_coordinate_info=part_item.axis_system + part_data=part_item_data, + part_coordinate_info=part_item.axis_system, ) if poly_data is not None: _preview_mesh = _preview_mesh.append_polydata(poly_data) diff --git a/src/ansys/speos/core/proto_message_utils.py b/src/ansys/speos/core/proto_message_utils.py index ed8e47329..f4f8d5537 100644 --- a/src/ansys/speos/core/proto_message_utils.py +++ b/src/ansys/speos/core/proto_message_utils.py @@ -53,7 +53,9 @@ def _replace_guids( json_dict = protobuf_message_to_dict(message=message) # Add for each element xxx_guid a key xxx with value the corresponding data from database _replace_guid_elt( - speos_client=speos_client, json_dict=json_dict, ignore_simple_key=ignore_simple_key + speos_client=speos_client, + json_dict=json_dict, + ignore_simple_key=ignore_simple_key, ) return json_dict @@ -63,14 +65,17 @@ def _replace_guid_elt( ) -> None: new_items = [] for k, v in json_dict.items(): - # If we are in the case of key "xxx_guid", with a guid non empty and that the key is not to ignore + # If we are in the case of key "xxx_guid", with a guid non empty + # and that the key is not to ignore if k.endswith("_guid") and v != "" and k != ignore_simple_key: # Retrieve the item from db and transform it to dictionary new_v = protobuf_message_to_dict(message=speos_client[v].get()) # This item can potentially have some "xxx_guid" fields to replace _replace_guid_elt( - speos_client=speos_client, json_dict=new_v, ignore_simple_key=ignore_simple_key + speos_client=speos_client, + json_dict=new_v, + ignore_simple_key=ignore_simple_key, ) # Add the new value under "xxx" key new_items.append((k[: k.find("_guid")], new_v)) @@ -85,22 +90,28 @@ def _replace_guid_elt( # This item can potentially have some "xxx_guid" fields to replace _replace_guid_elt( - speos_client=speos_client, json_dict=new_v, ignore_simple_key=ignore_simple_key + speos_client=speos_client, + json_dict=new_v, + ignore_simple_key=ignore_simple_key, ) # Add the new value to the "xxxs" list new_value_list.append(new_v) new_items.append((new_key_list, new_value_list)) # Call recursevely if the value is a dict or a list with dict as items values - if type(v) == dict: + if isinstance(v, dict): _replace_guid_elt( - speos_client=speos_client, json_dict=v, ignore_simple_key=ignore_simple_key + speos_client=speos_client, + json_dict=v, + ignore_simple_key=ignore_simple_key, ) - elif type(v) == list: + elif isinstance(v, list): for iv in v: - if type(iv) == dict: + if isinstance(iv, dict): _replace_guid_elt( - speos_client=speos_client, json_dict=iv, ignore_simple_key=ignore_simple_key + speos_client=speos_client, + json_dict=iv, + ignore_simple_key=ignore_simple_key, ) # To avoid modifying a dict when reading it, all changes were stored in new_items list @@ -178,7 +189,10 @@ def _replace_properties(json_dict: dict) -> None: def _finder_by_key(dict_var: dict, key: str, x_path: str = "") -> List[tuple[str, dict]]: - """Find a key in a dictionary (recursively). It will return a list of (x_path, dictionary) of items corresponding to the key.""" + """Find a key in a dictionary (recursively). + + It will return a list of (x_path, dictionary) of items corresponding to the key. + """ out_list = [] # Loop on all dictionary items @@ -204,7 +218,8 @@ def _finder_by_key(dict_var: dict, key: str, x_path: str = "") -> List[tuple[str for item in v: if isinstance(item, dict): x_path_bckp2 = x_path - # In case the dict has field name, use it in x_path like .key[.name='TheName'], it is more meaningful that just [idx] + # In case the dict has field name, use it in x_path like .key[.name='TheName'] + # it is more meaningful that just [idx] if "name" in item.keys(): x_path = x_path + ".name='" + item["name"] + "']" else: # if no field name, then just use .key[idx] diff --git a/src/ansys/speos/core/sensor.py b/src/ansys/speos/core/sensor.py index 948c0f7bf..5fe1fdb59 100644 --- a/src/ansys/speos/core/sensor.py +++ b/src/ansys/speos/core/sensor.py @@ -94,7 +94,8 @@ def __init__( else: self._unique_id = sensor_instance.metadata["UniqueId"] self.sensor_template_link = self._project.client[sensor_instance.sensor_guid] - # reset will fill _sensor_instance and _sensor_template from respectively project (using _unique_id) and sensor_template_link + # reset will fill _sensor_instance and _sensor_template from respectively project + # (using _unique_id) and sensor_template_link self.reset() class WavelengthsRange: @@ -113,7 +114,8 @@ class WavelengthsRange: Notes ----- - **Do not instantiate this class yourself**, use set_wavelengths_range method available in sensor classes. + **Do not instantiate this class yourself**, use set_wavelengths_range method available in + sensor classes. """ def __init__( @@ -171,7 +173,8 @@ def set_sampling(self, value: int = 13) -> BaseSensor.WavelengthsRange: Parameters ---------- value : int - Number of wavelengths to be taken into account between the minimum and maximum wavelengths range. + Number of wavelengths to be taken into account between the minimum and maximum + wavelengths range. By default, ``13``. Returns @@ -198,7 +201,8 @@ class Dimensions: Notes ----- - **Do not instantiate this class yourself**, use set_dimensions method available in sensor classes. + **Do not instantiate this class yourself**, use set_dimensions method available in sensor + classes. """ def __init__( @@ -321,7 +325,8 @@ def set_y_sampling(self, value: int = 100) -> BaseSensor.Dimensions: class Colorimetric: """Type of sensor : Colorimetric. - This kind of sensor will generate color results without any spectral data or layer separation (in lx or W//m2). + This kind of sensor will generate color results without any spectral data or layer + separation in lx or W//m2. By default, it uses a default wavelengths range. Parameters @@ -335,7 +340,8 @@ class Colorimetric: Notes ----- - **Do not instantiate this class yourself**, use set_type_colorimetric method available in sensor classes. + **Do not instantiate this class yourself**, use set_type_colorimetric method available in + sensor classes. """ def __init__( @@ -381,7 +387,8 @@ def set_wavelengths_range(self) -> BaseSensor.WavelengthsRange: class Spectral: """Type of sensor : Spectral. - This kind of sensor will generate color results and spectral data separated by wavelength (in lx or W/m2). + This kind of sensor will generate color results and spectral data separated by wavelength + in lx or W/m2. By default, it uses a default wavelengths range. Parameters @@ -395,7 +402,8 @@ class Spectral: Notes ----- - **Do not instantiate this class yourself**, use set_type_spectral method available in sensor classes. + **Do not instantiate this class yourself**, use set_type_spectral method available in + sensor classes. """ def __init__( @@ -463,7 +471,8 @@ class LayerTypeFace: Parameters ---------- - layer_type_face : ansys.api.speos.scene.v2.scene_pb2.Scene.SensorInstance.LayerTypeFace + layer_type_face : \ + ansys.api.speos.scene.v2.scene_pb2.Scene.SensorInstance.LayerTypeFace LayerTypeFace protobuf object to modify. default_values : bool Uses default values when True. @@ -472,7 +481,8 @@ class LayerTypeFace: Notes ----- - **Do not instantiate this class yourself**, use set_layer_type_face method available in sensor classes. + **Do not instantiate this class yourself**, use set_layer_type_face method available in + sensor classes. """ def __init__( @@ -491,7 +501,9 @@ def __init__( # Default values self.set_sca_filtering_mode_last_impact() - def set_sca_filtering_mode_intersected_one_time(self) -> BaseSensor.LayerTypeFace: + def set_sca_filtering_mode_intersected_one_time( + self, + ) -> BaseSensor.LayerTypeFace: """Set the filtering mode as intersected one time. Returns @@ -504,7 +516,9 @@ def set_sca_filtering_mode_intersected_one_time(self) -> BaseSensor.LayerTypeFac ) return self - def set_sca_filtering_mode_last_impact(self) -> BaseSensor.LayerTypeFace: + def set_sca_filtering_mode_last_impact( + self, + ) -> BaseSensor.LayerTypeFace: """Set the filtering mode as last impact. Returns @@ -551,7 +565,8 @@ class LayerTypeSequence: Parameters ---------- - layer_type_sequence : ansys.api.speos.scene.v2.scene_pb2.Scene.SensorInstance.LayerTypeSequence + layer_type_sequence : \ + ansys.api.speos.scene.v2.scene_pb2.Scene.SensorInstance.LayerTypeSequence LayerTypeSequence protobuf object to modify. default_values : bool Uses default values when True. @@ -560,7 +575,8 @@ class LayerTypeSequence: Notes ----- - **Do not instantiate this class yourself**, use set_layer_type_sequence method available in sensor classes. + **Do not instantiate this class yourself**, use set_layer_type_sequence method available in + sensor classes. """ def __init__( @@ -596,7 +612,9 @@ def set_maximum_nb_of_sequence(self, value: int = 10) -> BaseSensor.LayerTypeSeq self._layer_type_sequence.maximum_nb_of_sequence = value return self - def set_define_sequence_per_geometries(self) -> BaseSensor.LayerTypeSequence: + def set_define_sequence_per_geometries( + self, + ) -> BaseSensor.LayerTypeSequence: """Define sequence per geometries. Returns @@ -630,7 +648,8 @@ class LayerTypeIncidenceAngle: Parameters ---------- - layer_type_incidence_angle : ansys.api.speos.scene.v2.scene_pb2.Scene.SensorInstance.LayerTypeIncidenceAngle + layer_type_incidence_angle : \ + ansys.api.speos.scene.v2.scene_pb2.Scene.SensorInstance.LayerTypeIncidenceAngle LayerTypeIncidenceAngle protobuf object to modify. default_values : bool Uses default values when True. @@ -639,7 +658,8 @@ class LayerTypeIncidenceAngle: Notes ----- - **Do not instantiate this class yourself**, use set_layer_type_incidence_angle method available in sensor classes. + **Do not instantiate this class yourself**, use set_layer_type_incidence_angle method + available in sensor classes. """ def __init__( @@ -682,7 +702,8 @@ def _to_dict(self) -> dict: if self._project.scene_link and self._unique_id is not None: scene_data = self._project.scene_link.get() ssr_inst = next( - (x for x in scene_data.sensors if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.sensors if x.metadata["UniqueId"] == self._unique_id), + None, ) if ssr_inst is not None: out_dict = proto_message_utils._replace_guids( @@ -690,7 +711,8 @@ def _to_dict(self) -> dict: ) else: out_dict = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._sensor_instance + speos_client=self._project.client, + message=self._sensor_instance, ) else: out_dict = proto_message_utils._replace_guids( @@ -701,11 +723,13 @@ def _to_dict(self) -> dict: # SensorTemplate if self.sensor_template_link is None: out_dict["sensor"] = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._sensor_template + speos_client=self._project.client, + message=self._sensor_template, ) else: out_dict["sensor"] = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self.sensor_template_link.get() + speos_client=self._project.client, + message=self.sensor_template_link.get(), ) proto_message_utils._replace_properties(json_dict=out_dict) @@ -728,7 +752,10 @@ def get(self, key: str = "") -> str | dict: info = proto_message_utils._value_finder_key_startswith(dict_var=self._to_dict(), key=key) content = list(info) if len(content) != 0: - content.sort(key=lambda x: SequenceMatcher(None, x[0], key).ratio(), reverse=True) + content.sort( + key=lambda x: SequenceMatcher(None, x[0], key).ratio(), + reverse=True, + ) return content[0][1] info = proto_message_utils._flatten_dict(dict_var=self._to_dict()) print("Used key: {} not found in key list: {}.".format(key, info.keys())) @@ -740,7 +767,8 @@ def __str__(self) -> str: if self._project.scene_link and self._unique_id is not None: scene_data = self._project.scene_link.get() ssr_inst = next( - (x for x in scene_data.sensors if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.sensors if x.metadata["UniqueId"] == self._unique_id), + None, ) if ssr_inst is None: out_str += "local: " @@ -759,7 +787,8 @@ def commit(self) -> BaseSensor: ansys.speos.core.sensor.BaseSensor Sensor feature. """ - # The _unique_id will help to find the correct item in the scene.sensors (the list of SensorInstance) + # The _unique_id will help to find the correct item in the scene.sensors: + # the list of SensorInstance if self._unique_id is None: self._unique_id = str(uuid.uuid4()) self._sensor_instance.metadata["UniqueId"] = self._unique_id @@ -782,7 +811,8 @@ def commit(self) -> BaseSensor: # Look if an element corresponds to the _unique_id ssr_inst = next( - (x for x in scene_data.sensors if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.sensors if x.metadata["UniqueId"] == self._unique_id), + None, ) if ssr_inst is not None: if ssr_inst != self._sensor_instance: @@ -816,7 +846,8 @@ def reset(self) -> BaseSensor: scene_data = self._project.scene_link.get() # retrieve scene data # Look if an element corresponds to the _unique_id ssr_inst = next( - (x for x in scene_data.sensors if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.sensors if x.metadata["UniqueId"] == self._unique_id), + None, ) if ssr_inst is not None: self._sensor_instance = ssr_inst @@ -843,7 +874,8 @@ def delete(self) -> BaseSensor: # Remove the sensor from the scene scene_data = self._project.scene_link.get() # retrieve scene data ssr_inst = next( - (x for x in scene_data.sensors if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.sensors if x.metadata["UniqueId"] == self._unique_id), + None, ) if ssr_inst is not None: scene_data.sensors.remove(ssr_inst) @@ -859,7 +891,8 @@ class SensorCamera(BaseSensor): """Sensor feature: Camera. By default, regarding inherent characteristics, a camera with mode photometric is chosen. - By default, regarding properties, an axis system is selected to position the sensor, and no layer separation is chosen. + By default, regarding properties, an axis system is selected to position the sensor, + and no layer separation is chosen. Parameters ---------- @@ -884,7 +917,8 @@ class SensorCamera(BaseSensor): class Photometric: """Mode of camera sensor : Photometric. - This allows to set every Camera Sensor parameters, including the photometric definition parameters. + This allows to set every Camera Sensor parameters, including the photometric definition + parameters. By default, a camera with mode color is chosen (vs monochromatic mode). Parameters @@ -898,7 +932,8 @@ class Photometric: Notes ----- - **Do not instantiate this class yourself**, use set_type_photometric method available in sensor classes. + **Do not instantiate this class yourself**, use set_type_photometric method available in + sensor classes. """ @@ -919,19 +954,22 @@ class Color: Notes ----- - **Do not instantiate this class yourself**, use set_mode_color method available in photometric class. + **Do not instantiate this class yourself**, use set_mode_color method available in + photometric class. """ class BalanceModeUserWhite: """BalanceMode : UserWhite. - In addition to the basic treatment, it allows to apply specific coefficients to the red, green, blue images. + In addition to the basic treatment, it allows to apply specific coefficients to the + red, green, blue images. By default, coefficients of 1 are chosen for red, green and blue images. Parameters ---------- - balance_mode_user_white : ansys.api.speos.sensor.v1.camera_sensor_pb2.SensorCameraBalanceModeUserwhite + balance_mode_user_white : ansys.api.speos.sensor.v1.camera_sensor_pb2. + SensorCameraBalanceModeUserwhite SensorCameraBalanceModeUserwhite protobuf object to modify. default_values : bool Uses default values when True. @@ -940,7 +978,8 @@ class BalanceModeUserWhite: Notes ----- - **Do not instantiate this class yourself**, use set_balance_mode_user_white method available in color class. + **Do not instantiate this class yourself**, use set_balance_mode_user_white method + available in color class. """ @@ -1020,19 +1059,22 @@ class BalanceModeDisplayPrimaries: """BalanceMode : DisplayPrimaries. Spectral results are converted in a three-channel result. - Then a post-treatment is realized to take the distortion induced by the display devices into account. + Then a post-treatment is realized to take the distortion induced by the display + devices into account. With this method, displayed results are similar to what the camera really gets. Parameters ---------- - balance_mode_display : ansys.api.speos.sensor.v1.camera_sensor_pb2.SensorCameraBalanceModeDisplay + balance_mode_display : ansys.api.speos.sensor.v1.camera_sensor_pb2. + SensorCameraBalanceModeDisplay SensorCameraBalanceModeDisplay protobuf object to modify. default_values : bool Uses default values when True. Notes ----- - **Do not instantiate this class yourself**, use set_balance_mode_display_primaries method available in color class. + **Do not instantiate this class yourself**, use set_balance_mode_display_primaries + method available in color class. """ @@ -1177,9 +1219,9 @@ def set_blue_spectrum_file_uri(self, uri: str) -> SensorCamera.Photometric.Color def set_balance_mode_none(self) -> SensorCamera.Photometric.Color: """Set the balance mode as none. - The spectral transmittance of the optical system and the spectral sensitivity for each channel are applied - to the detected spectral image before the conversion in a three-channel result. - This method is referred to as the basic conversion. + The spectral transmittance of the optical system and the spectral sensitivity for + each channel are applied to the detected spectral image before the conversion in + a three-channel result. This method is referred to as the basic conversion. Returns ------- @@ -1190,12 +1232,15 @@ def set_balance_mode_none(self) -> SensorCamera.Photometric.Color: self._mode_color.balance_mode_none.SetInParent() return self - def set_balance_mode_grey_world(self) -> SensorCamera.Photometric.Color: + def set_balance_mode_grey_world( + self, + ) -> SensorCamera.Photometric.Color: """Set the balance mode as grey world. The grey world assumption states that the content of the image is grey on average. - This method converts spectral results in a three-channel result with the basic conversion. - Then it computes and applies coefficients to the red, green and blue images to make sure their averages are equal. + This method converts spectral results in a three-channel result with the basic + conversion. Then it computes and applies coefficients to the red, green and blue + images to make sure their averages are equal. Returns ------- @@ -1211,7 +1256,8 @@ def set_balance_mode_user_white( ) -> SensorCamera.Photometric.Color.BalanceModeUserWhite: """Set the balance mode as user white. - In addition to the basic treatment, it allows to apply specific coefficients to the red, green, blue images. + In addition to the basic treatment, it allows to apply specific coefficients to the + red, green, blue images. Returns ------- @@ -1225,7 +1271,9 @@ def set_balance_mode_user_white( default_values=False, stable_ctr=True, ) - elif type(self._mode) != SensorCamera.Photometric.Color.BalanceModeUserWhite: + elif not isinstance( + self._mode, SensorCamera.Photometric.Color.BalanceModeUserWhite + ): # if the _mode is not BalanceModeUserWhite then we create a new type. self._mode = SensorCamera.Photometric.Color.BalanceModeUserWhite( balance_mode_user_white=self._mode_color.balance_mode_userwhite, @@ -1245,8 +1293,9 @@ def set_balance_mode_display_primaries( """Set the balance mode as display primaries. Spectral results are converted in a three-channel result. - Then a post-treatment is realized to take the distortion induced by the display devices into account. - With this method, displayed results are similar to what the camera really gets. + Then a post-treatment is realized to take the distortion induced by the display + devices into account. With this method, displayed results are similar to what the + camera really gets. Returns ------- @@ -1260,10 +1309,13 @@ def set_balance_mode_display_primaries( default_values=False, stable_ctr=True, ) - elif type(self._mode) != SensorCamera.Photometric.Color.BalanceModeDisplayPrimaries: + elif not isinstance( + self._mode, SensorCamera.Photometric.Color.BalanceModeDisplayPrimaries + ): # if the _mode is not BalanceModeDisplayPrimaries then we create a new type. self._mode = SensorCamera.Photometric.Color.BalanceModeDisplayPrimaries( - balance_mode_display=self._mode_color.balance_mode_display, stable_ctr=True + balance_mode_display=self._mode_color.balance_mode_display, + stable_ctr=True, ) elif self._mode._balance_mode_display is not self._mode_color.balance_mode_display: # Happens in case of feature reset (to be sure to always modify correct data) @@ -1288,7 +1340,8 @@ def __init__( # Attribute to keep track of wavelength range object self._wavelengths_range = SensorCamera.WavelengthsRange( - wavelengths_range=self._mode_photometric.wavelengths_range, stable_ctr=stable_ctr + wavelengths_range=self._mode_photometric.wavelengths_range, + stable_ctr=stable_ctr, ) if default_values: @@ -1464,10 +1517,11 @@ def set_mode_color(self) -> SensorCamera.Photometric.Color: default_values=False, stable_ctr=True, ) - elif type(self._mode) != SensorCamera.Photometric.Color: + elif not isinstance(self._mode, SensorCamera.Photometric.Color): # if the _mode is not Color then we create a new type. self._mode = SensorCamera.Photometric.Color( - mode_color=self._mode_photometric.color_mode_color, stable_ctr=True + mode_color=self._mode_photometric.color_mode_color, + stable_ctr=True, ) elif self._mode._mode_color is not self._mode_photometric.color_mode_color: # Happens in case of feature reset (to be sure to always modify correct data) @@ -1480,7 +1534,8 @@ def set_trajectory_file_uri(self, uri: str) -> SensorCamera.Photometric: Parameters ---------- uri : str - Trajectory file, used to define the position and orientations of the Camera sensor in time. + Trajectory file, used to define the position and orientations of the Camera sensor + in time. Returns ------- @@ -1576,7 +1631,8 @@ def set_imager_distance(self, value: float = 10) -> SensorCamera: Parameters ---------- value : float - Imager distance (mm). The imager is located at the focal point. The Imager distance has no impact on the result. + Imager distance (mm). The imager is located at the focal point. + The Imager distance has no impact on the result. By default, ``10``. Returns @@ -1593,7 +1649,8 @@ def set_f_number(self, value: float = 20) -> SensorCamera: Parameters ---------- value : float - F-number represents the aperture of the front lens. F number has no impact on the result. + F-number represents the aperture of the front lens. + F number has no impact on the result. By default, ``20``. Returns @@ -1610,7 +1667,8 @@ def set_distortion_file_uri(self, uri: str) -> SensorCamera: Parameters ---------- uri : str - Optical aberration that deforms and bends straight lines. The distortion is expressed in a .OPTDistortion file. + Optical aberration that deforms and bends straight lines. The distortion is expressed in + a .OPTDistortion file. Returns ------- @@ -1705,7 +1763,8 @@ def set_mode_geometric(self) -> SensorCamera: def set_mode_photometric(self) -> SensorCamera.Photometric: """Set mode photometric for the camera sensor. - This allows setting every Camera Sensor parameter, including the photometric definition parameters. + This allows setting every Camera Sensor parameter, including the photometric definition + parameters. Returns ------- @@ -1722,7 +1781,7 @@ def set_mode_photometric(self) -> SensorCamera.Photometric: default_values=False, stable_ctr=True, ) - elif type(self._type) != SensorCamera.Photometric: + elif not isinstance(self._type, SensorCamera.Photometric): # if the _type is not Photometric then we create a new type. self._type = SensorCamera.Photometric( mode_photometric=self._sensor_template.camera_sensor_template.sensor_mode_photometric, @@ -1762,9 +1821,9 @@ def set_axis_system(self, axis_system: Optional[List[float]] = None) -> SensorCa class SensorIrradiance(BaseSensor): """Sensor feature: Irradiance. - By default, regarding inherent characteristics, an irradiance sensor of type photometric and illuminance type planar is chosen. - By default, regarding properties, an axis system is selected to position the sensor, no layer separation and no ray file generation - are chosen. + By default, regarding inherent characteristics, an irradiance sensor of type photometric and + illuminance type planar is chosen. By default, regarding properties, an axis system is + selected to position the sensor, no layer separation and no ray file generation are chosen. Parameters ---------- @@ -1898,7 +1957,7 @@ def layer( ------- Union[\ None,\ - ansys.speos.core.sensor.Irradiance,\ + ansys.speos.core.sensor.SensorIrradiance,\ ansys.speos.core.sensor.BaseSensor.LayerTypeFace,\ ansys.speos.core.sensor.BaseSensor.LayerTypeSequence,\ ansys.speos.core.sensor.BaseSensor.LayerTypeIncidenceAngle\ @@ -1942,7 +2001,8 @@ def set_type_photometric(self) -> SensorIrradiance: def set_type_colorimetric(self) -> BaseSensor.Colorimetric: """Set type colorimetric. - The sensor will generate color results without any spectral data or layer separation (in lx or W//m2). + The sensor will generate color results without any spectral data or layer separation + in lx or W//m2. Returns ------- @@ -1958,7 +2018,7 @@ def set_type_colorimetric(self) -> BaseSensor.Colorimetric: default_values=False, stable_ctr=True, ) - elif type(self._type) != BaseSensor.Colorimetric: + elif not isinstance(self._type, BaseSensor.Colorimetric): # if the _type is not Colorimetric then we create a new type. self._type = BaseSensor.Colorimetric( sensor_type_colorimetric=self._sensor_template.irradiance_sensor_template.sensor_type_colorimetric, @@ -1991,7 +2051,8 @@ def set_type_radiometric(self) -> SensorIrradiance: def set_type_spectral(self) -> BaseSensor.Spectral: """Set type spectral. - The sensor will generate color results and spectral data separated by wavelength (in lx or W/m2). + The sensor will generate color results and spectral data separated by wavelength + in lx or W/m2. Returns ------- @@ -2007,7 +2068,7 @@ def set_type_spectral(self) -> BaseSensor.Spectral: default_values=False, stable_ctr=True, ) - elif type(self._type) != BaseSensor.Spectral: + elif not isinstance(self._type, BaseSensor.Spectral): # if the _type is not Spectral then we create a new type. self._type = BaseSensor.Spectral( sensor_type_spectral=self._sensor_template.irradiance_sensor_template.sensor_type_spectral, @@ -2034,7 +2095,8 @@ def set_illuminance_type_planar( ---------- integration_direction : List[float], optional Sensor global integration direction [x,y,z]. - By default, ``None``. None means that a default direction is chosen (anti-normal of the sensor plane). + By default, ``None``. None means that a default direction is chosen + (anti-normal of the sensor plane). Returns ------- @@ -2092,7 +2154,8 @@ def set_illuminance_type_semi_cylindrical( ---------- integration_direction : List[float], optional Sensor global integration direction [x,y,z]. - By default, ``None``. None means that a default direction is chosen (anti-normal of the sensor plane). + By default, ``None``. None means that a default direction is chosen + (anti-normal of the sensor plane). Returns ------- @@ -2236,7 +2299,7 @@ def set_layer_type_face(self) -> BaseSensor.LayerTypeFace: default_values=False, stable_ctr=True, ) - elif type(self._layer_type) != BaseSensor.LayerTypeFace: + elif not isinstance(self._layer_type, BaseSensor.LayerTypeFace): # if the _layer_type is not LayerTypeFace then we create a new type. self._layer_type = BaseSensor.LayerTypeFace( layer_type_face=self._sensor_instance.irradiance_properties.layer_type_face, @@ -2269,7 +2332,7 @@ def set_layer_type_sequence(self) -> BaseSensor.LayerTypeSequence: default_values=False, stable_ctr=True, ) - elif type(self._layer_type) != BaseSensor.LayerTypeSequence: + elif not isinstance(self._layer_type, BaseSensor.LayerTypeSequence): # if the _type is not LayerTypeSequence then we create a new type. self._layer_type = BaseSensor.LayerTypeSequence( layer_type_sequence=self._sensor_instance.irradiance_properties.layer_type_sequence, @@ -2297,7 +2360,9 @@ def set_layer_type_polarization(self) -> SensorIrradiance: self._layer_type = None return self - def set_layer_type_incidence_angle(self) -> BaseSensor.LayerTypeIncidenceAngle: + def set_layer_type_incidence_angle( + self, + ) -> BaseSensor.LayerTypeIncidenceAngle: """Define layer separation as by incidence angle. Returns @@ -2314,7 +2379,7 @@ def set_layer_type_incidence_angle(self) -> BaseSensor.LayerTypeIncidenceAngle: default_values=False, stable_ctr=True, ) - elif type(self._layer_type) != BaseSensor.LayerTypeIncidenceAngle: + elif not isinstance(self._layer_type, BaseSensor.LayerTypeIncidenceAngle): # if the _layer_type is not LayerTypeIncidenceAngle then we create a new type. self._layer_type = BaseSensor.LayerTypeIncidenceAngle( layer_type_incidence_angle=self._sensor_instance.irradiance_properties.layer_type_incidence_angle, @@ -2359,7 +2424,8 @@ class SensorRadiance(BaseSensor): """Sensor feature: Radiance. By default, regarding inherent characteristics, a radiance sensor of type photometric is chosen. - By default, regarding properties, an axis system is selected to position the sensor and no layer separation is chosen. + By default, regarding properties, an axis system is selected to position the sensor and no layer + separation is chosen. Parameters ---------- @@ -2478,12 +2544,18 @@ def spectral(self) -> Union[None, BaseSensor.Spectral]: return None @property - def layer(self) -> Union[None, BaseSensor.LayerTypeFace, BaseSensor.LayerTypeSequence]: + def layer( + self, + ) -> Union[None, BaseSensor.LayerTypeFace, BaseSensor.LayerTypeSequence]: """Property containing all options in regard to the layer separation property. Returns ------- - Union[None, ansys.speos.core.sensor.BaseSensor.LayerTypeFace, ansys.speos.core.sensor.BaseSensor.LayerTypeSequence] + Union[\ + None,\ + ansys.speos.core.sensor.BaseSensor.LayerTypeFace,\ + ansys.speos.core.sensor.BaseSensor.LayerTypeSequence\ + ] Instance of Layer type Class for this sensor feature """ return self._layer_type @@ -2523,7 +2595,8 @@ def set_type_photometric(self) -> SensorRadiance: def set_type_colorimetric(self) -> BaseSensor.Colorimetric: """Set type colorimetric. - The sensor will generate color results without any spectral data or layer separation (in lx or W//m2). + The sensor will generate color results without any spectral data or layer separation + in lx or W//m2. Returns ------- @@ -2539,7 +2612,7 @@ def set_type_colorimetric(self) -> BaseSensor.Colorimetric: default_values=False, stable_ctr=True, ) - elif type(self._type) != BaseSensor.Colorimetric: + elif not isinstance(self._type, BaseSensor.Colorimetric): # if the _type is not Colorimetric then we create a new type. self._type = BaseSensor.Colorimetric( sensor_type_colorimetric=self._sensor_template.radiance_sensor_template.sensor_type_colorimetric, @@ -2572,7 +2645,8 @@ def set_type_radiometric(self) -> SensorRadiance: def set_type_spectral(self) -> BaseSensor.Spectral: """Set type spectral. - The sensor will generate color results and spectral data separated by wavelength (in lx or W/m2). + The sensor will generate color results and spectral data separated by wavelength + in lx or W/m2. Returns ------- @@ -2588,7 +2662,7 @@ def set_type_spectral(self) -> BaseSensor.Spectral: default_values=False, stable_ctr=True, ) - elif type(self._type) != BaseSensor.Spectral: + elif not isinstance(self._type, BaseSensor.Spectral): # if the _type is not Spectral then we create a new type. self._type = BaseSensor.Spectral( sensor_type_spectral=self._sensor_template.radiance_sensor_template.sensor_type_spectral, @@ -2658,8 +2732,9 @@ def set_axis_system(self, axis_system: Optional[List[float]] = None) -> SensorRa return self def set_observer_point(self, value: Optional[List[float]] = None) -> SensorRadiance: - """Set the position of the observer point. This is optional, because the focal length is used by default. + """Set the position of the observer point. + This is optional, because the focal length is used by default. Choosing to set an observer point will make the focal length ignored. Parameters @@ -2722,7 +2797,7 @@ def set_layer_type_face(self) -> BaseSensor.LayerTypeFace: default_values=False, stable_ctr=True, ) - elif type(self._layer_type) != BaseSensor.LayerTypeFace: + elif not isinstance(self._layer_type, BaseSensor.LayerTypeFace): # if the _layer_type is not LayerTypeFace then we create a new type. self._layer_type = BaseSensor.LayerTypeFace( layer_type_face=self._sensor_instance.radiance_properties.layer_type_face, @@ -2755,7 +2830,7 @@ def set_layer_type_sequence(self) -> BaseSensor.LayerTypeSequence: default_values=False, stable_ctr=True, ) - elif type(self._layer_type) != BaseSensor.LayerTypeSequence: + elif not isinstance(self._layer_type, BaseSensor.LayerTypeSequence): # if the _layer_type is not LayerTypeSequence then we create a new type. self._layer_type = BaseSensor.LayerTypeSequence( layer_type_sequence=self._sensor_instance.radiance_properties.layer_type_sequence, diff --git a/src/ansys/speos/core/simulation.py b/src/ansys/speos/core/simulation.py index 8f1be7910..52dc638f6 100644 --- a/src/ansys/speos/core/simulation.py +++ b/src/ansys/speos/core/simulation.py @@ -68,13 +68,15 @@ class BaseSimulation: """ class Weight: - """The Weight represents the ray energy. In real life, a ray loses some energy (power) when it interacts with an object. + """The Weight represents the ray energy. + In real life, a ray loses some energy (power) when it interacts with an object. Activating weight means that the Weight message is present. - When weight is not activated, rays' energy stays constant and probability laws dictate if rays continue or stop propagating. - When weight is activated, the rays' energy evolves with interactions until rays reach the sensors. - It is highly recommended to fill this parameter excepted in interactive simulation. - Not filling this parameter is useful to understand certain phenomena as absorption. + When weight is not activated, rays' energy stays constant and probability laws dictate if + rays continue or stop propagating. When weight is activated, the rays' energy evolves with + interactions until rays reach the sensors. It is highly recommended to fill this parameter + excepted in interactive simulation. Not filling this parameter is useful to understand + certain phenomena as absorption. Parameters ---------- @@ -84,12 +86,15 @@ class Weight: Notes ----- - **Do not instantiate this class yourself**, use set_weight method available in simulation classes. + **Do not instantiate this class yourself**, use set_weight method available in simulation + classes. """ def __init__( - self, weight: simulation_template_pb2.Weight, stable_ctr: bool = False + self, + weight: simulation_template_pb2.Weight, + stable_ctr: bool = False, ) -> None: if not stable_ctr: msg = "Weight class instantiated outside of class scope" @@ -104,8 +109,8 @@ def set_minimum_energy_percentage(self, value: float = 0.005) -> BaseSimulation. Parameters ---------- value : float - The Minimum energy percentage parameter defines the minimum energy ratio to continue to propagate a ray with weight. - By default, ``0.005``. + The Minimum energy percentage parameter defines the minimum energy ratio to continue + to propagate a ray with weight. By default, ``0.005``. Returns ------- @@ -198,24 +203,24 @@ def set_source_paths(self, source_paths: List[str]) -> BaseSimulation: return self # def set_geometries(self, geometries: List[GeoRef]) -> Simulation: - # """Set geometries that the simulation will take into account. + # """Set geometries that the simulation will take into account. # - # Parameters - # ---------- - # geometries : List[ansys.speos.core.geo_ref.GeoRef] + # Parameters + # ---------- + # geometries : List[ansys.speos.core.geo_ref.GeoRef] # List of geometries. # - # Returns - # ------- - # ansys.speos.core.simulation.BaseSimulation + # Returns + # ------- + # ansys.speos.core.simulation.BaseSimulation # Simulation feature. - # """ - # if geometries is []: - # self._simulation_instance.ClearField("geometries") - # else: - # self._simulation_instance.geometries.geo_paths[:] = [gr.to_native_link() for gr in geometries] - # - # return self + # """ + # if geometries is []: + # self._simulation_instance.ClearField("geometries") + # else: + # geo_paths = [gr.to_native_link() for gr in geometries] + # self._simulation_instance.geometries.geo_paths[:] = geo_paths + # return self def compute_CPU(self) -> List[job_pb2.Result]: """Compute the simulation on CPU. @@ -288,27 +293,33 @@ def _to_dict(self) -> dict: ) else: out_dict = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._simulation_instance + speos_client=self._project.client, + message=self._simulation_instance, ) else: out_dict = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._simulation_instance + speos_client=self._project.client, + message=self._simulation_instance, ) if "simulation" not in out_dict.keys(): # SimulationTemplate if self.simulation_template_link is None: out_dict["simulation"] = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._simulation_template + speos_client=self._project.client, + message=self._simulation_template, ) else: out_dict["simulation"] = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self.simulation_template_link.get() + speos_client=self._project.client, + message=self.simulation_template_link.get(), ) if self.job_link is None: out_dict["simulation_properties"] = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._job, ignore_simple_key="scene_guid" + speos_client=self._project.client, + message=self._job, + ignore_simple_key="scene_guid", ) else: out_dict["simulation_properties"] = proto_message_utils._replace_guids( @@ -338,7 +349,10 @@ def get(self, key: str = "") -> str | dict: info = proto_message_utils._value_finder_key_startswith(dict_var=self._to_dict(), key=key) content = list(info) if len(content) != 0: - content.sort(key=lambda x: SequenceMatcher(None, x[0], key).ratio(), reverse=True) + content.sort( + key=lambda x: SequenceMatcher(None, x[0], key).ratio(), + reverse=True, + ) return content[0][1] info = proto_message_utils._flatten_dict(dict_var=self._to_dict()) print("Used key: {} not found in key list: {}.".format(key, info.keys())) @@ -371,7 +385,8 @@ def commit(self) -> BaseSimulation: ansys.speos.core.simulation.BaseSimulation Simulation feature. """ - # The _unique_id will help to find correct item in the scene.simulations (the list of SimulationInstance) + # The _unique_id will help to find correct item in the scene.simulations: + # the list of SimulationInstance if self._unique_id is None: self._unique_id = str(uuid.uuid4()) self._simulation_instance.metadata["UniqueId"] = self._unique_id @@ -462,7 +477,8 @@ def delete(self) -> BaseSimulation: # Remove the simulation from the scene scene_data = self._project.scene_link.get() # retrieve scene data sim_inst = next( - (x for x in scene_data.simulations if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.simulations if x.metadata["UniqueId"] == self._unique_id), + None, ) if sim_inst is not None: scene_data.simulations.remove(sim_inst) @@ -496,7 +512,8 @@ class SimulationDirect(BaseSimulation): fast transmission gathering is set to False, ambient material URI is empty, and weight's minimum energy percentage is set to 0.005. - By default, the simulation will stop after 200000 rays, with an automatic save frequency of 1800s. + By default, the simulation will stop after 200000 rays, + with an automatic save frequency of 1800s. Parameters ---------- @@ -594,7 +611,8 @@ def set_weight(self) -> BaseSimulation.Weight: Weight. """ return BaseSimulation.Weight( - self._simulation_template.direct_mc_simulation_template.weight, stable_ctr=True + self._simulation_template.direct_mc_simulation_template.weight, + stable_ctr=True, ) def set_weight_none(self) -> SimulationDirect: @@ -656,23 +674,26 @@ def set_dispersion(self, value: bool = True) -> SimulationDirect: return self # def set_fast_transmission_gathering(self, value: bool = False) -> Simulation.Direct: - # """Activate/Deactivate the fast transmission gathering. - # To accelerate the simulation by neglecting the light refraction that occurs when the light is being - # transmitted through a transparent surface. + # """Activate/Deactivate the fast transmission gathering. + # + # To accelerate the simulation by neglecting the light refraction that occurs when the + # light is being + # transmitted through a transparent surface. # - # Parameters - # ---------- - # value : bool + # Parameters + # ---------- + # value : bool # Activate/Deactivate. # By default, ``False``, means deactivate # - # Returns - # ------- - # ansys.speos.core.simulation.Direct + # Returns + # ------- + # ansys.speos.core.simulation.Direct # Direct simulation - # """ - # self._simulation_template.direct_mc_simulation_template.fast_transmission_gathering = value - # return self + # """ + # template = self._simulation_template.direct_mc_simulation_template + # template.fast_transmission_gathering = value + # return self def set_ambient_material_file_uri(self, uri: str = "") -> SimulationDirect: """To define the environment in which the light will propagate (water, fog, smoke etc.). @@ -692,7 +713,9 @@ def set_ambient_material_file_uri(self, uri: str = "") -> SimulationDirect: return self def set_stop_condition_rays_number(self, value: Optional[int] = 200000) -> SimulationDirect: - """To stop the simulation after a certain number of rays were sent. Set None as value to have no condition about rays number. + """To stop the simulation after a certain number of rays were sent. + + Set None as value to have no condition about rays number. Parameters ---------- @@ -712,7 +735,9 @@ def set_stop_condition_rays_number(self, value: Optional[int] = 200000) -> Simul return self def set_stop_condition_duration(self, value: Optional[int] = None) -> SimulationDirect: - """To stop the simulation after a certain duration. Set None as value to have no condition about duration. + """To stop the simulation after a certain duration. + + Set None as value to have no condition about duration. Parameters ---------- @@ -867,7 +892,8 @@ def set_weight(self) -> BaseSimulation.Weight: Simulation.Weight """ return BaseSimulation.Weight( - self._simulation_template.inverse_mc_simulation_template.weight, stable_ctr=True + self._simulation_template.inverse_mc_simulation_template.weight, + stable_ctr=True, ) def set_weight_none(self) -> SimulationInverse: @@ -931,7 +957,8 @@ def set_dispersion(self, value: bool = False) -> SimulationInverse: def set_splitting(self, value: bool = False) -> SimulationInverse: """Activate/Deactivate the splitting. - To split each propagated ray into several paths at their first impact after leaving the observer point. + To split each propagated ray into several paths at their first impact after leaving the + observer point. Parameters ---------- @@ -961,7 +988,8 @@ def set_number_of_gathering_rays_per_source(self, value: int = 1) -> SimulationI ansys.speos.core.simulation.SimulationInverse Inverse simulation """ - self._simulation_template.inverse_mc_simulation_template.number_of_gathering_rays_per_source = value + template = self._simulation_template.inverse_mc_simulation_template + template.number_of_gathering_rays_per_source = value return self def set_maximum_gathering_error(self, value: int = 0) -> SimulationInverse: @@ -982,23 +1010,25 @@ def set_maximum_gathering_error(self, value: int = 0) -> SimulationInverse: return self # def set_fast_transmission_gathering(self, value: bool = False) -> Simulation.Inverse: - # """Activate/Deactivate the fast transmission gathering. - # To accelerate the simulation by neglecting the light refraction that occurs when the light is being - # transmitted through a transparent surface. + # """Activate/Deactivate the fast transmission gathering. # - # Parameters - # ---------- - # value : bool - # Activate/Deactivate. - # By default, ``False``, means deactivate + # To accelerate the simulation by neglecting the light refraction that occurs when the light + # is being transmitted through a transparent surface. # - # Returns - # ------- - # ansys.speos.core.simulation.Inverse - # Inverse simulation - # """ - # self._simulation_template.inverse_mc_simulation_template.fast_transmission_gathering = value - # return self + # Parameters + # ---------- + # value : bool + # Activate/Deactivate. + # By default, ``False``, means deactivate + # + # Returns + # ------- + # ansys.speos.core.simulation.Inverse + # Inverse simulation + # """ + # template = self._simulation_template.inverse_mc_simulation_template + # template.fast_transmission_gathering = value + # return self def set_ambient_material_file_uri(self, uri: str = "") -> SimulationInverse: """To define the environment in which the light will propagate (water, fog, smoke etc.). @@ -1018,7 +1048,9 @@ def set_ambient_material_file_uri(self, uri: str = "") -> SimulationInverse: return self def set_stop_condition_passes_number(self, value: Optional[int] = 5) -> SimulationInverse: - """To stop the simulation after a certain number of passes. Set None as value to have no condition about passes. + """To stop the simulation after a certain number of passes. + + Set None as value to have no condition about passes. Parameters ---------- @@ -1031,16 +1063,17 @@ def set_stop_condition_passes_number(self, value: Optional[int] = 5) -> Simulati ansys.speos.core.simulation.SimulationInverse Inverse simulation """ + propagation_none = self._job.inverse_mc_simulation_properties.optimized_propagation_none if value is None: - self._job.inverse_mc_simulation_properties.optimized_propagation_none.ClearField( - "stop_condition_passes_number" - ) + propagation_none.ClearField("stop_condition_passes_number") else: - self._job.inverse_mc_simulation_properties.optimized_propagation_none.stop_condition_passes_number = value + propagation_none.stop_condition_passes_number = value return self def set_stop_condition_duration(self, value: Optional[int] = None) -> SimulationInverse: - """To stop the simulation after a certain duration. Set None as value to have no condition about duration. + """To stop the simulation after a certain duration. + + Set None as value to have no condition about duration. Parameters ---------- @@ -1204,7 +1237,8 @@ def set_weight(self) -> BaseSimulation.Weight: Simulation.Weight """ return BaseSimulation.Weight( - self._simulation_template.interactive_simulation_template.weight, stable_ctr=True + self._simulation_template.interactive_simulation_template.weight, + stable_ctr=True, ) def set_weight_none(self) -> SimulationInteractive: @@ -1270,7 +1304,8 @@ def set_rays_number_per_sources( ) -> SimulationInteractive: """Select the number of rays emitted for each source. - If a source is present in the simulation but not referenced here, it will send by default 100 rays. + If a source is present in the simulation but not referenced here, it will send by default + 100 rays. Parameters ---------- @@ -1284,7 +1319,8 @@ def set_rays_number_per_sources( """ my_list = [ ProtoJob.InteractiveSimulationProperties.RaysNumberPerSource( - source_path=rays_nb_per_source.source_path, rays_nb=rays_nb_per_source.rays_nb + source_path=rays_nb_per_source.source_path, + rays_nb=rays_nb_per_source.rays_nb, ) for rays_nb_per_source in values ] @@ -1310,7 +1346,9 @@ def set_light_expert(self, value: bool = False) -> SimulationInteractive: return self def set_impact_report(self, value: bool = False) -> SimulationInteractive: - """Activate/Deactivate the details like number of impacts, position and surface state to the HTML simulation report. + """Activate/Deactivate the details in the HTML simulation report. + + e.g: number of impacts, position and surface state Parameters ---------- diff --git a/src/ansys/speos/core/source.py b/src/ansys/speos/core/source.py index 401142b86..9b91492dc 100644 --- a/src/ansys/speos/core/source.py +++ b/src/ansys/speos/core/source.py @@ -28,7 +28,10 @@ from typing import List, Mapping, Optional, Union import uuid -from ansys.speos.core import project as project, proto_message_utils as proto_message_utils +from ansys.speos.core import ( + project as project, + proto_message_utils as proto_message_utils, +) from ansys.speos.core.geo_ref import GeoRef from ansys.speos.core.intensity import Intensity from ansys.speos.core.kernel.client import SpeosClient @@ -109,7 +112,9 @@ def __init__( self._message_to_complete = message_to_complete if spectrum_guid != "": self._spectrum = Spectrum( - speos_client=speos_client, name=name + ".Spectrum", key=spectrum_guid + speos_client=speos_client, + name=name + ".Spectrum", + key=spectrum_guid, ) else: self._spectrum = Spectrum(speos_client=speos_client, name=name + ".Spectrum") @@ -150,7 +155,8 @@ def _to_dict(self) -> dict: if self._project.scene_link and self._unique_id is not None: scene_data = self._project.scene_link.get() src_inst = next( - (x for x in scene_data.sources if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.sources if x.metadata["UniqueId"] == self._unique_id), + None, ) if src_inst is not None: out_dict = proto_message_utils._replace_guids( @@ -158,7 +164,8 @@ def _to_dict(self) -> dict: ) else: out_dict = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._source_instance + speos_client=self._project.client, + message=self._source_instance, ) else: out_dict = proto_message_utils._replace_guids( @@ -169,11 +176,13 @@ def _to_dict(self) -> dict: # SourceTemplate if self.source_template_link is None: out_dict["source"] = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self._source_template + speos_client=self._project.client, + message=self._source_template, ) else: out_dict["source"] = proto_message_utils._replace_guids( - speos_client=self._project.client, message=self.source_template_link.get() + speos_client=self._project.client, + message=self.source_template_link.get(), ) # # handle spectrum & intensity @@ -200,7 +209,10 @@ def get(self, key: str = "") -> list[tuple[str, dict]]: info = proto_message_utils._value_finder_key_startswith(dict_var=self._to_dict(), key=key) content = list(info) if len(content) != 0: - content.sort(key=lambda x: SequenceMatcher(None, x[0], key).ratio(), reverse=True) + content.sort( + key=lambda x: SequenceMatcher(None, x[0], key).ratio(), + reverse=True, + ) return content[0][1] info = proto_message_utils._flatten_dict(dict_var=self._to_dict()) print("Used key: {} not found in key list: {}.".format(key, info.keys())) @@ -211,7 +223,8 @@ def __str__(self) -> str: if self._project.scene_link and self._unique_id is not None: scene_data = self._project.scene_link.get() src_inst = next( - (x for x in scene_data.sources if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.sources if x.metadata["UniqueId"] == self._unique_id), + None, ) if src_inst is None: out_str += "local: " @@ -229,7 +242,8 @@ def _commit(self) -> BaseSource: ansys.speos.core.source.BaseSource Source feature. """ - # The _unique_id will help to find correct item in the scene.sources (the list of SourceInstance) + # The _unique_id will help to find correct item in the scene.sources: + # the list of SourceInstance if self._unique_id is None: self._unique_id = str(uuid.uuid4()) self._source_instance.metadata["UniqueId"] = self._unique_id @@ -252,7 +266,8 @@ def _commit(self) -> BaseSource: # Look if an element corresponds to the _unique_id src_inst = next( - (x for x in scene_data.sources if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.sources if x.metadata["UniqueId"] == self._unique_id), + None, ) if src_inst is not None: if src_inst != self._source_instance: @@ -286,7 +301,8 @@ def _reset(self) -> BaseSource: scene_data = self._project.scene_link.get() # retrieve scene data # Look if an element corresponds to the _unique_id src_inst = next( - (x for x in scene_data.sources if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.sources if x.metadata["UniqueId"] == self._unique_id), + None, ) if src_inst is not None: self._source_instance = src_inst @@ -302,7 +318,8 @@ def _delete(self) -> BaseSource: ansys.speos.core.source.BaseSource Source feature. """ - # This allows to clean-managed object contained in _luminaire, _rayfile, etc.. Like Spectrum, IntensityTemplate + # This allows to clean-managed object contained in _luminaire, _rayfile, etc.. + # Like Spectrum, IntensityTemplate # Delete the source template if self.source_template_link is not None: @@ -315,7 +332,8 @@ def _delete(self) -> BaseSource: # Remove the source from the scene scene_data = self._project.scene_link.get() # retrieve scene data src_inst = next( - (x for x in scene_data.sources if x.metadata["UniqueId"] == self._unique_id), None + (x for x in scene_data.sources if x.metadata["UniqueId"] == self._unique_id), + None, ) if src_inst is not None: scene_data.sources.remove(src_inst) @@ -741,24 +759,27 @@ class ExitanceVariable: Parameters ---------- - exitance_variable : ansys.api.speos.source.v1.source_pb2.SourceTemplate.Surface.ExitanceVariable + exitance_variable : ansys.api.speos.source.v1.source_pb2.SourceTemplate.Surface. + ExitanceVariable Existence variable to complete. - exitance_variable_props : ansys.api.speos.scene.v2.scene_pb2.Scene.SourceInstance.SurfaceProperties.ExitanceVariableProperties + exitance_variable_props : ansys.api.speos.scene.v2.scene_pb2.Scene.SourceInstance. + SurfaceProperties.ExitanceVariableProperties Existence variable properties to complete. default_values : bool Uses default values when True. - stable_ctr : bool + stable_ctr : bool Variable to indicate if usage is inside class scope Notes ----- - **Do not instantiate this class yourself**, use set_exitance_variable method available in Source classes. + **Do not instantiate this class yourself**, use set_exitance_variable method available in + Source classes. """ def __init__( self, - exitance_variable: ProtoSourceTemplate.Surface.ExitanceVariable, - exitance_variable_props: ProtoScene.SourceInstance.SurfaceProperties.ExitanceVariableProperties, + exitance_variable, + exitance_variable_props, default_values: bool = True, stable_ctr: bool = False, ) -> None: @@ -984,7 +1005,7 @@ def set_exitance_variable(self) -> SourceSurface.ExitanceVariable: default_values=False, stable_ctr=True, ) - elif type(self._exitance_type) != SourceSurface.ExitanceVariable: + elif not isinstance(self._exitance_type, SourceSurface.ExitanceVariable): # if the _exitance_type is not ExitanceVariable then we create a new type. self._exitance_type = SourceSurface.ExitanceVariable( exitance_variable=self._source_template.surface.exitance_variable, @@ -1074,7 +1095,8 @@ def delete(self) -> SourceSurface: ansys.speos.core.source.SourceSurface Source feature. """ - # Currently we don't perform delete in cascade, so deleting a surface source does not delete the intensity template used + # Currently we don't perform delete in cascade, + # so deleting a surface source does not delete the intensity template used # self._intensity.delete() # spectrum & source diff --git a/src/ansys/speos/core/workflow/__init__.py b/src/ansys/speos/core/workflow/__init__.py index 82501a46f..6a0eaec52 100644 --- a/src/ansys/speos/core/workflow/__init__.py +++ b/src/ansys/speos/core/workflow/__init__.py @@ -24,7 +24,14 @@ import os -from ansys.speos.core.workflow.combine_speos import SpeosFileInstance, combine_speos, insert_speos +from ansys.speos.core.workflow.combine_speos import ( + SpeosFileInstance, + combine_speos, + insert_speos, +) if os.name == "nt": - from ansys.speos.core.workflow.open_result import open_result_image, open_result_in_viewer + from ansys.speos.core.workflow.open_result import ( + open_result_image, + open_result_in_viewer, + ) diff --git a/src/ansys/speos/core/workflow/combine_speos.py b/src/ansys/speos/core/workflow/combine_speos.py index 9d242ff82..f692e7670 100644 --- a/src/ansys/speos/core/workflow/combine_speos.py +++ b/src/ansys/speos/core/workflow/combine_speos.py @@ -33,23 +33,31 @@ class SpeosFileInstance: """Represents a SPEOS file containing geometries and materials. - Geometries are placed in the root part of a project, and oriented according to the axis_system argument. + Geometries are placed in the root part of a project, and oriented according to the axis_system + argument. Parameters ---------- speos_file : str SPEOS file to be loaded. axis_system : Optional[List[float]] - Location and orientation to define for the geometry of the SPEOS file, [Ox Oy Oz Xx Xy Xz Yx Yy Yz Zx Zy Zz]. + Location and orientation to define for the geometry of the SPEOS file, + [Ox, Oy, Oz, Xx, Xy, Xz, Yx, Yy, Yz, Zx, Zy, Zz]. By default, ``[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]``. name : str - Name chosen for the imported geometry. This name is used as subpart name under the root part of the project. - By default, "" (meaning user has not defined a name), then the name of the SPEOS file without extension is taken. - Note: Materials are named after the name. For instance name.material.1 representing the first material of the imported geometry. + Name chosen for the imported geometry. This name is used as subpart name under the root part + of the project. + By default, "" (meaning user has not defined a name), then the name of the SPEOS file + without extension is taken. + Note: Materials are named after the name. For instance name.material.1 representing the + first material of the imported geometry. """ def __init__( - self, speos_file: str, axis_system: Optional[List[float]] = None, name: str = "" + self, + speos_file: str, + axis_system: Optional[List[float]] = None, + name: str = "", ) -> None: self.speos_file = speos_file """SPEOS file.""" @@ -96,7 +104,8 @@ def insert_speos(project: Project, speos_to_insert: List[SpeosFileInstance]) -> def combine_speos(speos: Speos, speos_to_combine: List[SpeosFileInstance]) -> Project: """Create a project by combining geometries and materials from the selected SPEOS files. - Geometries and materials are placed in the root part, and orientated thanks to the SpeosFileInstance object. + Geometries and materials are placed in the root part, + and orientated thanks to the SpeosFileInstance object. Notes ----- @@ -124,7 +133,11 @@ def combine_speos(speos: Speos, speos_to_combine: List[SpeosFileInstance]) -> Pr return p -def _combine(project: Project, part_link: PartLink, speos_to_combine: List[SpeosFileInstance]): +def _combine( + project: Project, + part_link: PartLink, + speos_to_combine: List[SpeosFileInstance], +): scene_data = project.scene_link.get() part_data = part_link.get() diff --git a/src/ansys/speos/core/workflow/open_result.py b/src/ansys/speos/core/workflow/open_result.py index a9b46e267..b36f77102 100644 --- a/src/ansys/speos/core/workflow/open_result.py +++ b/src/ansys/speos/core/workflow/open_result.py @@ -36,7 +36,11 @@ import matplotlib.pyplot as plt from numpy import ndarray -from ansys.speos.core.simulation import SimulationDirect, SimulationInteractive, SimulationInverse +from ansys.speos.core.simulation import ( + SimulationDirect, + SimulationInteractive, + SimulationInverse, +) def _find_correct_result( @@ -116,7 +120,8 @@ def open_result_image( _display_image(mpimg.imread(file_path)) def open_result_in_viewer( - simulation_feature: Union[SimulationDirect, SimulationInverse], result_name: str + simulation_feature: Union[SimulationDirect, SimulationInverse], + result_name: str, ) -> None: """Open a specific simulation result in the suitable viewer. diff --git a/tests/conftest.py b/tests/conftest.py index 581a3cd46..5a40bb36f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -29,11 +29,13 @@ import json import logging +import logging as deflogging # Default logging import os from pathlib import Path import pytest +from ansys.speos.core import LOG from ansys.speos.core.speos import Speos @@ -81,14 +83,8 @@ def speos(): else: test_path = local_test_path -# Wait for the grpc server - in case the timeout is reached raise an error - -import logging as deflogging # Default logging - -import pytest # Define default pytest logging level to DEBUG and stdout -from ansys.speos.core import LOG LOG.setLevel(level="DEBUG") LOG.log_to_stdout() diff --git a/tests/core/test_intensity.py b/tests/core/test_intensity.py index 6c335e081..5ae166b63 100644 --- a/tests/core/test_intensity.py +++ b/tests/core/test_intensity.py @@ -46,7 +46,7 @@ def test_create_intensity(speos: Speos): assert intensity1.intensity_template_link.get().HasField("library") assert intensity1._intensity_properties.HasField("library_properties") assert intensity1._intensity_properties.library_properties.HasField("axis_system") - assert intensity1._intensity_properties.library_properties.HasField("exit_geometries") == False + assert intensity1._intensity_properties.library_properties.HasField("exit_geometries") is False intensity1.set_library().set_orientation_normal_to_surface() intensity1.commit() @@ -69,14 +69,14 @@ def test_create_intensity(speos: Speos): intensity1.set_library().set_exit_geometries() # use default [] to reset exit geometries intensity1.commit() - assert intensity1._intensity_properties.library_properties.HasField("exit_geometries") == False + assert intensity1._intensity_properties.library_properties.HasField("exit_geometries") is False # cos intensity1.set_cos(N=2, total_angle=160).commit() assert intensity1.intensity_template_link.get().HasField("cos") assert intensity1.intensity_template_link.get().cos.N == 2 assert intensity1.intensity_template_link.get().cos.total_angle == 160 - assert intensity1._intensity_properties.HasField("library_properties") == False + assert intensity1._intensity_properties.HasField("library_properties") is False # gaussian intensity1.set_gaussian().set_FWHM_angle_x(value=20).set_FWHM_angle_y(value=30).set_total_angle( @@ -116,7 +116,10 @@ def test_create_intensity(speos: Speos): def test_switch_intensity(speos: Speos): - """Test switch of intensity : from one with properties to one without (properties should be emptied).""" + """Test switch of intensity : from one with properties to one without. + + Properties should be emptied. + """ # Use intensity library with some default properties intensity1 = Intensity(speos_client=speos.client, name="Intensity.1") intensity1.set_library().set_intensity_file_uri(uri=str(Path(test_path) / "IES_C_DETECTOR.ies")) @@ -127,7 +130,7 @@ def test_switch_intensity(speos: Speos): # Switch to cos that has no properties intensity1.set_cos().commit() - assert intensity1._intensity_properties.HasField("properties") == False + assert intensity1._intensity_properties.HasField("properties") is False def test_commit_intensity(speos: Speos): diff --git a/tests/core/test_lxp.py b/tests/core/test_lxp.py index f24d53b77..f37576592 100644 --- a/tests/core/test_lxp.py +++ b/tests/core/test_lxp.py @@ -45,13 +45,17 @@ def test_light_path_finder_direct(speos: Speos): "wl": 779.0769653320312, "body_ids": [2001802324, 2001802324, 2001802324, 3601101451], "face_ids": [1815582994, 1815582994, 2122462972, 3866239813], - "last_direction": [0.07366610318422318, -0.9527596235275269, 0.2946563959121704], + "last_direction": [ + 0.07366610318422318, + -0.9527596235275269, + 0.2946563959121704, + ], "intersection_type": [5, 1, 1, -1], "sensor_contribution": None, } assert lpf.nb_traces == 24817 assert lpf.nb_xmps == 3 - assert lpf.has_sensor_contributions == False # No contributions stored in Direct simu + assert lpf.has_sensor_contributions is False # No contributions stored in Direct simu assert len(lpf.sensor_names) == 3 assert lpf.sensor_names[0] == "Irradiance Sensor (0)" assert lpf.sensor_names[2] == "Irradiance Sensor (2)" @@ -101,13 +105,16 @@ def test_light_path_finder_inverse(speos: Speos): "last_direction": [0.0, 0.0, 0.0], "intersection_type": [5, 1, 1, -1, 1, 1, -1], "sensor_contribution": [ - {"sensor_id": 0, "position": [-0.14824546764179047, 0.3064812525259446]} + { + "sensor_id": 0, + "position": [-0.14824546764179047, 0.3064812525259446], + } ], } assert lpf.nb_traces == 21044 assert lpf.nb_xmps == 1 - assert lpf.has_sensor_contributions == True # No contributions stored in Direct simu + assert lpf.has_sensor_contributions is True # No contributions stored in Direct simu assert len(lpf.sensor_names) == 1 assert lpf.sensor_names[0] == "Camera_Perfect_Lens_System_V2:3" lpf.filter_by_body_ids([3744252339]) diff --git a/tests/core/test_opt_prop.py b/tests/core/test_opt_prop.py index b5686465f..2e2246550 100644 --- a/tests/core/test_opt_prop.py +++ b/tests/core/test_opt_prop.py @@ -40,7 +40,7 @@ def test_create_optical_property(speos: Speos): assert op1.sop_template_link is not None assert op1.sop_template_link.get().HasField("mirror") assert op1.sop_template_link.get().mirror.reflectance == 100 - assert op1._material_instance.HasField("geometries") == False + assert op1._material_instance.HasField("geometries") is False # VOP opaque op1.set_volume_opaque().commit() @@ -58,7 +58,7 @@ def test_create_optical_property(speos: Speos): op1.set_volume_optic().commit() assert op1.vop_template_link.get().optic.index == 1.5 assert op1.vop_template_link.get().optic.absorption == 0.0 - assert op1.vop_template_link.get().optic.HasField("constringence") == False + assert op1.vop_template_link.get().optic.HasField("constringence") is False # VOP library op1.set_volume_library(path=str(Path(test_path) / "AIR.material")).commit() @@ -66,14 +66,22 @@ def test_create_optical_property(speos: Speos): assert op1.vop_template_link.get().library.material_file_uri.endswith("AIR.material") # VOP non-homogeneous - bug to be fixed - # op1.set_volume_nonhomogeneous(path=os.path.join(test_path, "Index_1.5_Gradient_0.499_Abs_0.gradedmaterial"), - # axis_system=[10,20,30,1,0,0,0,1,0,0,0,1]).commit() + # op1.set_volume_nonhomogeneous( + # path=Path(test_path) / "Index_1.5_Gradient_0.499_Abs_0.gradedmaterial", + # axis_system=[10, 20, 30, 1, 0, 0, 0, 1, 0, 0, 0, 1], + # ).commit() # assert op1.vop_template_link.get().HasField("non_homogeneous") - # assert op1.vop_template_link.get().non_homogeneous.gradedmaterial_file_uri.endswith("Index_1.5_Gradient_0.499_Abs_0.gradedmaterial") - # assert op1._material_instance.non_homogeneous_properties.axis_system == [10,20,30,1,0,0,0,1,0,0,0,1] + # non_homogeneous = op1.vop_template_link.get().non_homogeneous + # assert non_homogeneous.gradedmaterial_file_uri.endswith( + # "Index_1.5_Gradient_0.499_Abs_0.gradedmaterial" + # ) + # non_homogenous_properties = op1._material_instance.non_homogeneous_properties + # assert non_homogenous_properties.axis_system == [10, 20, 30, 1, 0, 0, 0, 1, 0, 0, 0, 1] # - # op1.set_volume_nonhomogeneous(path=os.path.join(test_path, "Index_1.5_Gradient_0.499_Abs_0.gradedmaterial")).commit() - # assert op1._material_instance.non_homogeneous_properties.axis_system == [0,0,0,1,0,0,0,1,0,0,0,1] + # op1.set_volume_nonhomogeneous( + # path=Path(test_path) / "Index_1.5_Gradient_0.499_Abs_0.gradedmaterial" + # ).commit() + # assert non_homogenous_properties.axis_system == [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1] # SOP optical_polished op1.set_surface_opticalpolished().commit() @@ -100,7 +108,7 @@ def test_create_optical_property(speos: Speos): op1._material_instance.geometries.geo_paths == ["TheBody1", "TheBodyB2"] op1.set_geometries(geometries=None) # means no geometry - assert op1._material_instance.HasField("geometries") == False + assert op1._material_instance.HasField("geometries") is False op1.set_geometries(geometries=[]) # means all geometries assert op1._material_instance.HasField("geometries") @@ -160,7 +168,7 @@ def test_reset_optical_property(speos: Speos): assert op1.sop_template_link.get().HasField("mirror") assert op1._sop_template.HasField("optical_polished") # local template assert p.scene_link.get().materials[0].HasField("geometries") - assert op1._material_instance.HasField("geometries") == False # local instance + assert op1._material_instance.HasField("geometries") is False # local instance # Ask for reset op1.reset() diff --git a/tests/core/test_part.py b/tests/core/test_part.py index 449adc6c0..39f319968 100644 --- a/tests/core/test_part.py +++ b/tests/core/test_part.py @@ -134,7 +134,20 @@ def test_create_subpart(speos: Speos): assert len(root_part._geom_features) == 1 assert len(root_part.part_link.get().parts) == 1 assert root_part.part_link.get().parts[0] == sp1._part_instance - assert sp1._part_instance.axis_system == [5, 4, 10, 1, 0, 0, 0, 1, 0, 0, 0, 1] + assert sp1._part_instance.axis_system == [ + 5, + 4, + 10, + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + ] assert sp1._part_instance.part_guid == sp1.part_link.key assert ( sp1.part_link.get().name == "SubPart.1" @@ -149,7 +162,20 @@ def test_create_subpart(speos: Speos): assert len(root_part._geom_features) == 2 assert len(root_part.part_link.get().parts) == 2 assert root_part.part_link.get().parts[1] == sp2._part_instance - assert sp2._part_instance.axis_system == [15, 14, 14, 1, 0, 0, 0, 1, 0, 0, 0, 1] + assert sp2._part_instance.axis_system == [ + 15, + 14, + 14, + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + ] assert sp2._part_instance.part_guid == sp2.part_link.key assert ( sp2.part_link.get().name == "SubPart.2" @@ -218,7 +244,20 @@ def test_create_subpart_subpart(speos: Speos): assert len(sp1._geom_features) == 1 assert len(sp1.part_link.get().parts) == 1 assert sp1.part_link.get().parts[0] == sp11._part_instance - assert sp11._part_instance.axis_system == [-5, -4, -10, 1, 0, 0, 0, 1, 0, 0, 0, 1] + assert sp11._part_instance.axis_system == [ + -5, + -4, + -10, + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + ] assert sp11._part_instance.part_guid == sp11.part_link.key assert ( sp11.part_link.get().name == "SubPart.11" @@ -233,7 +272,20 @@ def test_create_subpart_subpart(speos: Speos): assert len(sp1._geom_features) == 2 assert len(sp1.part_link.get().parts) == 2 assert sp1.part_link.get().parts[1] == sp12._part_instance - assert sp12._part_instance.axis_system == [-15, -14, -14, 1, 0, 0, 0, 1, 0, 0, 0, 1] + assert sp12._part_instance.axis_system == [ + -15, + -14, + -14, + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + ] assert sp12._part_instance.part_guid == sp12.part_link.key assert ( sp12.part_link.get().name == "SubPart.12" diff --git a/tests/core/test_project.py b/tests/core/test_project.py index 2c650cca9..4124a8c2c 100644 --- a/tests/core/test_project.py +++ b/tests/core/test_project.py @@ -133,7 +133,10 @@ def test_find_feature_geom(speos: Speos): assert len(feats) == 1 # Retrieve face - feats = p.find(name="Solid Body in GUIDE:1379760262/Face in GUIDE:166", feature_type=Part) + feats = p.find( + name="Solid Body in GUIDE:1379760262/Face in GUIDE:166", + feature_type=Part, + ) assert len(feats) == 1 # Retrieve face with regex (regex at body and at face level) diff --git a/tests/core/test_proto_message_utils.py b/tests/core/test_proto_message_utils.py index 075b98833..700b87ea4 100644 --- a/tests/core/test_proto_message_utils.py +++ b/tests/core/test_proto_message_utils.py @@ -53,7 +53,8 @@ def test_replace_guid_elt(speos: Speos): assert proto_message_utils._finder_by_key(dict_var=src_t_dict, key="intensity") == [] assert proto_message_utils._finder_by_key(dict_var=src_t_dict, key="spectrum") == [] - # Replace guid elements for this message, by adding new key to the dict with value corresponding to database item + # Replace guid elements for this message, + # by adding new key to the dict with value corresponding to database item proto_message_utils._replace_guid_elt(speos_client=speos.client, json_dict=src_t_dict) # Check that the new keys are added @@ -81,9 +82,12 @@ def test_replace_guid_elt_ignore_simple_key(speos: Speos): # Check that the new keys are not already present before calling _replace_guid_elt assert proto_message_utils._finder_by_key(dict_var=src_t_dict, key="intensity") == [] - # Replace guid elements for this message, by adding new key to the dict with value corresponding to database item + # Replace guid elements for this message, + # by adding new key to the dict with value corresponding to database item proto_message_utils._replace_guid_elt( - speos_client=speos.client, json_dict=src_t_dict, ignore_simple_key="intensity_guid" + speos_client=speos.client, + json_dict=src_t_dict, + ignore_simple_key="intensity_guid", ) # Check that the ignored key is not replaced @@ -113,7 +117,8 @@ def test_replace_guid_elt_list(speos: Speos): assert proto_message_utils._finder_by_key(dict_var=mat_i_dict, key="vop") == [] assert proto_message_utils._finder_by_key(dict_var=mat_i_dict, key="sops") == [] - # Replace guid elements for this message, by adding new key to the dict with value corresponding to database item + # Replace guid elements for this message, + # by adding new key to the dict with value corresponding to database item proto_message_utils._replace_guid_elt(speos_client=speos.client, json_dict=mat_i_dict) # Check that the new keys are added @@ -154,9 +159,11 @@ def test_replace_guid_elt_complex(speos: Speos): assert proto_message_utils._finder_by_key(dict_var=scene_dict, key="vop") == [] assert proto_message_utils._finder_by_key(dict_var=scene_dict, key="sops") == [] - # To avoid a lot of replacements (part -> bodies -> faces), part_guid is set as ignore_simple_key + # To avoid a lot of replacements (part->bodies->faces), part_guid is set as ignore_simple_key proto_message_utils._replace_guid_elt( - speos_client=speos.client, json_dict=scene_dict, ignore_simple_key="part_guid" + speos_client=speos.client, + json_dict=scene_dict, + ignore_simple_key="part_guid", ) # Check that the part_guid was correctly ignored @@ -234,7 +241,11 @@ def test__value_finder_key_endswith(speos: Speos): dict_var=src_i_dict, key="_properties" ): keys.append(key) - assert keys == ["surface_properties", "exitance_constant_properties", "intensity_properties"] + assert keys == [ + "surface_properties", + "exitance_constant_properties", + "intensity_properties", + ] def test_replace_properties(speos: Speos): @@ -280,7 +291,9 @@ def test_finder_by_key(speos: Speos): ) scene_dict = p._to_dict() - + expected_res = ( + ".sources[.name='Dom Source 2 (0) in SOURCE2'].source.surface.radiant_flux.radiant_value" + ) # key at root res = proto_message_utils._finder_by_key(dict_var=scene_dict, key="part_guid") assert len(res) == 1 @@ -289,29 +302,31 @@ def test_finder_by_key(speos: Speos): # key in a list elt (with name property : sources[.name='XXXX']) res = proto_message_utils._finder_by_key(dict_var=scene_dict, key="radiant_value") assert len(res) == 2 - assert ( - res[0][0] - == ".sources[.name='Dom Source 2 (0) in SOURCE2'].source.surface.radiant_flux.radiant_value" + expected_res = ( + ".sources[.name='Dom Source 2 (0) in SOURCE2'].source.surface.radiant_flux.radiant_value" ) + assert res[0][0] == expected_res assert res[0][1] == 6.590041607465698 - assert ( - res[1][0] - == ".sources[.name='Surface Source (0) in SOURCE1'].source.surface.radiant_flux.radiant_value" + expected_res = ( + ".sources[.name='Surface Source (0) in SOURCE1'].source.surface.radiant_flux.radiant_value" ) + assert res[1][0] == expected_res assert res[1][1] == 9.290411220389682 # key in a list (without name property : geo_paths[0]) res = proto_message_utils._finder_by_key(dict_var=scene_dict, key="geo_path") assert len(res) == 2 - assert ( - res[0][0] - == ".sources[.name='Dom Source 2 (0) in SOURCE2'].source.surface.exitance_constant.geo_paths[0].geo_path" + expected_res = ( + ".sources[.name='Dom Source 2 (0) in SOURCE2']" + ".source.surface.exitance_constant.geo_paths[0].geo_path" ) + assert res[0][0] == expected_res assert res[0][1] == "Solid Body in SOURCE2:2920204960/Face in SOURCE2:222" - assert ( - res[1][0] - == ".sources[.name='Surface Source (0) in SOURCE1'].source.surface.exitance_constant.geo_paths[0].geo_path" + expected_res = ( + ".sources[.name='Surface Source (0) in SOURCE1']" + ".source.surface.exitance_constant.geo_paths[0].geo_path" ) + assert res[1][0] == expected_res assert res[1][1] == "Solid Body in SOURCE1:2494956811/Face in SOURCE1:187" diff --git a/tests/core/test_sensor.py b/tests/core/test_sensor.py index ef5245c1a..a41bfea89 100644 --- a/tests/core/test_sensor.py +++ b/tests/core/test_sensor.py @@ -28,7 +28,11 @@ from ansys.api.speos.sensor.v1 import camera_sensor_pb2 from ansys.speos.core import GeoRef, Project, Speos, sensor -from ansys.speos.core.sensor import SensorCamera, SensorIrradiance, SensorRadiance +from ansys.speos.core.sensor import ( + SensorCamera, + SensorIrradiance, + SensorRadiance, +) from tests.conftest import test_path @@ -41,73 +45,44 @@ def test_create_camera_sensor(speos: Speos): sensor1.commit() assert sensor1.sensor_template_link is not None assert sensor1.sensor_template_link.get().HasField("camera_sensor_template") - assert sensor1.sensor_template_link.get().camera_sensor_template.focal_length == 5.0 - assert sensor1.sensor_template_link.get().camera_sensor_template.imager_distance == 10 - assert sensor1.sensor_template_link.get().camera_sensor_template.distortion_file_uri == "" - assert sensor1.sensor_template_link.get().camera_sensor_template.f_number == 20 - assert sensor1.sensor_template_link.get().camera_sensor_template.horz_pixel == 640 - assert sensor1.sensor_template_link.get().camera_sensor_template.vert_pixel == 480 - assert sensor1.sensor_template_link.get().camera_sensor_template.width == 5.0 - assert sensor1.sensor_template_link.get().camera_sensor_template.height == 5.0 - assert sensor1.sensor_template_link.get().camera_sensor_template.HasField( - "sensor_mode_photometric" - ) - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.acquisition_integration - == 0.01 - ) - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.acquisition_lag_time - == 0.0 - ) - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.transmittance_file_uri - == "" - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.focal_length == 5.0 + assert camera_sensor_template.imager_distance == 10 + assert camera_sensor_template.distortion_file_uri == "" + assert camera_sensor_template.f_number == 20 + assert camera_sensor_template.horz_pixel == 640 + assert camera_sensor_template.vert_pixel == 480 + assert camera_sensor_template.width == 5.0 + assert camera_sensor_template.height == 5.0 + assert camera_sensor_template.HasField("sensor_mode_photometric") + assert camera_sensor_template.sensor_mode_photometric.acquisition_integration == 0.01 + assert camera_sensor_template.sensor_mode_photometric.acquisition_lag_time == 0.0 + assert camera_sensor_template.sensor_mode_photometric.transmittance_file_uri == "" assert math.isclose( - a=sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.gamma_correction, + a=camera_sensor_template.sensor_mode_photometric.gamma_correction, b=2.2, rel_tol=1.192092896e-07, ) assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.png_bits + camera_sensor_template.sensor_mode_photometric.png_bits == camera_sensor_pb2.EnumSensorCameraPNGBits.PNG_16 ) + assert camera_sensor_template.sensor_mode_photometric.HasField("wavelengths_range") + assert camera_sensor_template.sensor_mode_photometric.wavelengths_range.w_start == 400 + assert camera_sensor_template.sensor_mode_photometric.wavelengths_range.w_end == 700 + assert camera_sensor_template.sensor_mode_photometric.wavelengths_range.w_sampling == 13 + assert camera_sensor_template.sensor_mode_photometric.HasField("color_mode_color") assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.HasField( - "wavelengths_range" - ) - ) - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.wavelengths_range.w_start - == 400 - ) - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.wavelengths_range.w_end - == 700 - ) - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.wavelengths_range.w_sampling - == 13 - ) - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.HasField( - "color_mode_color" - ) + camera_sensor_template.sensor_mode_photometric.color_mode_color.red_spectrum_file_uri == "" ) assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.color_mode_color.red_spectrum_file_uri + camera_sensor_template.sensor_mode_photometric.color_mode_color.green_spectrum_file_uri == "" ) assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.color_mode_color.green_spectrum_file_uri - == "" - ) - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.color_mode_color.blue_spectrum_file_uri - == "" + camera_sensor_template.sensor_mode_photometric.color_mode_color.blue_spectrum_file_uri == "" ) - assert sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.color_mode_color.HasField( + assert camera_sensor_template.sensor_mode_photometric.color_mode_color.HasField( "balance_mode_none" ) assert sensor1._sensor_instance.camera_properties.axis_system == [ @@ -130,116 +105,118 @@ def test_create_camera_sensor(speos: Speos): # focal_length sensor1.set_focal_length(value=5.5) sensor1.commit() - assert sensor1.sensor_template_link.get().camera_sensor_template.focal_length == 5.5 + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.focal_length == 5.5 # imager_distance sensor1.set_imager_distance(value=10.5) sensor1.commit() - assert sensor1.sensor_template_link.get().camera_sensor_template.imager_distance == 10.5 + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.imager_distance == 10.5 # f_number sensor1.set_f_number(value=20.5) sensor1.commit() - assert sensor1.sensor_template_link.get().camera_sensor_template.f_number == 20.5 + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.f_number == 20.5 # distortion_file_uri sensor1.set_distortion_file_uri( uri=str(Path(test_path) / "CameraInputFiles" / "CameraDistortion_130deg.OPTDistortion") ) sensor1.commit() - assert sensor1.sensor_template_link.get().camera_sensor_template.distortion_file_uri != "" + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.distortion_file_uri != "" # horz_pixel sensor1.set_horz_pixel(value=680) sensor1.commit() - assert sensor1.sensor_template_link.get().camera_sensor_template.horz_pixel == 680 + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.horz_pixel == 680 # vert_pixel sensor1.set_vert_pixel(value=500) sensor1.commit() - assert sensor1.sensor_template_link.get().camera_sensor_template.vert_pixel == 500 + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.vert_pixel == 500 # width sensor1.set_width(value=5.5) sensor1.commit() - assert sensor1.sensor_template_link.get().camera_sensor_template.width == 5.5 + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.width == 5.5 # height sensor1.set_height(value=5.3) sensor1.commit() - assert sensor1.sensor_template_link.get().camera_sensor_template.height == 5.3 + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.height == 5.3 # sensor_mode_geometric sensor1.set_mode_geometric() sensor1.commit() - assert sensor1.sensor_template_link.get().camera_sensor_template.HasField( - "sensor_mode_geometric" - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.HasField("sensor_mode_geometric") # sensor_mode_photometric sensor1.set_mode_photometric() sensor1.commit() - assert sensor1.sensor_template_link.get().camera_sensor_template.HasField( - "sensor_mode_photometric" - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.HasField("sensor_mode_photometric") # acquisition_integration sensor1.set_mode_photometric().set_acquisition_integration(value=0.03) sensor1.commit() - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.acquisition_integration - == 0.03 - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.sensor_mode_photometric.acquisition_integration == 0.03 # acquisition_lag_time sensor1.set_mode_photometric().set_acquisition_lag_time(value=0.1) sensor1.commit() - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.acquisition_lag_time - == 0.1 - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.sensor_mode_photometric.acquisition_lag_time == 0.1 # transmittance_file_uri sensor1.set_mode_photometric().set_transmittance_file_uri( uri=str(Path(test_path) / "CameraInputFiles" / "CameraTransmittance.spectrum") ) sensor1.commit() - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.transmittance_file_uri - != "" - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.sensor_mode_photometric.transmittance_file_uri != "" # gamma_correction sensor1.set_mode_photometric().set_gamma_correction(value=2.5) sensor1.commit() - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.gamma_correction - == 2.5 - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.sensor_mode_photometric.gamma_correction == 2.5 # png_bits sensor1.set_mode_photometric().set_png_bits_08() sensor1.commit() + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.png_bits + camera_sensor_template.sensor_mode_photometric.png_bits == camera_sensor_pb2.EnumSensorCameraPNGBits.PNG_08 ) sensor1.set_mode_photometric().set_png_bits_10() sensor1.commit() + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.png_bits + camera_sensor_template.sensor_mode_photometric.png_bits == camera_sensor_pb2.EnumSensorCameraPNGBits.PNG_10 ) sensor1.set_mode_photometric().set_png_bits_12() sensor1.commit() + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.png_bits + camera_sensor_template.sensor_mode_photometric.png_bits == camera_sensor_pb2.EnumSensorCameraPNGBits.PNG_12 ) sensor1.set_mode_photometric().set_png_bits_16() sensor1.commit() + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.png_bits + camera_sensor_template.sensor_mode_photometric.png_bits == camera_sensor_pb2.EnumSensorCameraPNGBits.PNG_16 ) @@ -250,29 +227,24 @@ def test_create_camera_sensor(speos: Speos): ) ) sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.HasField("color_mode_monochromatic") assert mode_photometric.color_mode_monochromatic.spectrum_file_uri != "" # color_mode_color sensor1.set_mode_photometric().set_mode_color() sensor1.commit() - assert ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric.HasField( - "color_mode_color" - ) - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + assert camera_sensor_template.sensor_mode_photometric.HasField("color_mode_color") # red_spectrum_file_uri sensor1.set_mode_photometric().set_mode_color().set_red_spectrum_file_uri( uri=str(Path(test_path) / "CameraInputFiles" / "CameraSensitivityRed.spectrum") ) sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.color_mode_color.red_spectrum_file_uri.endswith( "CameraSensitivityRed.spectrum" ) @@ -282,9 +254,8 @@ def test_create_camera_sensor(speos: Speos): uri=str(Path(test_path) / "CameraInputFiles" / "CameraSensitivityGreen.spectrum") ) sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.color_mode_color.green_spectrum_file_uri.endswith( "CameraSensitivityGreen.spectrum" ) @@ -294,9 +265,8 @@ def test_create_camera_sensor(speos: Speos): uri=str(Path(test_path) / "CameraInputFiles" / "CameraSensitivityBlue.spectrum") ) sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.color_mode_color.blue_spectrum_file_uri.endswith( "CameraSensitivityBlue.spectrum" ) @@ -304,17 +274,15 @@ def test_create_camera_sensor(speos: Speos): # balance_mode_greyworld sensor1.set_mode_photometric().set_mode_color().set_balance_mode_grey_world() sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.color_mode_color.HasField("balance_mode_greyworld") # balance_mode_userwhite sensor1.set_mode_photometric().set_mode_color().set_balance_mode_user_white() sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.color_mode_color.HasField("balance_mode_userwhite") assert mode_photometric.color_mode_color.balance_mode_userwhite.red_gain == 1 assert mode_photometric.color_mode_color.balance_mode_userwhite.green_gain == 1 @@ -324,9 +292,8 @@ def test_create_camera_sensor(speos: Speos): value=2 ).set_green_gain(value=3).set_blue_gain(value=4) sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.color_mode_color.balance_mode_userwhite.red_gain == 2 assert mode_photometric.color_mode_color.balance_mode_userwhite.green_gain == 3 assert mode_photometric.color_mode_color.balance_mode_userwhite.blue_gain == 4 @@ -334,9 +301,8 @@ def test_create_camera_sensor(speos: Speos): # balance_mode_display sensor1.set_mode_photometric().set_mode_color().set_balance_mode_display_primaries() sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.color_mode_color.HasField("balance_mode_display") assert mode_photometric.color_mode_color.balance_mode_display.red_display_file_uri == "" assert mode_photometric.color_mode_color.balance_mode_display.green_display_file_uri == "" @@ -350,9 +316,8 @@ def test_create_camera_sensor(speos: Speos): uri=str(Path(test_path) / "CameraInputFiles" / "CameraSensitivityBlue.spectrum") ) sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.color_mode_color.balance_mode_display.red_display_file_uri.endswith( "CameraSensitivityRed.spectrum" ) @@ -366,9 +331,8 @@ def test_create_camera_sensor(speos: Speos): # balance_mode_none sensor1.set_mode_photometric().set_mode_color().set_balance_mode_none() sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.color_mode_color.HasField("balance_mode_none") # wavelengths_range @@ -376,9 +340,8 @@ def test_create_camera_sensor(speos: Speos): value=750 ).set_sampling(value=15) sensor1.commit() - mode_photometric = ( - sensor1.sensor_template_link.get().camera_sensor_template.sensor_mode_photometric - ) + camera_sensor_template = sensor1.sensor_template_link.get().camera_sensor_template + mode_photometric = camera_sensor_template.sensor_mode_photometric assert mode_photometric.wavelengths_range.w_start == 430 assert mode_photometric.wavelengths_range.w_end == 750 assert mode_photometric.wavelengths_range.w_sampling == 15 @@ -432,25 +395,19 @@ def test_create_irradiance_sensor(speos: Speos): sensor1.commit() assert sensor1.sensor_template_link is not None assert sensor1.sensor_template_link.get().HasField("irradiance_sensor_template") - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField( - "sensor_type_photometric" - ) - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField( - "illuminance_type_planar" - ) - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField("dimensions") - assert sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.x_start == -50.0 - assert sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.x_end == 50.0 - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.x_sampling == 100 - ) - assert sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.y_start == -50.0 - assert sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.y_end == 50.0 - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.y_sampling == 100 - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.HasField("sensor_type_photometric") + assert sensor_template.HasField("illuminance_type_planar") + assert sensor_template.HasField("dimensions") + assert sensor_template.dimensions.x_start == -50.0 + assert sensor_template.dimensions.x_end == 50.0 + assert sensor_template.dimensions.x_sampling == 100 + assert sensor_template.dimensions.y_start == -50.0 + assert sensor_template.dimensions.y_end == 50.0 + assert sensor_template.dimensions.y_sampling == 100 assert sensor1._sensor_instance.HasField("irradiance_properties") - assert sensor1._sensor_instance.irradiance_properties.axis_system == [ + irra_properties = sensor1._sensor_instance.irradiance_properties + assert irra_properties.axis_system == [ 0, 0, 0, @@ -464,163 +421,114 @@ def test_create_irradiance_sensor(speos: Speos): 0, 1, ] - assert sensor1._sensor_instance.irradiance_properties.HasField("layer_type_none") - assert ( - sensor1._sensor_instance.irradiance_properties.ray_file_type - == sensor1._sensor_instance.EnumRayFileType.RayFileNone - ) - assert sensor1._sensor_instance.irradiance_properties.integration_direction == [] + assert irra_properties.HasField("layer_type_none") + assert irra_properties.ray_file_type == sensor1._sensor_instance.EnumRayFileType.RayFileNone + assert irra_properties.integration_direction == [] # sensor_type_colorimetric # default wavelengths range sensor1.set_type_colorimetric() sensor1.commit() - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField( - "sensor_type_colorimetric" - ) - assert sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_colorimetric.HasField( - "wavelengths_range" - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_colorimetric.wavelengths_range.w_start - == 400 - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_colorimetric.wavelengths_range.w_end - == 700 - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_colorimetric.wavelengths_range.w_sampling - == 13 - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.HasField("sensor_type_colorimetric") + assert sensor_template.sensor_type_colorimetric.HasField("wavelengths_range") + assert sensor_template.sensor_type_colorimetric.wavelengths_range.w_start == 400 + assert sensor_template.sensor_type_colorimetric.wavelengths_range.w_end == 700 + assert sensor_template.sensor_type_colorimetric.wavelengths_range.w_sampling == 13 # chosen wavelengths range sensor1.set_type_colorimetric().set_wavelengths_range().set_start(value=450).set_end( value=800 ).set_sampling(value=15) sensor1.commit() - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_colorimetric.wavelengths_range.w_start - == 450 - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_colorimetric.wavelengths_range.w_end - == 800 - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_colorimetric.wavelengths_range.w_sampling - == 15 - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.sensor_type_colorimetric.wavelengths_range.w_start == 450 + assert sensor_template.sensor_type_colorimetric.wavelengths_range.w_end == 800 + assert sensor_template.sensor_type_colorimetric.wavelengths_range.w_sampling == 15 # sensor_type_radiometric sensor1.set_type_radiometric() sensor1.commit() - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField( - "sensor_type_radiometric" - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.HasField("sensor_type_radiometric") # sensor_type_spectral # default wavelengths range sensor1.set_type_spectral() sensor1.commit() - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField( - "sensor_type_spectral" - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_spectral.HasField( - "wavelengths_range" - ) - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_spectral.wavelengths_range.w_start - == 400 - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_spectral.wavelengths_range.w_end - == 700 - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_spectral.wavelengths_range.w_sampling - == 13 - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.HasField("sensor_type_spectral") + assert sensor_template.sensor_type_spectral.HasField("wavelengths_range") + assert sensor_template.sensor_type_spectral.wavelengths_range.w_start == 400 + assert sensor_template.sensor_type_spectral.wavelengths_range.w_end == 700 + assert sensor_template.sensor_type_spectral.wavelengths_range.w_sampling == 13 # chosen wavelengths range sensor1.set_type_spectral().set_wavelengths_range().set_start(value=450).set_end( value=800 ).set_sampling(value=15) sensor1.commit() - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_spectral.wavelengths_range.w_start - == 450 - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_spectral.wavelengths_range.w_end - == 800 - ) - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.sensor_type_spectral.wavelengths_range.w_sampling - == 15 - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.sensor_type_spectral.wavelengths_range.w_start == 450 + assert sensor_template.sensor_type_spectral.wavelengths_range.w_end == 800 + assert sensor_template.sensor_type_spectral.wavelengths_range.w_sampling == 15 # sensor_type_photometric sensor1.set_type_photometric() sensor1.commit() - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField( - "sensor_type_photometric" - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.HasField("sensor_type_photometric") # illuminance_type_radial sensor1.set_illuminance_type_radial() sensor1.commit() - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField( - "illuminance_type_radial" - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.HasField("illuminance_type_radial") # illuminance_type_hemispherical - bug to be fixed - # sensor1.set_irradiance().set_illuminance_type_hemispherical() + # sensor1.set_illuminance_type_hemispherical() # sensor1.commit() - # assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField("illuminance_type_hemispherical") + # sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + # assert sensor_template.HasField("illuminance_type_hemispherical") # illuminance_type_cylindrical sensor1.set_illuminance_type_cylindrical() sensor1.commit() - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField( - "illuminance_type_cylindrical" - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.HasField("illuminance_type_cylindrical") # illuminance_type_semi_cylindrical - bug to be fixed - # sensor1.set_irradiance().set_illuminance_type_semi_cylindrical(integration_direction=[1,0,0]) + # sensor1.set_illuminance_type_semi_cylindrical(integration_direction=[1,0,0]) # sensor1.commit() - # assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField("illuminance_type_semi_cylindrical") + # sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + # assert sensor_template.HasField("illuminance_type_semi_cylindrical") # illuminance_type_planar sensor1.set_illuminance_type_planar(integration_direction=[0, 0, -1]) sensor1.commit() - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField( - "illuminance_type_planar" - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.HasField("illuminance_type_planar") sensor1.set_illuminance_type_planar(integration_direction=None) # cancel integration direction - assert sensor1._sensor_instance.irradiance_properties.integration_direction == [] + assert irra_properties.integration_direction == [] # dimensions sensor1.set_dimensions().set_x_start(value=-10).set_x_end(value=10).set_x_sampling( value=60 ).set_y_start(value=-20).set_y_end(value=20).set_y_sampling(value=120) sensor1.commit() - assert sensor1.sensor_template_link.get().irradiance_sensor_template.HasField("dimensions") - assert sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.x_start == -10.0 - assert sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.x_end == 10.0 - assert sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.x_sampling == 60 - assert sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.y_start == -20.0 - assert sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.y_end == 20.0 - assert ( - sensor1.sensor_template_link.get().irradiance_sensor_template.dimensions.y_sampling == 120 - ) + sensor_template = sensor1.sensor_template_link.get().irradiance_sensor_template + assert sensor_template.HasField("dimensions") + assert sensor_template.dimensions.x_start == -10.0 + assert sensor_template.dimensions.x_end == 10.0 + assert sensor_template.dimensions.x_sampling == 60 + assert sensor_template.dimensions.y_start == -20.0 + assert sensor_template.dimensions.y_end == 20.0 + assert sensor_template.dimensions.y_sampling == 120 # properties # axis_system sensor1.set_axis_system([10, 50, 20, 1, 0, 0, 0, 1, 0, 0, 0, 1]) sensor1.commit() - assert sensor1._sensor_instance.irradiance_properties.axis_system == [ + assert irra_properties.axis_system == [ 10, 50, 20, @@ -638,43 +546,34 @@ def test_create_irradiance_sensor(speos: Speos): # ray_file_type sensor1.set_ray_file_type_classic() sensor1.commit() - assert ( - sensor1._sensor_instance.irradiance_properties.ray_file_type - == sensor1._sensor_instance.EnumRayFileType.RayFileClassic - ) + assert irra_properties.ray_file_type == sensor1._sensor_instance.EnumRayFileType.RayFileClassic sensor1.set_ray_file_type_polarization() sensor1.commit() assert ( - sensor1._sensor_instance.irradiance_properties.ray_file_type + irra_properties.ray_file_type == sensor1._sensor_instance.EnumRayFileType.RayFilePolarization ) sensor1.set_ray_file_type_tm25() sensor1.commit() - assert ( - sensor1._sensor_instance.irradiance_properties.ray_file_type - == sensor1._sensor_instance.EnumRayFileType.RayFileTM25 - ) + assert irra_properties.ray_file_type == sensor1._sensor_instance.EnumRayFileType.RayFileTM25 sensor1.set_ray_file_type_tm25_no_polarization() sensor1.commit() assert ( - sensor1._sensor_instance.irradiance_properties.ray_file_type + irra_properties.ray_file_type == sensor1._sensor_instance.EnumRayFileType.RayFileTM25NoPolarization ) sensor1.set_ray_file_type_none() sensor1.commit() - assert ( - sensor1._sensor_instance.irradiance_properties.ray_file_type - == sensor1._sensor_instance.EnumRayFileType.RayFileNone - ) + assert irra_properties.ray_file_type == sensor1._sensor_instance.EnumRayFileType.RayFileNone # layer_type_source sensor1.set_layer_type_source() sensor1.commit() - assert sensor1._sensor_instance.irradiance_properties.HasField("layer_type_source") + assert irra_properties.HasField("layer_type_source") # layer_type_face sensor1.set_layer_type_face().set_sca_filtering_mode_intersected_one_time().set_layers( @@ -692,24 +591,16 @@ def test_create_irradiance_sensor(speos: Speos): ] ) sensor1.commit() - assert sensor1._sensor_instance.irradiance_properties.HasField("layer_type_face") - assert ( - sensor1._sensor_instance.irradiance_properties.layer_type_face.sca_filtering_mode - == sensor1._sensor_instance.irradiance_properties.layer_type_face.EnumSCAFilteringType.IntersectedOneTime - ) - assert len(sensor1._sensor_instance.irradiance_properties.layer_type_face.layers) == 2 + assert irra_properties.HasField("layer_type_face") assert ( - sensor1._sensor_instance.irradiance_properties.layer_type_face.layers[0].name == "Layer.1" + irra_properties.layer_type_face.sca_filtering_mode + == irra_properties.layer_type_face.EnumSCAFilteringType.IntersectedOneTime ) - assert sensor1._sensor_instance.irradiance_properties.layer_type_face.layers[ - 0 - ].geometries.geo_paths == ["TheBodyB"] - assert ( - sensor1._sensor_instance.irradiance_properties.layer_type_face.layers[1].name == "Layer.2" - ) - assert sensor1._sensor_instance.irradiance_properties.layer_type_face.layers[ - 1 - ].geometries.geo_paths == [ + assert len(irra_properties.layer_type_face.layers) == 2 + assert irra_properties.layer_type_face.layers[0].name == "Layer.1" + assert irra_properties.layer_type_face.layers[0].geometries.geo_paths == ["TheBodyB"] + assert irra_properties.layer_type_face.layers[1].name == "Layer.2" + assert irra_properties.layer_type_face.layers[1].geometries.geo_paths == [ "TheBodyC/TheFaceC1", "TheBodyC/TheFaceC2", ] @@ -717,8 +608,8 @@ def test_create_irradiance_sensor(speos: Speos): sensor1.set_layer_type_face().set_sca_filtering_mode_last_impact() sensor1.commit() assert ( - sensor1._sensor_instance.irradiance_properties.layer_type_face.sca_filtering_mode - == sensor1._sensor_instance.irradiance_properties.layer_type_face.EnumSCAFilteringType.LastImpact + irra_properties.layer_type_face.sca_filtering_mode + == irra_properties.layer_type_face.EnumSCAFilteringType.LastImpact ) # layer_type_sequence @@ -726,38 +617,35 @@ def test_create_irradiance_sensor(speos: Speos): value=5 ).set_define_sequence_per_faces() sensor1.commit() - assert sensor1._sensor_instance.irradiance_properties.HasField("layer_type_sequence") - assert ( - sensor1._sensor_instance.irradiance_properties.layer_type_sequence.maximum_nb_of_sequence - == 5 - ) + assert irra_properties.HasField("layer_type_sequence") + assert irra_properties.layer_type_sequence.maximum_nb_of_sequence == 5 assert ( - sensor1._sensor_instance.irradiance_properties.layer_type_sequence.define_sequence_per - == sensor1._sensor_instance.irradiance_properties.layer_type_sequence.EnumSequenceType.Faces + irra_properties.layer_type_sequence.define_sequence_per + == irra_properties.layer_type_sequence.EnumSequenceType.Faces ) sensor1.set_layer_type_sequence().set_define_sequence_per_geometries() sensor1.commit() assert ( - sensor1._sensor_instance.irradiance_properties.layer_type_sequence.define_sequence_per - == sensor1._sensor_instance.irradiance_properties.layer_type_sequence.EnumSequenceType.Geometries + irra_properties.layer_type_sequence.define_sequence_per + == irra_properties.layer_type_sequence.EnumSequenceType.Geometries ) # layer_type_polarization sensor1.set_layer_type_polarization() sensor1.commit() - assert sensor1._sensor_instance.irradiance_properties.HasField("layer_type_polarization") + assert irra_properties.HasField("layer_type_polarization") # layer_type_incidence_angle sensor1.set_layer_type_incidence_angle().set_sampling(value=8) sensor1.commit() - assert sensor1._sensor_instance.irradiance_properties.HasField("layer_type_incidence_angle") - assert sensor1._sensor_instance.irradiance_properties.layer_type_incidence_angle.sampling == 8 + assert irra_properties.HasField("layer_type_incidence_angle") + assert irra_properties.layer_type_incidence_angle.sampling == 8 # layer_type_none sensor1.set_layer_type_none() sensor1.commit() - assert sensor1._sensor_instance.irradiance_properties.HasField("layer_type_none") + assert irra_properties.HasField("layer_type_none") # output_face_geometries sensor1.set_output_face_geometries( @@ -766,7 +654,7 @@ def test_create_irradiance_sensor(speos: Speos): GeoRef.from_native_link(geopath="TheBodyB/TheFaceB2"), ] ) - assert sensor1._sensor_instance.irradiance_properties.output_face_geometries.geo_paths == [ + assert irra_properties.output_face_geometries.geo_paths == [ "TheBodyB/TheFaceB1", "TheBodyB/TheFaceB2", ] @@ -798,7 +686,8 @@ def test_create_radiance_sensor(speos: Speos): assert sensor1.sensor_template_link.get().radiance_sensor_template.dimensions.y_end == 50.0 assert sensor1.sensor_template_link.get().radiance_sensor_template.dimensions.y_sampling == 100 assert sensor1._sensor_instance.HasField("radiance_properties") - assert sensor1._sensor_instance.radiance_properties.axis_system == [ + radiance_properties = sensor1._sensor_instance.radiance_properties + assert radiance_properties.axis_system == [ 0, 0, 0, @@ -812,8 +701,8 @@ def test_create_radiance_sensor(speos: Speos): 0, 1, ] - assert sensor1._sensor_instance.radiance_properties.HasField("layer_type_none") - assert sensor1._sensor_instance.radiance_properties.observer_point == [] + assert radiance_properties.HasField("layer_type_none") + assert radiance_properties.observer_point == [] # sensor_type_radiometric sensor1.set_type_radiometric() @@ -898,7 +787,7 @@ def test_create_radiance_sensor(speos: Speos): # axis_system sensor1.set_axis_system([10, 50, 20, 1, 0, 0, 0, 1, 0, 0, 0, 1]) sensor1.commit() - assert sensor1._sensor_instance.radiance_properties.axis_system == [ + assert radiance_properties.axis_system == [ 10, 50, 20, @@ -916,16 +805,20 @@ def test_create_radiance_sensor(speos: Speos): # observer_point sensor1.set_observer_point([20, 30, 50]) sensor1.commit() - assert sensor1._sensor_instance.radiance_properties.observer_point == [20, 30, 50] + assert radiance_properties.observer_point == [ + 20, + 30, + 50, + ] sensor1.set_observer_point(value=None) # cancel observer point chosen previously sensor1.commit() - assert sensor1._sensor_instance.radiance_properties.observer_point == [] + assert radiance_properties.observer_point == [] # layer_type_source sensor1.set_layer_type_source() sensor1.commit() - assert sensor1._sensor_instance.radiance_properties.HasField("layer_type_source") + assert radiance_properties.HasField("layer_type_source") # layer_type_face sensor1.set_layer_type_face().set_sca_filtering_mode_intersected_one_time().set_layers( @@ -943,20 +836,16 @@ def test_create_radiance_sensor(speos: Speos): ] ) sensor1.commit() - assert sensor1._sensor_instance.radiance_properties.HasField("layer_type_face") + assert radiance_properties.HasField("layer_type_face") assert ( - sensor1._sensor_instance.radiance_properties.layer_type_face.sca_filtering_mode - == sensor1._sensor_instance.radiance_properties.layer_type_face.EnumSCAFilteringType.IntersectedOneTime + radiance_properties.layer_type_face.sca_filtering_mode + == radiance_properties.layer_type_face.EnumSCAFilteringType.IntersectedOneTime ) - assert len(sensor1._sensor_instance.radiance_properties.layer_type_face.layers) == 2 - assert sensor1._sensor_instance.radiance_properties.layer_type_face.layers[0].name == "Layer.1" - assert sensor1._sensor_instance.radiance_properties.layer_type_face.layers[ - 0 - ].geometries.geo_paths == ["TheBodyB"] - assert sensor1._sensor_instance.radiance_properties.layer_type_face.layers[1].name == "Layer.2" - assert sensor1._sensor_instance.radiance_properties.layer_type_face.layers[ - 1 - ].geometries.geo_paths == [ + assert len(radiance_properties.layer_type_face.layers) == 2 + assert radiance_properties.layer_type_face.layers[0].name == "Layer.1" + assert radiance_properties.layer_type_face.layers[0].geometries.geo_paths == ["TheBodyB"] + assert radiance_properties.layer_type_face.layers[1].name == "Layer.2" + assert radiance_properties.layer_type_face.layers[1].geometries.geo_paths == [ "TheBodyC/TheFaceC1", "TheBodyC/TheFaceC2", ] @@ -965,40 +854,38 @@ def test_create_radiance_sensor(speos: Speos): sensor1.set_layer_type_face().set_sca_filtering_mode_last_impact() sensor1.commit() assert ( - sensor1._sensor_instance.radiance_properties.layer_type_face.sca_filtering_mode - == sensor1._sensor_instance.radiance_properties.layer_type_face.EnumSCAFilteringType.LastImpact + radiance_properties.layer_type_face.sca_filtering_mode + == radiance_properties.layer_type_face.EnumSCAFilteringType.LastImpact ) # layer_type_face -> clear layers list sensor1.set_layer_type_face().set_layers(values=[]) # clear layers list sensor1.commit() - assert len(sensor1._sensor_instance.radiance_properties.layer_type_face.layers) == 0 + assert len(radiance_properties.layer_type_face.layers) == 0 # layer_type_sequence sensor1.set_layer_type_sequence().set_maximum_nb_of_sequence( value=5 ).set_define_sequence_per_faces() sensor1.commit() - assert sensor1._sensor_instance.radiance_properties.HasField("layer_type_sequence") - assert ( - sensor1._sensor_instance.radiance_properties.layer_type_sequence.maximum_nb_of_sequence == 5 - ) + assert radiance_properties.HasField("layer_type_sequence") + assert radiance_properties.layer_type_sequence.maximum_nb_of_sequence == 5 assert ( - sensor1._sensor_instance.radiance_properties.layer_type_sequence.define_sequence_per - == sensor1._sensor_instance.radiance_properties.layer_type_sequence.EnumSequenceType.Faces + radiance_properties.layer_type_sequence.define_sequence_per + == radiance_properties.layer_type_sequence.EnumSequenceType.Faces ) sensor1.set_layer_type_sequence().set_define_sequence_per_geometries() sensor1.commit() assert ( - sensor1._sensor_instance.radiance_properties.layer_type_sequence.define_sequence_per - == sensor1._sensor_instance.radiance_properties.layer_type_sequence.EnumSequenceType.Geometries + radiance_properties.layer_type_sequence.define_sequence_per + == radiance_properties.layer_type_sequence.EnumSequenceType.Geometries ) # layer_type_none sensor1.set_layer_type_none() sensor1.commit() - assert sensor1._sensor_instance.radiance_properties.HasField("layer_type_none") + assert radiance_properties.HasField("layer_type_none") def test_commit_sensor(speos: Speos): @@ -1146,7 +1033,7 @@ def test_irradiance_modify_after_reset(speos: Speos): sensor1.set_type_spectral() sensor1.set_layer_type_sequence() sensor1.commit() - assert type(sensor1) == SensorIrradiance + assert isinstance(sensor1, SensorIrradiance) # Ask for reset sensor1.reset() @@ -1221,7 +1108,7 @@ def test_radiance_modify_after_reset(speos: Speos): # Create + commit sensor1 = p.create_sensor(name="Sensor.1", feature_type=SensorRadiance) - assert type(sensor1) == SensorRadiance + assert isinstance(sensor1, SensorRadiance) sensor1.set_type_colorimetric() sensor1.set_layer_type_sequence() sensor1.commit() @@ -1299,7 +1186,7 @@ def test_camera_modify_after_reset(speos: Speos): # Create + commit sensor1 = p.create_sensor(name="Sensor.1", feature_type=SensorCamera) - assert type(sensor1) == SensorCamera + assert isinstance(sensor1, SensorCamera) sensor1.set_mode_photometric().set_mode_color().set_balance_mode_user_white() sensor1.set_mode_photometric().set_layer_type_source() sensor1.commit() diff --git a/tests/core/test_simulation.py b/tests/core/test_simulation.py index b7c2d85d0..81aefe0cf 100644 --- a/tests/core/test_simulation.py +++ b/tests/core/test_simulation.py @@ -28,7 +28,11 @@ from ansys.api.speos.simulation.v1 import simulation_template_pb2 from ansys.speos.core import GeoRef, Project, Speos from ansys.speos.core.sensor import SensorIrradiance -from ansys.speos.core.simulation import SimulationDirect, SimulationInteractive, SimulationInverse +from ansys.speos.core.simulation import ( + SimulationDirect, + SimulationInteractive, + SimulationInverse, +) from ansys.speos.core.source import SourceLuminaire from tests.conftest import test_path @@ -42,75 +46,60 @@ def test_create_direct(speos: Speos): sim1 = SimulationDirect(project=p, name="Direct.1") # sim1.set_direct() # do not commit to avoid issues about No sensor in simulation assert sim1._simulation_template.HasField("direct_mc_simulation_template") - assert sim1._simulation_template.direct_mc_simulation_template.geom_distance_tolerance == 0.01 - assert sim1._simulation_template.direct_mc_simulation_template.max_impact == 100 - assert ( - sim1._simulation_template.direct_mc_simulation_template.colorimetric_standard - == simulation_template_pb2.CIE_1931 - ) - assert sim1._simulation_template.direct_mc_simulation_template.dispersion == True - assert ( - sim1._simulation_template.direct_mc_simulation_template.fast_transmission_gathering == False - ) - assert sim1._simulation_template.direct_mc_simulation_template.ambient_material_uri == "" - assert sim1._simulation_template.direct_mc_simulation_template.HasField("weight") - assert ( - sim1._simulation_template.direct_mc_simulation_template.weight.minimum_energy_percentage - == 0.005 - ) + simulation_template = sim1._simulation_template.direct_mc_simulation_template + assert simulation_template.geom_distance_tolerance == 0.01 + assert simulation_template.max_impact == 100 + assert simulation_template.colorimetric_standard == simulation_template_pb2.CIE_1931 + assert simulation_template.dispersion is True + assert simulation_template.fast_transmission_gathering is False + assert simulation_template.ambient_material_uri == "" + assert simulation_template.HasField("weight") + assert simulation_template.weight.minimum_energy_percentage == 0.005 assert len(sim1._simulation_instance.sensor_paths) == 0 assert len(sim1._simulation_instance.source_paths) == 0 assert len(sim1._simulation_instance.geometries.geo_paths) == 0 assert sim1._job.HasField("direct_mc_simulation_properties") assert sim1._job.direct_mc_simulation_properties.HasField("stop_condition_rays_number") assert sim1._job.direct_mc_simulation_properties.stop_condition_rays_number == 200000 - assert sim1._job.direct_mc_simulation_properties.HasField("stop_condition_duration") == False + assert sim1._job.direct_mc_simulation_properties.HasField("stop_condition_duration") is False assert sim1._job.direct_mc_simulation_properties.automatic_save_frequency == 1800 # Change value # geom_distance_tolerance sim1.set_geom_distance_tolerance(value=0.1) - assert sim1._simulation_template.direct_mc_simulation_template.geom_distance_tolerance == 0.1 + assert simulation_template.geom_distance_tolerance == 0.1 # max_impact sim1.set_max_impact(value=200) - assert sim1._simulation_template.direct_mc_simulation_template.max_impact == 200 + assert simulation_template.max_impact == 200 # weight - minimum_energy_percentage sim1.set_weight_none() - assert sim1._simulation_template.direct_mc_simulation_template.HasField("weight") == False + assert simulation_template.HasField("weight") is False sim1.set_weight().set_minimum_energy_percentage(value=0.7) - assert sim1._simulation_template.direct_mc_simulation_template.HasField("weight") - assert ( - sim1._simulation_template.direct_mc_simulation_template.weight.minimum_energy_percentage - == 0.7 - ) + assert simulation_template.HasField("weight") + assert simulation_template.weight.minimum_energy_percentage == 0.7 # colorimetric_standard sim1.set_colorimetric_standard_CIE_1964() - assert ( - sim1._simulation_template.direct_mc_simulation_template.colorimetric_standard - == simulation_template_pb2.CIE_1964 - ) + assert simulation_template.colorimetric_standard == simulation_template_pb2.CIE_1964 # dispersion sim1.set_dispersion(value=False) - assert sim1._simulation_template.direct_mc_simulation_template.dispersion == False + assert simulation_template.dispersion is False # fast_transmission_gathering - # sim1.set_direct().set_fast_transmission_gathering(value=True) - # assert sim1._simulation_template.direct_mc_simulation_template.fast_transmission_gathering == True + # sim1.set_fast_transmission_gathering(value=True) + # assert simulation_template.fast_transmission_gathering is True # ambient_material_uri sim1.set_ambient_material_file_uri(uri=str(Path(test_path) / "AIR.material")) - assert sim1._simulation_template.direct_mc_simulation_template.ambient_material_uri.endswith( - "AIR.material" - ) + assert simulation_template.ambient_material_uri.endswith("AIR.material") # stop_condition_rays_number sim1.set_stop_condition_rays_number(value=None) - assert sim1._job.direct_mc_simulation_properties.HasField("stop_condition_rays_number") == False + assert sim1._job.direct_mc_simulation_properties.HasField("stop_condition_rays_number") is False # stop_condition_duration sim1.set_stop_condition_duration(value=600) @@ -151,29 +140,18 @@ def test_create_inverse(speos: Speos): sim1 = SimulationInverse(project=p, name="Inverse.1") # sim1.set_inverse() # do not commit to avoid issues about No sensor in simulation assert sim1._simulation_template.HasField("inverse_mc_simulation_template") - assert sim1._simulation_template.inverse_mc_simulation_template.geom_distance_tolerance == 0.01 - assert sim1._simulation_template.inverse_mc_simulation_template.max_impact == 100 - assert ( - sim1._simulation_template.inverse_mc_simulation_template.colorimetric_standard - == simulation_template_pb2.CIE_1931 - ) - assert sim1._simulation_template.inverse_mc_simulation_template.HasField("weight") - assert ( - sim1._simulation_template.inverse_mc_simulation_template.weight.minimum_energy_percentage - == 0.005 - ) - assert sim1._simulation_template.inverse_mc_simulation_template.dispersion == False - assert sim1._simulation_template.inverse_mc_simulation_template.splitting == False - assert ( - sim1._simulation_template.inverse_mc_simulation_template.number_of_gathering_rays_per_source - == 1 - ) - assert sim1._simulation_template.inverse_mc_simulation_template.maximum_gathering_error == 0 - assert ( - sim1._simulation_template.inverse_mc_simulation_template.fast_transmission_gathering - == False - ) - assert sim1._simulation_template.inverse_mc_simulation_template.ambient_material_uri == "" + simulation_template = sim1._simulation_template.inverse_mc_simulation_template + assert simulation_template.geom_distance_tolerance == 0.01 + assert simulation_template.max_impact == 100 + assert simulation_template.colorimetric_standard == simulation_template_pb2.CIE_1931 + assert simulation_template.HasField("weight") + assert simulation_template.weight.minimum_energy_percentage == 0.005 + assert simulation_template.dispersion is False + assert simulation_template.splitting is False + assert simulation_template.number_of_gathering_rays_per_source == 1 + assert simulation_template.maximum_gathering_error == 0 + assert simulation_template.fast_transmission_gathering is False + assert simulation_template.ambient_material_uri == "" assert len(sim1._simulation_instance.sensor_paths) == 0 assert len(sim1._simulation_instance.source_paths) == 0 assert len(sim1._simulation_instance.geometries.geo_paths) == 0 @@ -183,73 +161,62 @@ def test_create_inverse(speos: Speos): sim1._job.inverse_mc_simulation_properties.optimized_propagation_none.stop_condition_passes_number == 5 ) - assert sim1._job.inverse_mc_simulation_properties.HasField("stop_condition_duration") == False + assert sim1._job.inverse_mc_simulation_properties.HasField("stop_condition_duration") is False assert sim1._job.inverse_mc_simulation_properties.automatic_save_frequency == 1800 # Change value # geom_distance_tolerance sim1.set_geom_distance_tolerance(value=0.1) - assert sim1._simulation_template.inverse_mc_simulation_template.geom_distance_tolerance == 0.1 + assert simulation_template.geom_distance_tolerance == 0.1 # max_impact sim1.set_max_impact(value=200) - assert sim1._simulation_template.inverse_mc_simulation_template.max_impact == 200 + assert simulation_template.max_impact == 200 # weight - minimum_energy_percentage sim1.set_weight_none() - assert sim1._simulation_template.inverse_mc_simulation_template.HasField("weight") == False + assert simulation_template.HasField("weight") is False sim1.set_weight().set_minimum_energy_percentage(value=0.7) - assert sim1._simulation_template.inverse_mc_simulation_template.HasField("weight") - assert ( - sim1._simulation_template.inverse_mc_simulation_template.weight.minimum_energy_percentage - == 0.7 - ) + assert simulation_template.HasField("weight") + assert simulation_template.weight.minimum_energy_percentage == 0.7 # colorimetric_standard sim1.set_colorimetric_standard_CIE_1964() - assert ( - sim1._simulation_template.inverse_mc_simulation_template.colorimetric_standard - == simulation_template_pb2.CIE_1964 - ) + assert simulation_template.colorimetric_standard == simulation_template_pb2.CIE_1964 # dispersion sim1.set_dispersion(value=True) - assert sim1._simulation_template.inverse_mc_simulation_template.dispersion == True + assert simulation_template.dispersion is True # splitting sim1.set_splitting(value=True) - assert sim1._simulation_template.inverse_mc_simulation_template.splitting == True + assert simulation_template.splitting is True # number_of_gathering_rays_per_source sim1.set_number_of_gathering_rays_per_source(value=2) - assert ( - sim1._simulation_template.inverse_mc_simulation_template.number_of_gathering_rays_per_source - == 2 - ) + assert simulation_template.number_of_gathering_rays_per_source == 2 # maximum_gathering_error sim1.set_maximum_gathering_error(value=3) - assert sim1._simulation_template.inverse_mc_simulation_template.maximum_gathering_error == 3 + assert simulation_template.maximum_gathering_error == 3 # fast_transmission_gathering - # sim1.set_inverse().set_fast_transmission_gathering(value=True) - # assert sim1._simulation_template.inverse_mc_simulation_template.fast_transmission_gathering == True + # sim1.set_fast_transmission_gathering(value=True) + # assert simulation_template.fast_transmission_gathering == True # ambient_material_uri sim1.set_ambient_material_file_uri(uri=str(Path(test_path) / "AIR.material")) - assert sim1._simulation_template.inverse_mc_simulation_template.ambient_material_uri.endswith( - "AIR.material" - ) + assert simulation_template.ambient_material_uri.endswith("AIR.material") # stop_condition_passes_number sim1.set_stop_condition_passes_number(value=None) - assert sim1._job.inverse_mc_simulation_properties.HasField("optimized_propagation_none") == True + assert sim1._job.inverse_mc_simulation_properties.HasField("optimized_propagation_none") is True assert ( sim1._job.inverse_mc_simulation_properties.optimized_propagation_none.HasField( "stop_condition_passes_number" ) - == False + is False ) # stop_condition_duration @@ -308,8 +275,8 @@ def test_create_interactive(speos: Speos): assert len(sim1._simulation_instance.geometries.geo_paths) == 0 assert sim1._job.HasField("interactive_simulation_properties") assert len(sim1._job.interactive_simulation_properties.rays_number_per_sources) == 0 - assert sim1._job.interactive_simulation_properties.light_expert == False - assert sim1._job.interactive_simulation_properties.impact_report == False + assert sim1._job.interactive_simulation_properties.light_expert is False + assert sim1._job.interactive_simulation_properties.impact_report is False # Change value # geom_distance_tolerance @@ -322,7 +289,7 @@ def test_create_interactive(speos: Speos): # weight - minimum_energy_percentage sim1.set_weight_none() - assert sim1._simulation_template.interactive_simulation_template.HasField("weight") == False + assert sim1._simulation_template.interactive_simulation_template.HasField("weight") is False sim1.set_weight().set_minimum_energy_percentage(value=0.7) assert sim1._simulation_template.interactive_simulation_template.HasField("weight") @@ -368,11 +335,11 @@ def test_create_interactive(speos: Speos): # light_expert sim1.set_light_expert(value=True) - assert sim1._job.interactive_simulation_properties.light_expert == True + assert sim1._job.interactive_simulation_properties.light_expert is True # impact_report sim1.set_impact_report(value=True) - assert sim1._job.interactive_simulation_properties.impact_report == True + assert sim1._job.interactive_simulation_properties.impact_report is True # sensor_paths sim1.set_sensor_paths(sensor_paths=["sensor.1", "sensor.2"]) @@ -670,9 +637,9 @@ def test_interactive_modify_after_reset(speos: Speos): assert sim1._simulation_instance.sensor_paths == ["NewSensor"] # Job Props - assert sim1._job.interactive_simulation_properties.light_expert == False + assert sim1._job.interactive_simulation_properties.light_expert is False sim1.set_light_expert(value=True) - assert sim1._job.interactive_simulation_properties.light_expert == True + assert sim1._job.interactive_simulation_properties.light_expert is True p.delete() diff --git a/tests/core/test_source.py b/tests/core/test_source.py index 49cf7803e..f6b1f7738 100644 --- a/tests/core/test_source.py +++ b/tests/core/test_source.py @@ -26,7 +26,11 @@ from pathlib import Path from ansys.speos.core import GeoRef, Project, Speos -from ansys.speos.core.source import SourceLuminaire, SourceRayFile, SourceSurface +from ansys.speos.core.source import ( + SourceLuminaire, + SourceRayFile, + SourceSurface, +) from tests.conftest import test_path @@ -160,13 +164,10 @@ def test_create_surface_source(speos: Speos): intensity = speos.client[source1.source_template_link.get().surface.intensity_guid] assert intensity.get().HasField("library") assert source1._source_instance.HasField("surface_properties") - assert source1._source_instance.surface_properties.HasField("intensity_properties") - assert source1._source_instance.surface_properties.intensity_properties.HasField( - "library_properties" - ) - assert source1._source_instance.surface_properties.intensity_properties.library_properties.HasField( - "axis_system" - ) + surface_properties = source1._source_instance.surface_properties + assert surface_properties.HasField("intensity_properties") + assert surface_properties.intensity_properties.HasField("library_properties") + assert surface_properties.intensity_properties.library_properties.HasField("axis_system") # luminous_flux source1.set_flux_luminous(value=630) @@ -198,8 +199,8 @@ def test_create_surface_source(speos: Speos): assert source1.source_template_link.get().surface.HasField("exitance_variable") assert source1.source_template_link.get().surface.exitance_variable.exitance_xmp_file_uri != "" assert source1.source_template_link.get().surface.HasField("spectrum_from_xmp_file") - assert source1._source_instance.surface_properties.HasField("exitance_variable_properties") - assert source1._source_instance.surface_properties.exitance_variable_properties.axis_plane == [ + assert surface_properties.HasField("exitance_variable_properties") + assert surface_properties.exitance_variable_properties.axis_plane == [ 0, 0, 0, @@ -215,8 +216,8 @@ def test_create_surface_source(speos: Speos): # exitance_variable axis_plane source1.set_exitance_variable().set_axis_plane(axis_plane=[10, 10, 15, 1, 0, 0, 0, 1, 0]) source1.commit() - assert source1._source_instance.surface_properties.HasField("exitance_variable_properties") - assert source1._source_instance.surface_properties.exitance_variable_properties.axis_plane == [ + assert surface_properties.HasField("exitance_variable_properties") + assert surface_properties.exitance_variable_properties.axis_plane == [ 10, 10, 15, @@ -236,41 +237,17 @@ def test_create_surface_source(speos: Speos): ] ).set_spectrum().set_blackbody() source1.commit() - assert source1._source_instance.surface_properties.HasField("exitance_constant_properties") - assert ( - len(source1._source_instance.surface_properties.exitance_constant_properties.geo_paths) == 2 - ) - assert ( - source1._source_instance.surface_properties.exitance_constant_properties.geo_paths[ - 0 - ].geo_path - == "BodyB/FaceB1" - ) - assert ( - source1._source_instance.surface_properties.exitance_constant_properties.geo_paths[ - 0 - ].reverse_normal - == False - ) - assert ( - source1._source_instance.surface_properties.exitance_constant_properties.geo_paths[ - 1 - ].geo_path - == "BodyB/FaceB2" - ) - assert ( - source1._source_instance.surface_properties.exitance_constant_properties.geo_paths[ - 1 - ].reverse_normal - == True - ) + assert surface_properties.HasField("exitance_constant_properties") + assert len(surface_properties.exitance_constant_properties.geo_paths) == 2 + assert surface_properties.exitance_constant_properties.geo_paths[0].geo_path == "BodyB/FaceB1" + assert surface_properties.exitance_constant_properties.geo_paths[0].reverse_normal is False + assert surface_properties.exitance_constant_properties.geo_paths[1].geo_path == "BodyB/FaceB2" + assert surface_properties.exitance_constant_properties.geo_paths[1].reverse_normal is True source1.set_exitance_constant(geometries=[]) # clear geometries source1.commit() - assert source1._source_instance.surface_properties.HasField("exitance_constant_properties") - assert ( - len(source1._source_instance.surface_properties.exitance_constant_properties.geo_paths) == 0 - ) + assert surface_properties.HasField("exitance_constant_properties") + assert len(surface_properties.exitance_constant_properties.geo_paths) == 0 source1.delete() @@ -376,7 +353,7 @@ def test_create_rayfile_source(speos: Speos): source1.set_exit_geometries() # use default [] to reset exit geometries source1.commit() - assert source1._source_instance.rayfile_properties.HasField("exit_geometries") == False + assert source1._source_instance.rayfile_properties.HasField("exit_geometries") is False source1.delete() diff --git a/tests/helper.py b/tests/helper.py index e9cd73fee..426e0fdeb 100644 --- a/tests/helper.py +++ b/tests/helper.py @@ -23,7 +23,8 @@ """Unit Test Helper Module. This module offers some helpers that can be useful in PySpeos unit tests. -For example a method to check file existence depending on if the file is in the docker container or in local. +For example a method to check file existence depending on if the file is in the docker container or +in local. """ import os @@ -130,7 +131,8 @@ def remove_file(path): """ if config.get("SpeosServerOnDocker"): subprocess.call( - "docker exec " + config.get("SpeosContainerName") + ' rm -rf "' + path + '"', shell=True + "docker exec " + config.get("SpeosContainerName") + ' rm -rf "' + path + '"', + shell=True, ) else: Path(path).unlink() diff --git a/tests/kernel/test_geometry.py b/tests/kernel/test_geometry.py index 2bb94b622..6221a068c 100644 --- a/tests/kernel/test_geometry.py +++ b/tests/kernel/test_geometry.py @@ -207,7 +207,10 @@ def test_part(speos: Speos): message=create_face_rectangle( name="face_0", description="face_0 for body_0", - metadata={"key_0": "val_0", "key_1": "val_1"}, + metadata={ + "key_0": "val_0", + "key_1": "val_1", + }, ) ).key ], diff --git a/tests/kernel/test_logging.py b/tests/kernel/test_logging.py index c3baff3aa..213780932 100644 --- a/tests/kernel/test_logging.py +++ b/tests/kernel/test_logging.py @@ -37,7 +37,13 @@ # - capfd: for testing console printing. # - caplog: for testing logging printing. -LOG_LEVELS = {"CRITICAL": 50, "ERROR": 40, "WARNING": 30, "INFO": 20, "DEBUG": 10} +LOG_LEVELS = { + "CRITICAL": 50, + "ERROR": 40, + "WARNING": 30, + "INFO": 20, + "DEBUG": 10, +} def test_stdout_reading(capfd: pytest.CaptureFixture): @@ -55,7 +61,7 @@ def test_stdout_reading(capfd: pytest.CaptureFixture): def test_only_logger(caplog: pytest.LogCaptureFixture): - """Test for checking that the logging capabilities are working fine in the Python version installed. + """Test for checking that the logging capabilities are working fine. Parameters ---------- @@ -76,7 +82,10 @@ def test_global_logger_exist(): def test_global_logger_has_handlers(): - """Test for checking that the general Logger has file_handlers and sdtout file_handlers implemented.""" + """Test for checking that the general Logger has file_handlers \ + + and sdtout file_handlers implemented. + """ assert hasattr(LOG, "file_handler") assert hasattr(LOG, "std_out_handler") assert LOG.logger.hasHandlers @@ -100,7 +109,11 @@ def test_global_logger_logging(caplog: pytest.LogCaptureFixture): msg = f"This is an {each_log_name} message." LOG.logger.log(each_log_number, msg) # Make sure we are using the right logger, the right level and message. - assert caplog.record_tuples[-1] == ("pyspeos_global", each_log_number, msg) + assert caplog.record_tuples[-1] == ( + "pyspeos_global", + each_log_number, + msg, + ) # Set back to default level == ERROR LOG.logger.setLevel("ERROR") @@ -108,7 +121,10 @@ def test_global_logger_logging(caplog: pytest.LogCaptureFixture): def test_global_logger_level_mode(): - """Checking that the Logger levels are stored as integer values and that the default value (unless changed) is ERROR.""" + """Checking that the Logger levels are stored as integer values \ + + and that the default value (unless changed) is ERROR. + """ assert isinstance(LOG.logger.level, int) assert LOG.logger.level == logger.ERROR @@ -145,7 +161,9 @@ def test_global_logger_exception_handling(caplog: pytest.LogCaptureFixture): ], ) def test_global_logger_debug_levels(level: int, caplog: pytest.LogCaptureFixture): - """Testing for all the possible logging level that the output is recorded properly for each type of msg. + """Testing for all the possible logging level that the output is recorded properly. + + Test is done for each type of msg. Parameters ---------- @@ -203,7 +221,7 @@ def test_global_logger_format(fake_record: Callable): def test_global_methods(caplog: pytest.LogCaptureFixture): - """Testing global logger methods for printing out different log messages, from DEBUG to CRITICAL. + """Testing global logger methods for printing out different log messages. Parameters ---------- diff --git a/tests/kernel/test_scene.py b/tests/kernel/test_scene.py index 8fd3128f1..d710ce899 100644 --- a/tests/kernel/test_scene.py +++ b/tests/kernel/test_scene.py @@ -237,7 +237,9 @@ def create_basic_scene(speos: Speos) -> SceneLink: # Create a vop template opaque_t = speos.client.vop_templates().create( message=ProtoVOPTemplate( - name="opaque", description="opaque vop template", opaque=ProtoVOPTemplate.Opaque() + name="opaque", + description="opaque vop template", + opaque=ProtoVOPTemplate.Opaque(), ) ) @@ -281,7 +283,10 @@ def create_basic_scene(speos: Speos) -> SceneLink: surface_properties=ProtoScene.SourceInstance.SurfaceProperties( exitance_constant_properties=ProtoScene.SourceInstance.SurfaceProperties.ExitanceConstantProperties( geo_paths=[ - ProtoScene.GeoPath(geo_path="BodySource:1", reverse_normal=False) + ProtoScene.GeoPath( + geo_path="BodySource:1", + reverse_normal=False, + ) ] ) ), @@ -303,14 +308,24 @@ def create_basic_scene(speos: Speos) -> SceneLink: ProtoScene.SimulationInstance( name="direct_simu.1", simulation_guid=direct_t.key, - source_paths=["luminaire_AA.1", "luminaire_AA.2", "surface_with_blackbody.1"], - sensor_paths=["irradiance_photometric.1", "irradiance_colorimetric.1"], + source_paths=[ + "luminaire_AA.1", + "luminaire_AA.2", + "surface_with_blackbody.1", + ], + sensor_paths=[ + "irradiance_photometric.1", + "irradiance_colorimetric.1", + ], ), ProtoScene.SimulationInstance( name="direct_simu.2", simulation_guid=direct_t.key, source_paths=["surface_with_blackbody.1"], - sensor_paths=["irradiance_photometric.1", "irradiance_colorimetric.1"], + sensor_paths=[ + "irradiance_photometric.1", + "irradiance_colorimetric.1", + ], ), ProtoScene.SimulationInstance( name="inverse_simu.1", @@ -321,8 +336,15 @@ def create_basic_scene(speos: Speos) -> SceneLink: ProtoScene.SimulationInstance( name="interactive_simu.1", simulation_guid=interactive_t.key, - source_paths=["luminaire_AA.1", "luminaire_AA.2", "surface_with_blackbody.1"], - sensor_paths=["irradiance_photometric.1", "irradiance_colorimetric.1"], + source_paths=[ + "luminaire_AA.1", + "luminaire_AA.2", + "surface_with_blackbody.1", + ], + sensor_paths=[ + "irradiance_photometric.1", + "irradiance_colorimetric.1", + ], ), ], ) @@ -451,7 +473,10 @@ def create_body_box( base0.extend(base[6:9]) # y_vect face0 = face_stub.create( message=create_face_rectangle( - name="Face:" + str(idx_face), base=base0, x_size=x_size, y_size=y_size + name="Face:" + str(idx_face), + base=base0, + x_size=x_size, + y_size=y_size, ) ) @@ -461,7 +486,10 @@ def create_body_box( base1.extend(base[6:9]) face1 = face_stub.create( message=create_face_rectangle( - name="Face:" + str(idx_face + 1), base=base1, x_size=x_size, y_size=y_size + name="Face:" + str(idx_face + 1), + base=base1, + x_size=x_size, + y_size=y_size, ) ) @@ -471,7 +499,10 @@ def create_body_box( base2.extend(base[6:9]) face2 = face_stub.create( message=create_face_rectangle( - name="Face:" + str(idx_face + 2), base=base2, x_size=z_size, y_size=y_size + name="Face:" + str(idx_face + 2), + base=base2, + x_size=z_size, + y_size=y_size, ) ) @@ -481,7 +512,10 @@ def create_body_box( base3.extend(base[6:9]) face3 = face_stub.create( message=create_face_rectangle( - name="Face:" + str(idx_face + 3), base=base3, x_size=z_size, y_size=y_size + name="Face:" + str(idx_face + 3), + base=base3, + x_size=z_size, + y_size=y_size, ) ) @@ -491,7 +525,10 @@ def create_body_box( base4.extend(base[9:]) face4 = face_stub.create( message=create_face_rectangle( - name="Face:" + str(idx_face + 4), base=base4, x_size=x_size, y_size=z_size + name="Face:" + str(idx_face + 4), + base=base4, + x_size=x_size, + y_size=z_size, ) ) @@ -501,7 +538,10 @@ def create_body_box( base5.extend(np.multiply(-1, base[9:])) face5 = face_stub.create( message=create_face_rectangle( - name="Face:" + str(idx_face + 5), base=base5, x_size=x_size, y_size=z_size + name="Face:" + str(idx_face + 5), + base=base5, + x_size=x_size, + y_size=z_size, ) ) @@ -591,7 +631,8 @@ def test_scene_actions_get_source_ray_paths(speos: Speos): blackbody_2856 = speos.client.spectrums().create( message=ProtoSpectrum( - name="Blackbody_2856", blackbody=ProtoSpectrum.BlackBody(temperature=2856) + name="Blackbody_2856", + blackbody=ProtoSpectrum.BlackBody(temperature=2856), ) ) luminaire_t = speos.client.source_templates().create( diff --git a/tests/kernel/test_sensor_template.py b/tests/kernel/test_sensor_template.py index 9cdaf32c7..46a62c3ca 100644 --- a/tests/kernel/test_sensor_template.py +++ b/tests/kernel/test_sensor_template.py @@ -25,7 +25,11 @@ import os from pathlib import Path -from ansys.api.speos.sensor.v1 import camera_sensor_pb2, common_pb2, irradiance_sensor_pb2 +from ansys.api.speos.sensor.v1 import ( + camera_sensor_pb2, + common_pb2, + irradiance_sensor_pb2, +) from ansys.speos.core.kernel.sensor_template import ProtoSensorTemplate from ansys.speos.core.speos import Speos from tests.conftest import test_path diff --git a/tests/kernel/test_vop_template.py b/tests/kernel/test_vop_template.py index 17edd7423..7e8cea7f6 100644 --- a/tests/kernel/test_vop_template.py +++ b/tests/kernel/test_vop_template.py @@ -43,7 +43,9 @@ def test_vop_template(speos: Speos): # Opaque vop_t_opaque = vop_t_db.create( ProtoVOPTemplate( - name="opaque_0", description="Opaque vop template", opaque=ProtoVOPTemplate.Opaque() + name="opaque_0", + description="Opaque vop template", + opaque=ProtoVOPTemplate.Opaque(), ) ) assert vop_t_opaque.key != "" diff --git a/tests/stubs/test_anisotropic_bsdf.py b/tests/stubs/test_anisotropic_bsdf.py index ece09dcdd..f22163c85 100644 --- a/tests/stubs/test_anisotropic_bsdf.py +++ b/tests/stubs/test_anisotropic_bsdf.py @@ -175,7 +175,10 @@ def compareAnisotropicBsdf(bsdf1, bsdf2): return False for p in range(len(incidence_diag1.phi_samples)): - if not approx_cmp(incidence_diag1.phi_samples[p], incidence_diag2.phi_samples[p]): + if not approx_cmp( + incidence_diag1.phi_samples[p], + incidence_diag2.phi_samples[p], + ): return False if len(incidence_diag1.theta_samples) != len(incidence_diag2.theta_samples): @@ -192,7 +195,10 @@ def compareAnisotropicBsdf(bsdf1, bsdf2): return False # transmission spectrum - if not approx_cmp(bsdf1.transmission.spectrum_incidence, bsdf2.transmission.spectrum_incidence): + if not approx_cmp( + bsdf1.transmission.spectrum_incidence, + bsdf2.transmission.spectrum_incidence, + ): return False if bsdf1.transmission.spectrum_anisotropy != bsdf2.transmission.spectrum_anisotropy: @@ -234,7 +240,10 @@ def compareAnisotropicBsdf(bsdf1, bsdf2): return False for p in range(len(incidence_diag1.phi_samples)): - if not approx_cmp(incidence_diag1.phi_samples[p], incidence_diag2.phi_samples[p]): + if not approx_cmp( + incidence_diag1.phi_samples[p], + incidence_diag2.phi_samples[p], + ): return False if len(incidence_diag1.theta_samples) != len(incidence_diag2.theta_samples): @@ -242,7 +251,8 @@ def compareAnisotropicBsdf(bsdf1, bsdf2): for t in range(len(incidence_diag1.theta_samples)): if not approx_cmp( - incidence_diag1.theta_samples[t], incidence_diag2.theta_samples[t] + incidence_diag1.theta_samples[t], + incidence_diag2.theta_samples[t], ): return False for p in range(len(incidence_diag1.phi_samples)): @@ -400,9 +410,9 @@ def test_grpc_anisotropic_bsdf(speos: Speos): assert compareEnhancementData(rc, rc2) # white specular enabling and disabling - l = anisotropic_bsdf__v1__pb2.Wavelength() - l.wavelength = 632.0 - stub.EnableWhiteSpecular(l) + wl = anisotropic_bsdf__v1__pb2.Wavelength() + wl.wavelength = 632.0 + stub.EnableWhiteSpecular(wl) stub.DisableWhiteSpecular(Empty()) # spectrum imports diff --git a/tests/stubs/test_eulumdat_file.py b/tests/stubs/test_eulumdat_file.py index ca18c7dcc..e192fb4b2 100644 --- a/tests/stubs/test_eulumdat_file.py +++ b/tests/stubs/test_eulumdat_file.py @@ -26,7 +26,10 @@ import os from pathlib import Path -from ansys.api.speos.intensity_distributions.v1 import eulumdat_pb2, eulumdat_pb2_grpc +from ansys.api.speos.intensity_distributions.v1 import ( + eulumdat_pb2, + eulumdat_pb2_grpc, +) from ansys.speos.core.speos import Speos from tests.conftest import test_path import tests.helper as helper diff --git a/tests/stubs/test_lpf_file_reader.py b/tests/stubs/test_lpf_file_reader.py index cbbc0fa8d..1c75da244 100644 --- a/tests/stubs/test_lpf_file_reader.py +++ b/tests/stubs/test_lpf_file_reader.py @@ -49,7 +49,7 @@ def test_lpf_file_reader_mono_v2_DirectSimu(speos: Speos): assert nb_of_traces == 24817 assert res_information.nb_of_xmps == 3 assert ( - res_information.has_sensor_contributions == False + res_information.has_sensor_contributions is False ) # No contributions stored in Direct simu assert len(res_information.sensor_names) == 3 assert res_information.sensor_names[0] == "Irradiance Sensor (0)" @@ -105,7 +105,7 @@ def test_lpf_file_reader_mono_v2_InverseSimu(speos: Speos): nb_of_traces = res_information.nb_of_traces assert nb_of_traces == 21044 assert res_information.nb_of_xmps == 1 - assert res_information.has_sensor_contributions == True # contributions stored in Inverse simu + assert res_information.has_sensor_contributions is True # contributions stored in Inverse simu assert len(res_information.sensor_names) == 1 assert res_information.sensor_names[0] == "Camera_Perfect_Lens_System_V2:3" @@ -233,7 +233,7 @@ def test_lpf_file_reader_mono_v2_DirectSimu_with_file_transfer(speos: Speos): assert nb_of_traces == 24817 assert res_information.nb_of_xmps == 3 assert ( - res_information.has_sensor_contributions == False + res_information.has_sensor_contributions is False ) # No contributions stored in Direct simu assert len(res_information.sensor_names) == 3 assert res_information.sensor_names[0] == "Irradiance Sensor (0)" diff --git a/tests/stubs/test_xmp_intensity_file.py b/tests/stubs/test_xmp_intensity_file.py index 71d2faa25..9234e50cd 100644 --- a/tests/stubs/test_xmp_intensity_file.py +++ b/tests/stubs/test_xmp_intensity_file.py @@ -67,23 +67,23 @@ def create_xmp_intensity(): xmp.base_data.rad_angular_resolution_radius = 0 # fill layer data - for l in range(xmp.base_data.layer_nb): + for layer_index in range(xmp.base_data.layer_nb): xmp.base_data.layer.add() - xmp.base_data.layer[l].layer_name = "0" + str(l) - xmp.base_data.layer[l].initial_source_power = 1000 - xmp.base_data.layer[l].initial_source_power_watt = 1000 - xmp.base_data.layer[l].initial_source_power_lumen = 1000 + xmp.base_data.layer[layer_index].layer_name = "0" + str(layer_index) + xmp.base_data.layer[layer_index].initial_source_power = 1000 + xmp.base_data.layer[layer_index].initial_source_power_watt = 1000 + xmp.base_data.layer[layer_index].initial_source_power_lumen = 1000 for s in range(10): - xmp.base_data.layer[l].wavelength.append(400 + 40 * s) - xmp.base_data.layer[l].value.append(0.1) + xmp.base_data.layer[layer_index].wavelength.append(400 + 40 * s) + xmp.base_data.layer[layer_index].value.append(0.1) xmp.value.layer.add() for y in range(xmp.base_data.y_nb): - xmp.value.layer[l].y.add() + xmp.value.layer[layer_index].y.add() for x in range(xmp.base_data.x_nb): if x == y: - xmp.value.layer[l].y[y].x.append(1) + xmp.value.layer[layer_index].y[y].x.append(1) else: - xmp.value.layer[l].y[y].x.append(0) + xmp.value.layer[layer_index].y[y].x.append(0) return xmp @@ -120,27 +120,33 @@ def compare_xmp_intensity_distributions(xmp1, xmp2): return False if xmp1.base_data.precision != xmp2.base_data.precision: return False - for l in range(xmp1.base_data.layer_nb): - if xmp1.base_data.layer[l].layer_name != xmp2.base_data.layer[l].layer_name: + for layer_index in range(xmp1.base_data.layer_nb): + if ( + xmp1.base_data.layer[layer_index].layer_name + != xmp2.base_data.layer[layer_index].layer_name + ): return False if ( - xmp1.base_data.layer[l].initial_source_power - != xmp2.base_data.layer[l].initial_source_power + xmp1.base_data.layer[layer_index].initial_source_power + != xmp2.base_data.layer[layer_index].initial_source_power ): return False if ( - xmp1.base_data.layer[l].initial_source_power_watt - != xmp2.base_data.layer[l].initial_source_power_watt + xmp1.base_data.layer[layer_index].initial_source_power_watt + != xmp2.base_data.layer[layer_index].initial_source_power_watt ): return False if ( - xmp1.base_data.layer[l].initial_source_power_lumen - != xmp2.base_data.layer[l].initial_source_power_lumen + xmp1.base_data.layer[layer_index].initial_source_power_lumen + != xmp2.base_data.layer[layer_index].initial_source_power_lumen ): return False for y in range(xmp1.base_data.y_nb): for x in range(xmp1.base_data.x_nb): - if xmp1.value.layer[l].y[y].x[x] != xmp2.value.layer[l].y[y].x[x]: + if ( + xmp1.value.layer[layer_index].y[y].x[x] + != xmp2.value.layer[layer_index].y[y].x[x] + ): return False return True diff --git a/tests/workflow/test_combine_speos.py b/tests/workflow/test_combine_speos.py index 029a27b80..3cb82f428 100644 --- a/tests/workflow/test_combine_speos.py +++ b/tests/workflow/test_combine_speos.py @@ -26,7 +26,11 @@ from pathlib import Path from ansys.speos.core import OptProp, Part, Project, Speos -from ansys.speos.core.workflow.combine_speos import SpeosFileInstance, combine_speos, insert_speos +from ansys.speos.core.workflow.combine_speos import ( + SpeosFileInstance, + combine_speos, + insert_speos, +) from tests.conftest import test_path @@ -42,11 +46,37 @@ def test_combine_speos(speos: Speos): ), SpeosFileInstance( speos_file=str(Path(test_path) / "BlueCar.speos" / "BlueCar.speos"), - axis_system=[2000, 0, 35000, 0.0, 0.0, -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0], + axis_system=[ + 2000, + 0, + 35000, + 0.0, + 0.0, + -1.0, + -1.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + ], ), SpeosFileInstance( speos_file=str(Path(test_path) / "RedCar.speos" / "RedCar.speos"), - axis_system=[-4000, 0, 48000, 1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0], + axis_system=[ + -4000, + 0, + 48000, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 1.0, + 0.0, + ], ), ], ) @@ -92,11 +122,37 @@ def test_modify_parts_after_combine(speos: Speos): ), SpeosFileInstance( speos_file=str(Path(test_path) / "BlueCar.speos" / "BlueCar.speos"), - axis_system=[2000, 0, 35000, 0.0, 0.0, -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0], + axis_system=[ + 2000, + 0, + 35000, + 0.0, + 0.0, + -1.0, + -1.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + ], ), SpeosFileInstance( speos_file=str(Path(test_path) / "RedCar.speos" / "RedCar.speos"), - axis_system=[-4000, 0, 48000, 1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0], + axis_system=[ + -4000, + 0, + 48000, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 1.0, + 0.0, + ], ), ], ) @@ -147,11 +203,37 @@ def test_insert_speos(speos: Speos): speos_to_insert=[ SpeosFileInstance( speos_file=str(Path(test_path) / "BlueCar.speos" / "BlueCar.speos"), - axis_system=[2000, 0, 35000, 0.0, 0.0, -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0], + axis_system=[ + 2000, + 0, + 35000, + 0.0, + 0.0, + -1.0, + -1.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + ], ), SpeosFileInstance( speos_file=str(Path(test_path) / "RedCar.speos" / "RedCar.speos"), - axis_system=[-4000, 0, 48000, 1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0], + axis_system=[ + -4000, + 0, + 48000, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 1.0, + 0.0, + ], ), ], )