Working with Python

Python is a general-purpose programming language and supports code execution on other languages, such as Java, C and C#. A special set of external libraries has been developed to provide work with Python in Foresight Analytics Platform. These libraries allow for working with Foresight Analytics Platform core. The libraries are available in the folder S\Interops\python\ after running the FP10PythonInterops.exe installer, where S - path to the folder with installed Foresight Analytics Platform.

NOTE. When working in Windows OS, the Python version in use should match the version used on compiling external libraries. The current version is 3.11. Linux libraries do not depend on the Python version used in the build. If libraries of other versions are required, contact technical support by sending an email to support@fsight.ru or use technical support services that are available after registration at the website.

Connecting Assemblies

When working with Python 3.8 or later, first of all, add a path to the platform to the list of allowed paths:

import os
os.add_dll_directory("C:\Program Files\Foresight\Analytics Platform 10.x")

In the code enter the string with type import from the external assembly in one of the following formats:

from foresight.<Unit name> import * #Import of all library classes/interfaces.
from foresight.<Unit name> import <class name> #Import of a specific class/interface.
import foresight.<Unit name> as <variable> #Class import with a specific name.

Converting Code

When creating external libraries to be used in Python, system classes, interfaces, enumerations and other types are specifically transformed. Take into account the following changes when creating a Python code using Foresight Analytics Platform resources:

  1. Properties are compared with methods in the following formats: get_<property name>([<parameters>]) and put_<property name>(<value>). Get returns the property value and Put sets the specified value.

  2. Classes names are added with C, for example: the Fore MetabaseManagerFactory class corresponds to the Python CMetabaseManagerFactory class.

  3. To create an object of the required class, use the structure: <Class name>.Create() or <Class name>.Create<interface name>() without the new keyword.

  4. To cast types, it is required to sent existing object as parameter, for example:

import foresight.metabase as modmetabase
...
creds = pack.CreateCredentials(amPassword)
pswdCreds = modmetabase.IPasswordCredentials(creds)

Examples

Below are the examples of implementation of various Fore procedures or functions and their Python analogs. For simplicity of understanding, variable names and comments in functions are kept the same.

The example of connecting to repository in the Python code:

Function ConnectMB: IMetabase;
Var
    mb: IMetabase;
    mbMan: IMetabaseManager;
    mbDefs: IMetabaseDefinitions;
    mbDef: IMetabaseDefinition;
    pack: ISecurityPackage;
    creds: ICredentials;
    pswdCreds: IPasswordCredentials;
Begin
    // Repository manager
    mbMan := MetabaseManagerFactory.Active;
    // All descriptions of repositories
    mbDefs := mbMan.Definitions;
    // Get description of the repository, to which connection is established
    mbDef := mbDefs.FindById("'Repository'");
    // Security unit
    pack := mbMan.Packs.FindById(mbDef.SecurityPackage).Package;
    // Create and set up credentials for connection
    creds := pack.CreateCredentials(AuthenticationMode.Password);
    pswdCreds := creds As IPasswordCredentials;
    pswdCreds.UserName := "user";
    pswdCreds.Password := "password";
    // Connect to repository and return context to work with repository contents
    mb := mbDef.OpenDefault(pswdCreds);
    Return mb
End Function ConnectMB;
import os
from foresight.metabase import * #Import of contents of the entire Metabase assembly
def ConnectMB():
    os.add_dll_directory("C:\Program Files\Foresight\Analytics Platform 10.x")
    # Repository manager
    mbFactory = CMetabaseManagerFactory.Create()
    mbMan = mbFactory.Active
    # All descriptions of repositories
    mbDefs = mbMan.Definitions
    mbDefs.ReadFromRegistry()
    # Get description of the repository, to which connection is established
    mbDef = mbDefs.FindById('Repository')
    # Security unit
    pack = mbMan.Packs.FindById(mbDef.get_SecurityPackage()).Package
    # Create and set up credentials for connection
    creds = pack.CreateCredentials(amPassword)
    pswdCreds = IPasswordCredentials(creds)
    pswdCreds.UserName = 'user'
    pswdCreds.Password = 'password'
    # Connect to repository and return context for working with repository contents
    mb = mbDef.OpenDefault(pswdCreds)
    return mb
 
