Example_Spectrum_MS2760A

This is an example of using the library.

  1# %% ==========================================================================
  2# Import and Definitions
  3# =============================================================================
  4import datetime
  5import time
  6
  7import matplotlib.pyplot as plt
  8import numpy as np
  9import pandas as pd
 10from tqdm import tqdm
 11
 12# Instrument Libraries Github: https://github.com/MartinMiroslavovMihaylov/Python_Instruments_Automation_Scripts
 13# Install with:
 14# pip install git+https://github.com/MartinMiroslavovMihaylov/Python_Instruments_Automation_Scripts.git
 15# from Instruments_Libraries.MS2760A import MS2760A  # SpectrumAnalyzer
 16from Instruments_Libraries.InstrumentSelect import SpecAnalyser
 17
 18# %% ==========================================================================
 19# Select Instruments and Load Instrument Libraries
 20# =============================================================================
 21# mySpecAnalyser = MS2760A('127.0.0.1') # using class directly  # noqa: N816
 22mySpecAnalyser = SpecAnalyser() # using InstrumentSelect  # noqa: N816
 23mySpecAnalyser.reset()
 24
 25# %% ==========================================================================
 26# Setup the Measurement
 27# =============================================================================
 28num_of_points = 10
 29sleep_time = 1 # in seconds
 30freq = np.linspace(1e9, 40e9, num_of_points)
 31
 32# Initial Spectrum Analyzer Sweep Settings
 33SA_TraceNum = 1  # only for Anrisu MS2760A
 34SA_f_min = 0
 35SA_f_max = 40e9
 36SA_resBW = 100e3
 37SA_ref_level = -10  # dBm
 38datapoints = 4001
 39
 40# %% ==========================================================================
 41# Configure the Instrument
 42# =============================================================================
 43mySpecAnalyser.set_continuous('OFF')
 44# time.sleep(0.5) # probably not needed
 45mySpecAnalyser.set_sweep_points(datapoints)
 46mySpecAnalyser.set_reference_level(SA_ref_level) # in dBm
 47mySpecAnalyser.set_if_gain_state('ON') # Enable IF Gain (need ref level <= -10dBm)
 48mySpecAnalyser.set_resolution_bandwidth(SA_resBW, 'HZ')
 49mySpecAnalyser.set_stop_frequency(SA_f_max, 'HZ')
 50mySpecAnalyser.set_start_frequency(SA_f_min, 'HZ')
 51mySpecAnalyser.set_trace_mode('NORM', trace_number=SA_TraceNum)
 52# Detector Type: POS -> Peak (default), others are: RMS, NEG
 53mySpecAnalyser.set_detector_mode('POS', trace_number=SA_TraceNum) 
 54
 55# %% ==========================================================================
 56# Measurement
 57# =============================================================================
 58
 59records = [] # Empty list to store data and meta data
 60for idx in tqdm(range(num_of_points)):
 61    rec = {} # single record
 62
 63    # Do some changes, like change input frequency
 64    # SignalGenerator.set_freq_CW(freq[i])
 65
 66    # Write Meta Data
 67    rec["SA f_min"] = SA_f_min
 68    rec["SA f_max"] = SA_f_max
 69    rec["SA ref level"] = SA_ref_level
 70    rec["SA Resolution BW"] = SA_resBW
 71
 72    # Take the Measurement
 73    time.sleep(sleep_time)
 74    rec["data_peak"] = mySpecAnalyser.measure_and_get_trace(
 75        trace_number=SA_TraceNum, clear_trace=True)
 76
 77    # append the record
 78    rec["Timestamps"] = datetime.datetime.now()
 79    records.append(rec)
 80    temp = idx*np.pi # do something with idx
 81    
 82
 83# %% ==========================================================================
 84# Create Dataframe
 85# =============================================================================
 86meas_df = pd.DataFrame.from_records(records)
 87
 88# %% ==========================================================================
 89# Plot the Measurement
 90# =============================================================================
 91freq_hz = np.linspace(SA_f_min, SA_f_max, datapoints)
 92power_dBm = np.vstack(meas_df["data_peak"])  # noqa: N816
 93
 94plt.plot(freq_hz, meas_df["data_peak"][0])
 95plt.xlabel('Frequency (Hz)')
 96plt.ylabel('Power (dBm)')
 97plt.show()
 98# %% ==========================================================================
 99# Save Dataframe
100# =============================================================================
101# Save DataFrame to HDF5 (better than CSV)
102meas_df.to_hdf("measurements.h5", key="data", mode="w")
103# key="data" is like a "dataset name" inside the HDF5 file 
104# (you can store multiple DataFrames in one file with different keys).
105# mode="w" overwrites the file. Use mode="a" if you want to append new datasets.
106
107# Later: Load it back
108loaded_df = pd.read_hdf("measurements.h5", key="data")
109print(loaded_df.head())
110
111#or
112
113# Save DataFrame to CSV
114meas_df.to_csv("measurements.csv", index=False)
115
116# Load it back, auto-parsing the "Timestamps" column as datetime
117loaded_df = pd.read_csv("measurements.csv", parse_dates=["Timestamps"])
118print(loaded_df.head())
119
120# %% ==========================================================================
121# Close Instrument
122# =============================================================================
123mySpecAnalyser.Close()