<jupyter_start><jupyter_text>Hard- Tested On:  - Ubuntu 18.04 x86     - pyvisa (backend: pyvisa-py)  - Windows 10:    - pyvisa (backend: NI-VISA) TODO:Testing on more platforms:- raspberrypi4.- FreeBSD.<jupyter_code>import time
import mhs5200
import platform
import os
if os.name == "posix":
    signal_gen_port = "/dev/ttyUSB0"
    oscilloscope_port = scope_port = 'USB0::6833::1416::DS1EU152500705\x00::0::INSTR'
if os.name == "nt":
    signal_gen_port = "COM4"
    oscilloscope_port = scope_port = 'USB0::0x1AB1::0x0588::DS1EU152500705::INSTR'
import mhs5200.enums
with mhs5200.MHS5200(signal_gen_port) as signal_generator:
    for channel in signal_generator.channels:
        channel.amplitude=1
        channel.duty_cycle=50
        channel.frequency=1
        channel.offset=0
        channel.phase=0
        channel.wave=mhs5200.enums.SQUARE
import pyvisa
rm = pyvisa.ResourceManager('@py')
print(rm.list_resources())
import uuid
class Scope():
    def __init__(self, *args, oscilloscope=None, oscilloscope_port=None):
        if oscilloscope_port is not None:
            self.resource = rm.open_resource(oscilloscope_port)
        else:
            self.resource = oscilloscope
            
        for fcn in ["write", "query", "close", "query_ascii_values", "__repr__"]:
            setattr(self, fcn, getattr(self.resource, fcn))
        
    def __enter__(self):
        return self
    
    def __exit__(self, type, value, tb):
        t1=time.time()
        try:
            while True:
                if time.time()>t1+5:
                    break
                self.close()
                time.sleep(0.2)
        except InvalidSession:
            pass
        except:
            raise
signal_gen = mhs5200.MHS5200(signal_gen_port)
scope = Scope(oscilloscope_port=oscilloscope_port)
signal_generator.serial.open()
for channel, scope_channel in zip(signal_generator.channels, [1, 2]):
    frequency = scope_channel
    amplitude = 20

    channel.amplitude=amplitude
    channel.duty_cycle=50
    channel.frequency=frequency
    channel.offset=0
    channel.phase=0
    channel.wave=mhs5200.enums.SQUARE


    period = 1/float(frequency)
    timescale="{:.20f}".format(float(period/5))
    # Configure scope

    scope.write(f":MEASURE:TOTAL ON")
    scope.write(f":TIMebase:SCALE {timescale}")
    scope.write(f":CHANNEL{scope_channel}:probe 1")
    scope.write(f":CHANNEL{scope_channel}:scale {amplitude}")
    scope.write(f":CHANNEL{scope_channel}:offset 0")

    period = 1/float(frequency)
    timescale="{:.20f}".format(float(period/5))
    # Configure scope
    
    scope.write(f":MEASURE:TOTAL ON")
    scope.write(f":TIMebase:SCALE {timescale}")
    for scope_channel in [1, 2]:
        scope.write(f":CHANNEL{scope_channel}:probe 1")
        scope.write(f":CHANNEL{scope_channel}:scale {amplitude/5}")
        scope.write(f":CHANNEL{scope_channel}:offset 0")
scope.write(f":MEASURE:SOURCE CHAN1")
import pandas as pd
import pandas as pd
class TestPair():
    def __init__(channel_output, channel_input):
        self.channel_output = channel_output
        self.channel_input  = channel_input
df = pd.DataFrame()
with mhs5200.MHS5200(signal_gen_port) as signal_gen:
    with Scope(oscilloscope_port=oscilloscope_port) as scope:
        for _ in range(2):
            for frequency in np.logspace(np.log10(1000), np.log10(1000000), 2):
                for amplitude in [20]:
                    result_df = test_frequency_amplitude3(frequency, amplitude, signal_gen=signal_gen, scope=scope)
                    df = df.append(result_df)
def my_decorator(*args, **kwargs):
    # Args in passed to the decorator
    for idx, arg in enumerate(args):
        print(f"my_decorator {idx}: {arg}")
    for key,value in kwargs.items():
        print(f"my_decorator {key}: {value}") 
    # The inner function 
    def inner_function(*args2, **kwargs2):        
        for idx, arg in enumerate(args2):
            print(f"inner_function {idx}: {arg}")
        for key,value in kwargs2.items():
            print(f"inner_function {key}: {value}")
    return inner_function
class RigolChannel():
    def __init__(self, num, scope):
        self.num=num
        self.scope=scope
        
        
    def __repr__(self):
        return ""
        
    @property
    def source(self):
        return f"CHAN{self.num}"
    
    @my_decorator
    def fcn1(*args, **kwargs):        
        for idx, arg in enumerate(args):
            print(f"fcn1 {idx}: {arg}")
        for key,value in kwargs.items():
            print(f"fcn1 {key}: {value}")
        print("")     
    def __repr__(self):
        return "MyClass<!obj!>"
