Objectives

In this Exercise you will write MultiplyByFactor custom function.

Tip

you can define your calculation as required!

Define your calculation

Business scenario:

A robotics company is testing new robotic arms and has discovered that testing tools introduce delays affecting speed and travel time measurements. The operations manager needs to adjust these values by a factor of 2 but wants flexibility to change this factor later.

Solution approach:

Create a reusable MultiplyByFactor function that can:
- Accept multiple input items
- Apply a configurable multiplication factor
- Generate corresponding output items
- Be reused across different calculations
- Formula: output_value = input_value * factor

Package your function and store it in GitHub

  1. Create a new private repository on GitHub for the starter package you cloned.
  2. Add an empty file (such as README.md) to create the master branch
  3. Open the project in PyCharm locally for editing.
  4. Verify that the project has the following directory structure and files:
    
            functions
            |
            |__ setup.py
            |
            |__ scripts
                |
                |_ local_test_of_function.py
            |
            |__ custom
                |
                |_ functions.py
                |_  __init__.py
         

Create your custom function

  1. Rename the custom directory to custom{your_initials} (for example, customRS)
  2. Create a new file multiplybyfactor{your_initials}.py in your custom{your_initials} directory
  3. Add the following code, Update the variables in <> to match your environment. For example, if your code is in GitHub, you might set PACKAGE_URL to
    'git+https://@github.com/github.com/jones/starter@starter_package'. In this function, you implement two methods. You add your calculation to the execute method. You set the inputs and outputs arguments for the function in the build_ui method.

  4. 
    import inspect
    import logging
    import datetime as dt
    import math
    from sqlalchemy.sql.sqltypes import TIMESTAMP,VARCHAR
    import numpy as np
    import pandas as pd
    
    from iotfunctions.base import BaseTransformer
    from iotfunctions import ui
    
    logger = logging.getLogger(__name__)
    
    # Specify the URL to your package here.
    # This URL must be accessible via pip install.
    # Example assumes the repository is private.
    # Replace XXXXXX with your personal access token.
    # After @ you must specify a branch.
    
    PACKAGE_URL = 'git+https://XXXXXX@github.com/@starter_package'
    
    class MultiplyByFactor(BaseTransformer):
    
        def __init__(self, input_items, factor, output_items):
    
            self.input_items = input_items
            self.output_items = output_items
            self.factor = float(factor)
            super().__init__()
        def execute(self, df):
            df = df.copy()
            for i,input_item in enumerate(self.input_items):
                df[self.output_items[i]] = df[input_item] * self.factor
            return df
    
        @classmethod
        def build_ui(cls):
            #define arguments that behave as function inputs
            inputs = []
            inputs.append(ui.UIMultiItem(
                    name = 'input_items',
                    datatype=float,
                    description = "Data items adjust",
                    output_item = 'output_items',
                    is_output_datatype_derived = True)
                          )        
            inputs.append(ui.UISingle(
                    name = 'factor',
                    datatype=float)
                          )
            outputs = []
            return (inputs,outputs)   
    

Save your credentials to a file

Set credentials to connect to Maximo Monitor.

  1. Navigate to your starter package directory and locate the credentials_as.json template file
  2. Replace the variables with your data and then save the file to your local machine.

Note

The credentials file is used to run or test the function locally. Do not push this file to your external repository.

Push your local changes to your GitHub repository

The files that you modified are still pointing to the GitHub repository that you cloned the code from. Change the remote repository to your GitHub repository.

Verify that your credentials file is not included with your function code before the commit the changes to your external directory.

Push your function code to your external repository in GitHub.

  1. Open a terminal window in the project folder
  2. Enter: git remote -v. The remote repository is still pointing to https://github.com/ibm-watson-iot/functions
  3. Change the remote origin URL by using the following commands:

  4.  git remote set-url origin URL_To_YOUR_GITHUB_REPOSITORY
             
    Confirm that the Fetch and Push URLs are pointing to your repository.
  5. Add the upstream remote by using the following command. Enter:
  6.  git remote add upstream https://github.com/ibm-watson-iot/functions.git  
  7. Add your files to GIT and commit them.
    a. In PyCharm, select the custom directory.
    b. Select Git > Add.
    c. Select Git > Commit.
    d. In the Commit Changes window, click Commit.
    e. Select Git > Repository > Push.
    f. Click Push.
  8. Verify that your module was pushed to a starter_package branch in your repository.

Congratulations you have successfully written custom function.