Tutorial: Adding a simple function from the UI

In this tutorial, you are writing a simple function to identify outlier values in the distance traveled by robots. Test this simple function using a script before you apply it to a sample device type in Analytics Service.

Before you begin

  1. Install Python 3.x in your environment.
  2. Install IoT Functions in your local environment. Follow the instructions in the IoT Functions readme.
    Tip: Alternatively, to install IoT Functions and its dependencies, you can follow the steps in the Before you begin section of Tutorial - Adding a custom function. Clone the HelloWorld starter package and import the starter package into PyCharm. Install the requirements from PyCharm. Note: In the beta environment, to install or upgrade IoT Functions, use the beta branch. Otherwise, use the production branch.
  3. Complete Tutorial: Adding expressions to add a distance KPI to the robot device type in Analytics Service.

About this task

You are testing a simple function in your local environment to make sure that the calculation works and that the syntax is correct.

In the script, you create a sample device type, generate some sample data, and apply the simple function to the sample data to create a new adjusted_distance KPI.

Steps

Complete these steps to apply a calculation to sample data using a simple function.

Step 1: Define your calculation

Define adjusted_distance as follows:

adjusted_distance = distance * 0.9

Step 2: Save your credentials to a file

Set credentials to connect to Analytics Service.

  1. Create a credentials_as.json file in your working directory. From the user interface, go to the Usage tab.
  2. Select Watson IoT Platform Analytics and click View Details.
  3. In the Environment Variables field, click Copy to Clipboard.
  4. Paste the contents of the clipboard into the credentials_as.json file.

Note: Take care not to save the credentials file to any external repository.

Step 3: Write a simple function in Python

Write a script, save_simple_function_locally.py, that adjusts the distance traveled by robots. In the script, connect to Analytics Service using your credentials and save the function to a local model store. See the inline comments for instructions.

#Import packages and libraries

import datetime as dt
import json
import pandas as pd
import numpy as np
from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean, func
import iotfunctions.bif as bif
from iotfunctions.metadata import EntityType, LocalEntityType
from iotfunctions.db import Database
from iotfunctions.dbtables import FileModelStore


#Connect to the service
with open('credentials_as.json', encoding='utf-8') as F:
    credentials = json.loads(F.read())
db_schema = None
db = Database(credentials=credentials)

#Write the function

def f(df, parameters = None):
    adjusted_distance = df['distance'] * 0.9
    return adjusted_distance

#Save the function to a local model store
model_store = FileModelStore()
model_store.store_model('adjusted_distance', f)

Step 4: Save the function to a local file model store

Run the script save_simple_function_locally.py from your local environment. A file KPI_MODEL_STOREadjusted_distance is created in the same directory where you stored your script.

Step 5: Test your simple function in your local environment

Create a script called test_my_simple_function_locally.py. In the script, complete these steps:

  1. Import Python libraries and packages:
     import datetime as dt
     import json
     import pandas as pd
     import numpy as np
     from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean, func
     import iotfunctions.bif as bif
     from iotfunctions.metadata import EntityType, LocalEntityType
     from iotfunctions.db import Database
     from iotfunctions.dbtables import FileModelStore
    
  2. Connect to the service:

     with open('credentials_as.json', encoding='utf-8') as F:
         credentials = json.loads(F.read())
     db_schema = None
     model_store = FileModelStore()
     db = Database(credentials=credentials, model_store=model_store)
    
  3. Create a sample device type and pass the simple function to it using the built-in PythonFunction from the bif module that you imported from IoT Functions.
    sample_entity_type = bif.PythonFunction(
        function_code = 'adjusted_distance',
        input_items = ['distance'],
        output_item = 'adjusted_distance',
        parameters = {}
            )
    
  4. Run the execute_local_test method of the sample device type to test the function in your local environment. Save the results to a csv file.
    sample_entity_type.execute_local_test(db=db, generate_days=1, to_csv=True)
    
    The script creates a new adjusted_distance data item. Review the results in the CSV file. If successful, you are ready add the simple function using the Analytics Service UI.

Step 6: Apply the simple function to the Robot device type

  1. From the Data tab, click Screenshot of the Create new data item button..
  2. Select the PythonFunction function from the catalog.
  3. Select distance as an input item.
  4. Enter or paste in the simple function in the function_code field. Enter:
    def f(df, parameters = None):
     adjusted_distance = df['distance'] * 0.9
     return adjusted_distance
    
  5. Click Next
  6. On the output page, specify adjusted_distance as the new KPI name.
  7. Specify the data type as Number.
  8. Click Create
  9. In the data item list, select adjusted_distance.
  10. View the new adjusted_distance metric data in the Details & derived data pane.

Wait up to 5 minutes for Analytics Service to evaluate the simple function against the sample data.