Examples of Using the Python Collector (Additional Functionality)

To use additional Python modules, install them over Python 3.8.

For example, to install NumPy:
  1. Run the following command:
    Pip intall numpy
  2. Add the site packages to the Python path as follows:
    Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\GE Digital\iHistorian\CollectorServiceExtensions\PythonExpressions\PythonPath 
    After you do so, the changes are reflected as follows:
    C:\Program Files (x86)\GE Digital\Historian Python Expressions\Python38\lib
    C:\Program Files (x86)\GE Digital\Historian Python Expressions\Python38\user
    C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\Lib
    C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\Lib\site-packages

Retrieve the Age of the First Person from a List Using a REST API

import requests
import json
api_url = https://myRestAPIURL/
response = requests.get(api_url)
json_data = json.loads(response.text)

Results=json_data["results"][0]
dateOfBirth =Results["dateofbirth"]
age = dateOfBirth["age"]
Result=age
Returns the following result:
{
    "results": [
        {
            "gender": "female",
            "name": {
                "title": "Mrs",
                "first": "Lumi",
                "last": "Tikkanen"
            },
            "dateofbirth": {
                "date": "1982-01-08T21:23:26.095Z",
                "age": 39
            },
            "phone": "08-609-184",
            "cell": "049-127-63-22"
        }
    ]
}

Calculate the Sum of all Values in a Column in an SQL Database

import pyodbc

conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
                      'Server=MySQLServer;'
                      'Database=MyDB;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()
cursor.execute('SELECT column1 FROM Table_1')

sum = 0;
for i in cursor:
	sum = sum + i.column1

Result = sum
conn.close()

Calculate a Score Using Linear Regression in NumPy

import numpy as np
from sklearn.linear_model import LinearRegression

X = np.array([[2, 7], [10, 4], [5, 7], [2, 3]])
y = np.dot(X, np.array([1, 2])) + 3
reg = LinearRegression().fit(X, y)
Result = reg.score(X, y)

Reading Data from a File Using Pandas

To read the data using Pandas, you must create:
  • Training dataset using 80% of the data
  • Linear regression model using the training data
  • Return the coefficient of the model
import pandas as pd
import numpy as np
from sklearn import linear_model

data = pd.read_csv("C:\\myFile.csv")
data = data[["Column1","Column2"]]
train = data[:(int((len(data)*0.8)))]

regressionLine = linear_model.LinearRegression()

train_x = np.array(train[["Column1"]])
train_y = np.array(train[["Column2"]])

regressionLine.fit(train_x,train_y)

Result=regressionLine.coef_[0][0]

Mathematical Optimization

The Rosenbrock function to perform mathematical optimization is defined in SciPy as follows: sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
import numpy as np
from scipy.optimize import rosen

a = 0.2 * np.arange(9)
Result=rosen(a)

Calculating the Determinant of a Matrix using SciPy

#calculate the determinant of a square matrix
import numpy as np
from scipy import linalg

A = np.array([[1,2,4], [4,3,7], [2,7,3]])
Result=linalg.det(A)

Creating a Data Frame from an Array and Calculating the Sum of all Elements

import numpy as np
import pandas as pd

df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6]]))
Result=float(df.sum().sum())

Generating a Random Value

from random import seed
from random import random

seed(10)
Result=random()*random()