Source code for qtics.instruments.rohde_schwarz.znb

"""
Controller of the R&S ZNB Vector Network Analyzer.

.. module:: znb.py
.. moduleauthor:: Pietro Campana <p.campana1@campus.unimib.it>
"""

import time
from typing import Tuple

import numpy as np

from qtics import log
from qtics.instruments.base import SCPIInstrument
from qtics.instruments.types import VNA
from qtics.instruments.utils import query_binblock, to_bool
from qtics.transport import Transport

MEAS_TIME_FACTOR = 1.02


[docs]class ZNB(VNA, SCPIInstrument): """R&S ZNB Vector Network Analyzer by Rohde & Schwarz.""" def __init__( self, transport: Transport | str, name: str = "ZNB", max_points: int = 100001, channel: int = 1, **transport_kwargs, ): """Initialize instrument.""" super().__init__(transport, name, **transport_kwargs) self._max_points = max_points self._channel = channel self._active_trace = "Trc1" def _after_connect(self): """Clear, reset and configure a standard measurement.""" self.clear() self.reset() self.setup()
[docs] def setup(self, s_parameter="S21"): """Configure standard measurement.""" # Create default trace if it doesn't exist self.write( f"CALCulate{self._channel}:PARameter:SDEFine '{self._active_trace}', '{s_parameter}'" ) self.write(f"DISPlay:WINDow1:TRACe1:FEED '{self._active_trace}'") self.s_parameter = s_parameter self.activate_trace() self.hold() self.set(yformat="MLOG", ifbw=1000, smoothing=0, averages=1) self.data_format = "REAL,64"
[docs] def write_and_hold(self, cmd: str): """Write command and wait until it has been processed.""" self.write(cmd) self.hold()
[docs] def clear(self): """Clear the error queue and all status registers.""" self.write_and_hold("*CLS")
[docs] def hold(self): """Wait until all commands have been processed.""" complete = self.query("*OPC?") if complete != "1": raise ValueError( f"Operation completed query returned value {complete} instead of 1." )
[docs] def activate_trace(self): """Make active the selected trace.""" self.write(f"CALCulate{self._channel}:PARameter:SELect '{self._active_trace}'")
@property def f_start(self) -> float: """Minimum frequency.""" return float(self.query(f"SENSe{self._channel}:FREQuency:STARt?")) @f_start.setter def f_start(self, f: float): self.write(f"SENSe{self._channel}:FREQuency:STARt {abs(f)}") @property def f_stop(self) -> float: """Maximum frequency.""" return float(self.query(f"SENSe{self._channel}:FREQuency:STOP?")) @f_stop.setter def f_stop(self, f: float): self.write(f"SENSe{self._channel}:FREQuency:STOP {abs(f)}") @property def f_center(self) -> float: """Central frequency.""" return (self.f_start + self.f_stop) / 2 @f_center.setter def f_center(self, f: float): self.write(f"SENSe{self._channel}:FREQuency:CENTer {f}") @property def f_span(self) -> float: """Frequency span.""" return self.f_stop - self.f_start @f_span.setter def f_span(self, f: float): """Frequency span.""" center = self.f_center self.f_start = center - abs(f) / 2 self.f_stop = center + abs(f) / 2 @property def points(self) -> int: """Number of points in sweep.""" return int(self.query(f"SENSe{self._channel}:SWEep:POINts?")) @points.setter def points(self, npoints): npoints = min(abs(npoints), self._max_points) self.write(f"SENSe{self._channel}:SWEep:POINts {npoints}") @property def sweep_time(self) -> float: """Time to complete a measurement sweep.""" return float(self.query(f"SENSe{self._channel}:SWEep:TIME?")) @property def sweep_meas_time(self) -> float: """Time to complete a measurement sweep (same as sweep_time for R&S ZNB).""" return self.sweep_time @property def averages(self) -> int: """The number of sweep averages.""" return int(self.query(f"SENSe{self._channel}:AVERage:COUNt?")) @averages.setter def averages(self, n_avg: int): n_avg = self.validate_range(n_avg, 1, 65536) self.write(f"SENSe{self._channel}:AVERage:COUNt {n_avg}") if n_avg > 1: self.write(f"SENSe{self._channel}:AVERage:STATe ON") else: self.write(f"SENSe{self._channel}:AVERage:STATe OFF") @property def continuous(self) -> bool: """Acquisition mode.""" return to_bool(self.query(f"INITiate{self._channel}:CONTinuous?")) @continuous.setter def continuous(self, status: bool): self.write_and_hold(f"INITiate{self._channel}:CONTinuous {int(status)}") @property def data_format(self) -> str: """Get data format.""" return self.query("FORMat:DATA?") @data_format.setter def data_format(self, form: str): self.validate_opt(form, ("REAL,32", "REAL,64", "ASC,0")) self.write("FORMat:DATA " + form) @property def s_parameter(self) -> str: """The current scattering matrix parameter.""" return self.query( f"CALCulate{self._channel}:PARameter:DEFine? '{self._active_trace}'" ) @s_parameter.setter def s_parameter(self, par="S21"): # Common S-parameters for ZNB valid_spars = ( "S11", "S21", "S12", "S22", "S31", "S32", "S33", "S41", "S42", "S43", "S44", "Z-S11", "Z-S21", "Z-S12", "Z-S22", "Y-S11", "Y-S21", "Y-S12", "Y-S22", ) if not any(par.upper().startswith(sp) for sp in valid_spars): log.warning(f"S-parameter {par} may not be supported. Continuing anyway.") self.write( f"CALCulate{self._channel}:PARameter:MEASure '{self._active_trace}', '{par}'" ) @property def yformat(self) -> str: """Scale and format of data.""" return self.query(f"CALCulate{self._channel}:FORMat?") @yformat.setter def yformat(self, data_format="MLOG"): valid_formats = ( "MLOG", "MLIN", "REAL", "IMAG", "UPHase", "PHASe", "POLar", "SMITh", "SWR", ) if data_format.upper() not in [fmt.upper() for fmt in valid_formats]: log.warning( f"Format {data_format} may not be supported. Continuing anyway." ) self.write(f"CALCulate{self._channel}:FORMat {data_format}") @property def smoothing(self) -> int: """Number of points in smoothing window.""" status = self.query(f"CALCulate{self._channel}:SMOothing:STATe?") if to_bool(status): aperture = int(self.query(f"CALCulate{self._channel}:SMOothing:APERture?")) return aperture return 0 @smoothing.setter def smoothing(self, aperture: int): if aperture > 0: self.write(f"CALCulate{self._channel}:SMOothing:STATe ON") self.write(f"CALCulate{self._channel}:SMOothing:APERture {abs(aperture)}") else: self.write(f"CALCulate{self._channel}:SMOothing:STATe OFF")
[docs] def clear_average(self): """Reset averaging.""" self.write(f"SENSe{self._channel}:AVERage:CLEar")
@property def ifbw(self) -> float: """IF bandwidth of the receiver.""" return float(self.query(f"SENSe{self._channel}:BANDwidth:RESolution?")) @ifbw.setter def ifbw(self, bw: int): # R&S ZNB typically supports 1 Hz to 5 MHz bw = self.validate_range(bw, 1, 5_000_000) self.write(f"SENSe{self._channel}:BANDwidth:RESolution {bw}") @property def power(self) -> float: """Output signal power.""" return float( self.query(f"SOURce{self._channel}:POWer:LEVel:IMMediate:AMPLitude?") ) @power.setter def power(self, pwd: float): # R&S ZNB typically supports -45 to +13 dBm pwd = self.validate_range(pwd, -45, 13) self.write( f"SOURce{self._channel}:POWer:LEVel:IMMediate:AMPLitude {round(pwd, 1)}" )
[docs] def autoscale(self, trace: int = 1): """Autoscale the given trace of window 1.""" self.write(f"DISPlay:WINDow1:TRACe{trace}:Y:SCALe:AUTO ONCE")
[docs] def read_freqs(self) -> np.ndarray: """Read frequencies.""" return np.linspace(self.f_start, self.f_stop, self.points)
[docs] def sweep(self): """Perform a sweep measurement considering averaging (continuous mode waits).""" if self.averages > 1: self.clear_average() self.autoscale() if self.continuous: meas_time = self.sweep_time * self.averages * MEAS_TIME_FACTOR time.sleep(meas_time) else: if self.averages > 1: for _ in range(self.averages): self.write_and_hold(f"INITiate{self._channel}:IMMediate") else: self.write_and_hold(f"INITiate{self._channel}:IMMediate")
[docs] def read_trace_data(self, yformat=None) -> np.ndarray: """Read unformatted IQ data (complex) or formatted trace data. The data of the last sweep is read, call :meth:`sweep` first. """ if yformat is None: # Read complex S-parameter data self.activate_trace() iq = query_binblock(self, f"CALCulate{self._channel}:DATA? SDATa") z = np.empty(len(iq) // 2, dtype=np.complex128) z.real = iq[0::2] z.imag = iq[1::2] return z # Read formatted data self.yformat = yformat self.activate_trace() return query_binblock(self, f"CALCulate{self._channel}:DATA? FDATa")
[docs] def snapshot(self, yformat=None, **kwargs) -> Tuple[np.ndarray, np.ndarray]: """Set the given parameters, sweep once and return (frequencies, trace).""" self.set(**kwargs) self.hold() self.sweep() z = self.read_trace_data(yformat=yformat) f = self.read_freqs() self.hold() return f, z
[docs] def survey( self, f_win_start, f_win_end, f_win_size, **kwargs ) -> Tuple[np.ndarray, np.ndarray]: """Execute multiple scans with higher resolution.""" f = [] z = [] self.set(**kwargs) for f_start in np.arange(f_win_start, f_win_end, f_win_size): f_temp, z_temp = self.snapshot(f_start=f_start, f_stop=f_start + f_win_size) f.append(f_temp[1:]) z.append(z_temp[1:]) return np.array(f).flatten(), np.array(z).flatten()
# Calibration methods
[docs] def start_calibration(self, cal_type="TOSM", ports=None): """Start a calibration procedure. Args: cal_type: Calibration type ("TOSM", "SOLT", "FOPORT", etc.) ports: List of ports to calibrate (e.g., [1, 2]) """ if ports is None: ports = [1, 2] port_str = ", ".join(map(str, ports)) cal_name = f"Cal_{cal_type}_{port_str.replace(', ', '_')}" self.write( f"SENSe{self._channel}:CORRection:COLLect:METHod:DEFine '{cal_name}', {cal_type}, {port_str}" ) log.info(f"Started {cal_type} calibration on ports {ports}")
[docs] def measure_standard(self, standard, port=None): """Measure a calibration standard. Args: standard: Standard type ("OPEN", "SHORT", "LOAD", "THROUGH") port: Port number for single-port standards """ if port is not None: self.write( f"SENSe{self._channel}:CORRection:COLLect:ACQuire:SELected {standard}, {port}" ) else: self.write( f"SENSe{self._channel}:CORRection:COLLect:ACQuire:SELected {standard}" ) log.info(f"Measured {standard} standard" + (f" on port {port}" if port else ""))
[docs] def apply_calibration(self): """Apply the calibration.""" self.write(f"SENSe{self._channel}:CORRection:COLLect:SAVE:SELected") log.info("Calibration applied successfully")
# Trace management
[docs] def create_trace(self, trace_name: str, s_parameter: str): """Create a new trace with specified S-parameter.""" self.write( f"CALCulate{self._channel}:PARameter:SDEFine '{trace_name}', '{s_parameter}'" ) self._active_trace = trace_name log.info(f"Created trace '{trace_name}' for {s_parameter}")
[docs] def select_trace(self, trace_name: str): """Select active trace.""" self.write(f"CALCulate{self._channel}:PARameter:SELect '{trace_name}'") self._active_trace = trace_name
[docs] def delete_trace(self, trace_name: str): """Delete a trace.""" self.write(f"CALCulate{self._channel}:PARameter:DELete '{trace_name}'") if self._active_trace == trace_name: self._active_trace = "Trc1"
[docs] def list_traces(self): """List all traces in the current channel.""" response = self.query(f"CALCulate{self._channel}:PARameter:CATalog?") # Response format: 'TraceName,S-Parameter,TraceName,S-Parameter,...' response = response.strip().strip("'\"") if response: traces = response.split(",") return [(traces[i], traces[i + 1]) for i in range(0, len(traces), 2)] return []
@property def time_domain(self) -> bool: """Time domain mode status.""" return to_bool(self.query(f"CALCulate{self._channel}:TRANsform:TIME:STATe?")) @time_domain.setter def time_domain(self, state: bool): state_str = "ON" if to_bool(state) else "OFF" self.write(f"CALCulate{self._channel}:TRANsform:TIME:STATe {state_str}") @property def t_start(self) -> float: """Minimum measured time.""" return float(self.query(f"CALCulate{self._channel}:TRANsform:TIME:STARt?")) @t_start.setter def t_start(self, t_min: float): self.write(f"CALCulate{self._channel}:TRANsform:TIME:STARt {t_min}") @property def t_stop(self) -> float: """Maximum measured time.""" return float(self.query(f"CALCulate{self._channel}:TRANsform:TIME:STOP?")) @t_stop.setter def t_stop(self, t_max: float): self.write(f"CALCulate{self._channel}:TRANsform:TIME:STOP {t_max}")
[docs] def read_times(self) -> np.ndarray: """Read time domain x axis.""" return np.linspace(self.t_start, self.t_stop, self.points)
@property def time_domain_window(self) -> str: """Window shape used to process frequency into time domain data.""" return str(self.query(f"CALCulate{self._channel}:TRANsform:TIME:WINDow?")) @time_domain_window.setter def time_domain_window(self, window: str): self.validate_opt(window, ("RECT", "HANN", "HAMM", "BOHM", "DCH")) self.write(f"CALCulate{self._channel}:TRANsform:TIME:WINDOW {window}") @property def harmonic_grid(self) -> bool: """Status of automatic harmonic grid for step response time domain measurements.""" return to_bool(self.query(f"SENSe{self._channel}:HARMonic:AUTO?")) @harmonic_grid.setter def harmonic_grid(self, state: bool): state_str = "ON" if to_bool(state) else "OFF" self.write(f"SENSe{self._channel}:HARMonic:AUTO {state_str}") @property def low_pass_extrapolation(self) -> float: """Reflection coefficient extrapolation at 0 frequency.""" return float( self.query(f"CALCulate{self._channel}:TRANsform:TIME:LPASs:DCSParam?") ) @low_pass_extrapolation.setter def low_pass_extrapolation(self, low_pass_extrapolation: float): self.write( f"CALCulate{self._channel}:TRANsform:TIME:LPASs:DCSParam {self.validate_range(low_pass_extrapolation, -1, 1)}" ) @property def low_pass_stimulus(self) -> str: """Shape of the low pass time domain probe.""" return self.query(f"CALCulate{self._channel}:TRANsform:TIME:STIM?") @low_pass_stimulus.setter def low_pass_stimulus(self, low_pass_stimulus: str): self.validate_opt(low_pass_stimulus, ("STEP", "IMP")) self.write(f"CALCulate{self._channel}:TRANsform:TIME:STIM {low_pass_stimulus}")