# 1.17 Calling Python Functions from Origin C

Python functions can be called from Origin C using the syntax

Python.function_name(arg1, arg2...)

By default the .py file should be placed in the same folder as the C/CPP or XF file. The name of the file should be origin.py.

Example - Python Function to perform Bayesian regression:

import numpy as np
import pandas as pd
import originpro as op
from sklearn import linear_model

def bayesian(vX, vY):
blr = linear_model.BayesianRidge(tol=1e-6, fit_intercept=True, compute_score=False, alpha_init=1, lambda_init=1e-3)
blr.fit(np.vander(vX, 10), vY)
mean = blr.predict(np.vander(vX, 10))
return mean

The function can then be called from OC code:

void bayesian_reg()
{
// Have a worksheet active, with three columns
// Columns 1 and 2 have the X and Y data for fitting
// Column 3 will have the fit curve result
Worksheet wks=Project.ActiveLayer();
Dataset dsx, dsy, dsypred;
dsx.Attach(wks, 0);
dsy.Attach(wks, 1);
dsypred.Attach(wks, 2);

dsypred = Python.bayesian(dsx, dsy);
}

Multiple variables can be returned from Python function through arguments. & sign before the argument name indicates it's a returned variable.

Python.function_name(arg1, arg2..., & ret1, & ret2...)

Example - Python Function to perform Bayesian regression to return both fitted values and fitted errors:

import numpy as np
import pandas as pd
import originpro as op
from sklearn import linear_model

def bayesian(vX, vY, vYmean, vYstd):
blr = linear_model.BayesianRidge(tol=1e-6, fit_intercept=True, compute_score=False, alpha_init=1, lambda_init=1e-3)
blr.fit(np.vander(vX, 10), vY)
mean, std = blr.predict(np.vander(vX, 10), return_std=True)
vYmean[:] = mean # pass mean values to variable vYmean
vYstd[:] = std  # pass error values to variable vYstd

The function can then be called from OC code:

void bayesian_reg()
{
// Have a worksheet active, with four columns
// Columns 1 and 2 have the X and Y data for fitting
// Column 3 and column 4 will have the fit curve result, and fitted error.
Worksheet wks=Project.ActiveLayer();
Dataset dsx, dsy, dsypred, dsystd;
dsx.Attach(wks, 0);
dsy.Attach(wks, 1);
dsypred.Attach(wks, 2);
dsystd.Attach(wks, 3);
vector vYmean, vYstd;
Python.bayesian(dsx, dsy, &vYmean, &vYstd);
dsypred = vYmean;
dsystd = vYstd;
}

To change the file location, you can set the LabTalk Python object property: Python.OCWD$to the full path of the desired folder (the working directory). To change the file name, you can set the LabTalk Python object property: Python.OCWF$ to the name of the desired Python file in the working directory.