Skip to main content
Version: current

Python Script

Description

The script block Python Script can run external Python functions, from .py files, so you can develop your own algorithms.

Python 3.6 or above must be installed.

MxNKxL

Input

The input is MxN and your function will be receiving a dictionary as seen below. You can manipulate the keys of the dictionary but the variable type of each key should remain constant.

import numpy as np

data = {'0': {'msg': '',
              'fs': np.array([[48000]]),
              'xlabel': np.array([['Time']]),
              'ylabel': np.array([['Amplitude']]),
              'xunit': np.array([['s']]),
              'yunit': np.array([['SPL']]),
              'X': np.array([[1],
                             [2],
                             [3]]),
              'Y': np.array([[5],
                             [8],
                             [9]])
              }
        }

Output

The output is KxL and is the return dictionary from you Python function. An example of some python processing can be seen below.

def bar(data, variables, metadata):
    """
    Example function to be used in a SAFE measurement sequence.
    
    :param data: A dictionary to be used throughout a measurement sequence.
    :param variables: A dictionary of all the variables your have defined in the current project
    :param metadata: A dictionary af all the metadata you have defined in the current project
    :return: data, variables, metadata: The data dictionary, the variables dictionary and the metadata dictionary
    """
    data['0']['Y'] = data['0']['Y'] * 2
    variables['my_var'] = 4
    return data, variables, metadata

if __name__ == '__main__':
    import sys
    import json
    import numpy as np
    import time

    def serializeDict(d):
        return {k.replace('\'', '"'): v.tolist() if isinstance(v, np.ndarray) else serializeDict(v) if isinstance(v, dict) else v for k, v in d.items()}

    def deserializeDict(d):
        return {k.replace('\'', '"'): np.array(v) if isinstance(v, list) else deserializeDict(v) if isinstance(v, dict) else v for k, v in d.items()}

    info, variables, metadata = {}, {}, {}
    for i, arg in enumerate(sys.argv):
        if i == 2:
            variables = deserializeDict(json.loads(arg))  # decode data to numpy arrays
        elif i == 3:
            metadata = deserializeDict(json.loads(arg))  # decode data to numpy arrays
    data = deserializeDict(json.loads(sys.stdin.read()))  # read and decode data to numpy arrays
    # If you need to setup something before running the function do it here
    returnList = list(globals()[sys.argv[1]](data, variables, metadata))  # function call
    for i, ret in enumerate(returnList[:3]):
        if not isinstance(ret, dict):
            raise ValueError('Function must return two dictionaries.')
        if i == 0:
            print(f"***DATA***")
        elif i == 1:
            print(f"***VARIABLES***")
        elif i == 2:
            print(f"***METADATA***")
        print(json.dumps(serializeDict(ret)))  # encode and print output
    # NO PRINTS AFTER THIS LINE #

Attributes

AttributeValue
NamePython Script
File Path
Function Namefoo
Timeout (seconds)5
Channels1

Name

Name specifies the name of the block.

File Path

The filepath is the path to the Python .py file you want to use.

Function Name

The function name is the name of the function you want to run inside your Python script.

Timeout (seconds)

The timeout parameter determines how long time SAFE will wait for the script to execute.

Channels

Channels specifies the number of input(s)/output(s) the block will have.

Literature