scope.close()
ch = RigolChannel(1, scope)
ch.fcn1()
self = ch
scope.write(f":MEASURE:SOURCE {self.source}")
ch.test1(1, 2, 4, foo="bar")
for source in ["CHAN1", "CHAN2"]:
scope.write(f":MEASURE:SOURCE {source}")
time.sleep(1)
for param in ['VPP',
                'VMAX',
                'VMIN',
                'VAMPlitude',
                'VTOP',
                'VBASe',
                'VAVerage',
                'VRMS',
                'OVERshoot',
                'PREShoot',
                'FREQuency',
                'RISetime',
                'FALLtime',
                'PERiod',
                'PWIDth',
                'NWIDth',
                'PDUTycycle',
                'NDUTycycle',
                'PDELay',
                'NDELay',
                'TOTal',
                'SOURce',]:
    try:
        measured = scope.query_ascii_values(f":MEASURE:{param}?")[0]
        # Returns Junk
        if measured == 9.9e+37:
            measured = np.nan
    except:
        measured = scope.query(f":MEASURE:{param}?")[0]
def test_dataframe(frequency, amplitude, signal_gen, scope):
    for chan in signal_gen.channels:
        chan.frequency=frequency
        chan.amplitude=amplitude
        chan.phase=0
    period = 1/float(frequency)
    timescale="{:.20f}".format(float(period/5))
    # Configure scope
    
    scope.write(f":MEASURE:TOTAL ON")
    scope.write(f":TIMebase:SCALE {timescale}")
    for scope_channel in [1, 2]:
        scope.write(f":CHANNEL{scope_channel}:probe 1")
        scope.write(f":CHANNEL{scope_channel}:scale {amplitude/5}")
        scope.write(f":CHANNEL{scope_channel}:offset 0")
    # Configure signal generator
    for chan in signal_gen.channels:
        chan.frequency=frequency
        chan.amplitude=amplitude
        chan.offset = 0
        chan.phase=0

    df = dict()
    df["uuid"] = str(uuid.uuid4())
    df["frequency"] = frequency
    df["amplitude"] = amplitude
    for source in ["CHAN1", "CHAN2"]:
        scope.write(f":MEASURE:SOURCE {source}")
        time.sleep(1)
        for param in ['VPP',
                        'VMAX',
                        'VMIN',
                        'VAMPlitude',
                        'VTOP',
                        'VBASe',
                        'VAVerage',
                        'VRMS',
                        'OVERshoot',
                        'PREShoot',
                        'FREQuency',
                        'RISetime',
                        'FALLtime',
                        'PERiod',
                        'PWIDth',
                        'NWIDth',
                        'PDUTycycle',
                        'NDUTycycle',
                        'PDELay',
                        'NDELay',
                        'TOTal',
                        'SOURce',]:
            try:
                measured = scope.query_ascii_values(f":MEASURE:{param}?")[0]
                # Returns Junk
                if measured == 9.9e+37:
                    measured = np.nan
            except:
                measured = scope.query(f":MEASURE:{param}?")[0]

            df[f"{source}_{param}"] = measured
    return pd.DataFrame(df, index=[0])
import numpy as np
df = pd.DataFrame()
with mhs5200.MHS5200(signal_gen_port) as signal_gen:
    with Scope(oscilloscope_port=oscilloscope_port) as scope:
        for _ in range(2):
            for frequency in np.logspace(np.log10(1000), np.log10(1000000), 2):
                for amplitude in [20]:
                    result_df = test_frequency_amplitude3(frequency, amplitude, signal_gen=signal_gen, scope=scope)
                    df = df.append(result_df)
df.groupby(["frequency"])["CHAN1_FREQuency"].agg(["mean", "median", "std", "var"])
import numpy as np
frequencies = np.logspace(np.log10(1000000), np.log10(100000000), 10)
amplitudes = [20]
n_tests=1
df = pd.DataFrame()
with mhs5200.MHS5200(signal_gen_port) as signal_gen:
    with Scope(oscilloscope_port=oscilloscope_port) as scope:
        for _ in range(n_tests):
            for frequency in frequencies:
                for amplitude in [20]:
                    result_df = test_frequency_amplitude3(frequency, amplitude, signal_gen=signal_gen, scope=scope)
                    df = df.append(result_df)
df.groupby(["frequency"])["CHAN1_FREQuency"].agg(["mean", "median", "std", "var"])
scope=Scope(oscilloscope_port=oscilloscope_port)
param="FREQUENCY"
scope.query_ascii_values(f":MEASURE:{param}?")[0]==9.9e+37
np.nan
scope.close()
df = pd.DataFrame()
with mhs5200.MHS5200(signal_gen_port) as signal_gen:
    with Scope(oscilloscope_port=oscilloscope_port) as scope:
        test_frequency_amplitude3(100, 20, signal_gen, scope)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12399700438643416, 'fraction_numerical': 0.02963517706215898, 'mean_word_length': 2.18935516888434, 'pattern_counts': {'":': 26, '<': 6, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '184133', 'license': 'MIT', 'n_tokens_mistral': 3197, 'n_tokens_neox': 2939, 'n_words': 573, 'path': 'DevelopmentNotebooks/HIL_Unit_Tests-Copy6.ipynb', 'repo_name': 'dapperfu/python_Rigol', 'size': '9347'}