if __name__ == '__main__':
    mb = ConnectMB()
    print(mb.Name)

Get object description. As the first parameter, one sends repository context returned by the ConnectMB function:

Function GetMbObject(mb: IMetabase; id: String): IMetabaseObjectDescriptor;
Var
    mdesc: IMetabaseObjectDescriptor;
Begin
    // Get object description by getting value of the IMetabase.ItemById property
    mdesc := mb.ItemById(id);
    Return mdesc;
End Function GetMbObject;
from foresight.metabase import *
def GetMbObject(mb, id):
    # Get object description by getting value of the IMetabase.ItemById property
    mdesc = mb.get_ItemById(id)
    return mdesc

Open regular report, change cell value and save changes. As the first parameter, one sends regular report description that can be obtained using the GetMbObject previous function:

Sub EditPrxReport(mdesc: IMetabaseObjectDescriptor; newValue: Variant);
Var
    report: IPrxReport;
    ptable: IPrxTable;
    sheet: ITabSheet;
Begin
    // Open report for edit and cast result to the IPrxReport type
    report := mdesc.Edit As IPrxReport;
    // Get active sheet table
    ptable := report.ActiveSheet As IPrxTable;
    sheet := ptable.TabSheet;
    // Change cell value
    sheet.Cell(00).Value := newValue;
    // Save changes
    report.MetabaseObject.Save;
    // Check set cell value
    Debug.WriteLine(sheet.Cell(00).Value);
End Sub EditPrxReport;
from foresight.metabase import *
from foresight.report import *
from foresight.tab import *
def EditPrxReport(mdesc, newValue):
    # Open report for edit and cast result to the IPrxReport type
    report = IPrxReport(mdesc.Edit())
    # Get active sheet table
    ptable = IPrxTable(report.get_ActiveSheet())
    sheet = ITabSheet(ptable.get_TabSheet())
    # Change cell value
    sheet.get_Cell(0, 0).put_Value(newValue)
    # Save values
    report.get_MetabaseObject().Save()
    # Check set cell value
    print(sheet.get_Cell(0, 0).get_Value())

Open cube, create selection, calculate and return output cube matrix:

Function GetCubeMatrix(mdesc: IMetabaseObjectDescriptor): IMatrix;
Var
    cube: ICubeInstance;
    destInst: ICubeInstanceDestination;
    dimSS: IDimSelectionSet;
    dimS: IDimSelection;
    matr: IMatrix;
    i, c: Integer;
Begin
    // Open cube
    cube := mdesc.Open(NullAs ICubeInstance;
    // Get cube display version instance
    destInst := cube.Destinations.DefaultDestination;
    // Create selection
    dimSS := destInst.CreateDimSelectionSet;
    // Select all elements in all dimensions
    c := dimSS.Count;
    For i := 0 To c - 1 Do
        dimS := dimSS.Item(i);
        dimS.SelectAll;
    End For;
    // Calculate cube output matrix
    matr := destInst.Execute(DimSS);
    // Reyurn obtained matrix
    Return matr;
End Function GetCubeMatrix;
import ctypes
from foresight.cubes import *
from foresight.dimensions import *
from foresight.matrix import *
from foresight.metabase import *
def GetCubeMatrix(mdesc):
    # Open cube
    cube = ICubeInstance(mdesc.Open(None ))
    # Get cube display version instance
    destInst = ICubeInstanceDestination(cube.get_Destinations().get_DefaultDestination())
    # Create selection
    dimSS = IDimSelectionSet(destInst.CreateDimSelectionSet())
    # Select all elements in all dimensions
    c = dimSS.get_Count();
    for i in range(c):
        dimS = dimSS.get_Item(i)
        dimS.SelectAll()
    # Calculate cube output matrix
    matr = IMatrix(destInst.Execute(dimSS, ctypes.c_uint(-1).value))
    # Return obtained matrix
    return matr;

See also:

Using Foresight Analytics Platform Resources in Third-Party Applications