Switch keysight polarization navigator#226
Conversation
Summary of ChangesHello @franz-sweepMe, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a comprehensive driver for the Keysight N778xB Polarization Synthesizer, allowing users to control the instrument's polarization settings through the SweepMe! application. The driver supports two primary modes of operation: setting individual waveplate orientations and retardations, and directly defining the State of Polarization (SOP) using Stokes parameters. Communication with the hardware is facilitated by integrating with the Keysight Polarization Navigator DLL, ensuring robust and precise control over the optical polarization. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request adds two new drivers for Keysight polarization control hardware: one for the N778xB using GPIB, and another for the Polarization Navigator software using a DLL. The review focuses on improving code quality, correctness, and maintainability.
Key feedback points include:
- Critical issues: The Polarization Navigator driver contains a hardcoded DLL path and a duplicated, buggy call to the DLL function. These must be fixed.
- High-severity issues: Error handling is inconsistent, with some errors being printed instead of raised as exceptions. There are also logical inconsistencies in function implementations and resource management issues in a test script.
- Medium-severity issues: There are several opportunities for improvement, such as replacing
printwith proper logging, avoiding broad exception catches, removing hardcoded constants like pi, and cleaning up unused variables and imports.
|
|
||
| from pysweepme.EmptyDeviceClass import EmptyDevice | ||
|
|
||
| DLL_PATH = r"C:\Program Files\Keysight\Polarization Navigator\bin\PolNavClient.dll" |
There was a problem hiding this comment.
The DLL path is hardcoded. This makes the driver not portable and it will fail on any system where the software is installed in a different location. This path should be made configurable, for example by reading it from an environment variable, a configuration file, or passing it as a parameter during initialization.
| send_command( | ||
| target.encode("ascii"), | ||
| command.encode("ascii"), | ||
| response_buffer, | ||
| buffer_size, | ||
| response_len, | ||
| ) | ||
|
|
||
| # Call the DLL function | ||
| result = self.client.PolNavC_SendCommand( | ||
| ctypes.c_char_p(target.encode("ascii")), | ||
| ctypes.c_char_p(command.encode("ascii")), | ||
| response_buffer, | ||
| ctypes.c_int(buffer_size), | ||
| ctypes.byref(response_len), # why is this empty? | ||
| ) |
There was a problem hiding this comment.
The PolNavC_SendCommand function is called twice in a row. The first call uses incorrect arguments (passing response_len directly instead of by reference) and its return value is ignored. The second call is also overly verbose. This appears to be a copy-paste error and can lead to unpredictable behavior. The block should be simplified to a single, correct call to the function.
| send_command( | |
| target.encode("ascii"), | |
| command.encode("ascii"), | |
| response_buffer, | |
| buffer_size, | |
| response_len, | |
| ) | |
| # Call the DLL function | |
| result = self.client.PolNavC_SendCommand( | |
| ctypes.c_char_p(target.encode("ascii")), | |
| ctypes.c_char_p(command.encode("ascii")), | |
| response_buffer, | |
| ctypes.c_int(buffer_size), | |
| ctypes.byref(response_len), # why is this empty? | |
| ) | |
| result = send_command( | |
| target.encode("ascii"), | |
| command.encode("ascii"), | |
| response_buffer, | |
| buffer_size, | |
| ctypes.byref(response_len), | |
| ) |
| """'apply' is used to set the new set value that is always available as 'self.value'.""" | ||
| if self.mode == "SOP": | ||
| try: | ||
| x, y, z = map(float, self.value.split(";")) |
There was a problem hiding this comment.
The code splits the input self.value using a semicolon (;), but the error message on line 129 suggests a comma-separated format ('x,y,z'). This inconsistency will be confusing for users. Please ensure the parsing logic and the error message are aligned. Based on the error message, it seems the value should be split by a comma.
| x, y, z = map(float, self.value.split(";")) | |
| x, y, z = map(float, self.value.split(",")) |
| if result != 0: | ||
| msg = f"PolNav_SendCommand failed with error code: {result}" | ||
| print(msg) | ||
| # raise RuntimeError(msg) |
There was a problem hiding this comment.
Errors from the DLL are printed to the console but the RuntimeError is commented out. This means failures will be silent from the perspective of the calling code, which can lead to unexpected behavior and make debugging difficult. Errors should be raised as exceptions.
| # raise RuntimeError(msg) | |
| raise RuntimeError(msg) |
| def get_sop(self) -> str: | ||
| """Get the current SOP from the Polarization Navigator. | ||
|
|
||
| Sending the 'Get CurrentSOPN' command results in an access error, which is why this function is currently not implemented. | ||
| """ | ||
| self.send_command("Get CurrentSOPN") | ||
| return self.read() |
There was a problem hiding this comment.
The docstring states that this function is not implemented because the underlying command causes an error. However, the function body proceeds to call the failing command. If a function is not meant to be used, it should raise a NotImplementedError to clearly communicate its status to the developer.
| def get_sop(self) -> str: | |
| """Get the current SOP from the Polarization Navigator. | |
| Sending the 'Get CurrentSOPN' command results in an access error, which is why this function is currently not implemented. | |
| """ | |
| self.send_command("Get CurrentSOPN") | |
| return self.read() | |
| def get_sop(self) -> str: | |
| """Get the current SOP from the Polarization Navigator. | |
| Sending the 'Get CurrentSOPN' command results in an access error, which is why this function is currently not implemented. | |
| """ | |
| raise NotImplementedError("Reading SOP is not supported due to a command error.") |
| """Set the orientation and retardation for the 5 waveplates.""" | ||
| try: | ||
| orientations_and_retardations = [float(x.strip()) for x in orientations_and_retardations.split(",")] | ||
| except Exception as e: |
There was a problem hiding this comment.
Catching a broad Exception can hide bugs and make debugging more difficult. It's better to catch more specific exceptions. In this case, float(x.strip()) is most likely to raise a ValueError, so it would be better to catch that specifically.
| except Exception as e: | |
| except ValueError as e: |
| for n in range(5): | ||
| orientation = orientations_and_retardations[n * 2] | ||
| retardation = orientations_and_retardations[n * 2 + 1] | ||
| if not (0 <= orientation <= 2 * 3.14159): |
There was a problem hiding this comment.
Using a hardcoded value for π is less precise and readable than using the constant from the math module. Please import the math module at the top of the file and use math.pi.
import math
# ... later in the code
if not (0 <= orientation <= 2 * math.pi):| if not (0 <= orientation <= 2 * 3.14159): | |
| if not (0 <= orientation <= 2 * 3.141592653589793): |
|
|
||
| configuration += f"{orientation},{retardation}," | ||
|
|
||
| error = self.port.query(f"POLCON:WAVEPL {configuration}") |
There was a problem hiding this comment.
| """Initialize the driver class and the instrument parameters.""" | ||
| super().__init__() | ||
|
|
||
| self.shortname = "N778xB" # short name will be shown in the sequencer |
There was a problem hiding this comment.
The shortname is set to "N778xB", but this driver is for the "Keysight Polarization Navigator" software, as indicated by the file path and class description. This could be confusing. Consider using a more descriptive shortname like "PolNav" to better reflect the instrument being controlled.
| self.shortname = "N778xB" # short name will be shown in the sequencer | |
| self.shortname = "PolNav" # short name will be shown in the sequencer |
| @@ -0,0 +1,22 @@ | |||
| # -*- coding: utf-8 -*- | |||
|
|
|||
| import time | |||
add driver for polarization controll