Example_MS2760A

This is an example of using the library.

  1# %% ==========================================================================
  2# Import and Definitions
  3# =============================================================================
  4import time
  5import datetime
  6import pandas as pd
  7import numpy as np
  8import matplotlib.pyplot as plt
  9from tqdm import tqdm
 10
 11
 12
 13# Instrument Libraries Github: https://github.com/MartinMiroslavovMihaylov/Python_Instruments_Automation_Scripts
 14# Install with:
 15# pip install git+https://github.com/MartinMiroslavovMihaylov/Python_Instruments_Automation_Scripts.git
 16
 17# from Instruments_Libraries.MS2760A import MS2760A  # SpectrumAnalyzer
 18from Instruments_Libraries.InstrumentSelect import SpecAnalyser
 19
 20# %% ==========================================================================
 21# Select Instruments and Load Instrument Libraries
 22# =============================================================================
 23# mySpecAnalyser = MS2760A('127.0.0.1')
 24mySpecAnalyser = SpecAnalyser()
 25mySpecAnalyser.reset()
 26
 27# %% ==========================================================================
 28# Setup the Measurement
 29# =============================================================================
 30num_of_points = 10
 31sleep_time = 1 # in seconds
 32freq = np.linspace(1e9, 40e9, num_of_points)
 33
 34# Initial Spectrum Analyzer Sweep Settings
 35SA_TraceNum = 1  # only for Anrisu MS2760A
 36SA_f_min = 0
 37SA_f_max = 40e9
 38SA_resBW = 100e3
 39SA_ref_level = -10  # dBm
 40datapoints = 4001
 41
 42# %% ==========================================================================
 43# Configure the Instrument
 44# =============================================================================
 45mySpecAnalyser.set_Continuous('OFF')
 46# time.sleep(0.5) # probably not needed
 47mySpecAnalyser.set_DataPointCount(datapoints)
 48mySpecAnalyser.set_RefLevel(SA_ref_level) # in dBm
 49mySpecAnalyser.set_IFGainState('ON') # Enable IF Gain (need ref level <= -10dBm)
 50mySpecAnalyser.set_ResBwidth(SA_resBW, 'HZ')
 51mySpecAnalyser.set_freq_Stop(SA_f_max, 'HZ')
 52mySpecAnalyser.set_freq_Start(SA_f_min, 'HZ')
 53mySpecAnalyser.set_TraceType('NORM', SA_TraceNum)
 54# Detector Type: POS -> Peak (default), others are: RMS, NEG
 55mySpecAnalyser.set_DetectorType('POS', SA_TraceNum) 
 56
 57# %% ==========================================================================
 58# Measurement
 59# =============================================================================
 60
 61records = [] # Empty list to store data and meta data
 62for i in tqdm(range(num_of_points)):
 63    rec = {} # single record
 64
 65    # Do some changes, like change input frequency
 66    # SignalGenerator.set_freq_CW(freq[i])
 67
 68    # Write Meta Data
 69    rec["SA f_min"] = SA_f_min
 70    rec["SA f_max"] = SA_f_max
 71    rec["SA ref level"] = SA_ref_level
 72    rec["SA Resolution BW"] = SA_resBW
 73
 74    # Take the Measurement
 75    time.sleep(sleep_time)
 76    rec["data_peak"] = mySpecAnalyser.ExtractTraceData(SA_TraceNum,True)
 77
 78    # append the record
 79    rec["Timestamps"] = datetime.datetime.now()
 80    records.append(rec)
 81    
 82
 83# %% ==========================================================================
 84# Create Dataframe
 85# =============================================================================
 86meas_df = pd.DataFrame.from_records(records)
 87
 88# %% ==========================================================================
 89# Plot the Measurement
 90# =============================================================================
 91freq_hz = SA_f_min + np.arange(datapoints) * (SA_f_max - SA_f_min) / (datapoints - 1)
 92power_dBm = np.vstack(meas_df["data_peak"])
 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()