8 Code Examples using originpro package



Introduction

Several Python code samples are provided in this page. To try the samples, the easiest way is to do the following:

  1. From Origin, select the menu Connectivity > Open untitled.py.... This will open Code Builder with a file named untitled.py
  2. Simply copy the code from each sample and then paste (to replace previous code etc)
  3. Press F5 to run. You do not need to save the file before running.

Note that several examples require Python packages to be installed first. Use the script command provided to install the package, then copy the sample code to the Python IDE in Code Builder to run.

Worksheet Data

For functions like new_sheet, see project.py.

For from_list, see worksheet

Putting Data to Columns

import originpro as op
data=[x/10. for x in range(50)]
wks=op.new_sheet()
wks.from_list('A',data, 'time', 'sec',axis='N')
data1=[x*1.5 for x in range(50)]
wks.from_list('B', data1, axis='X')
wks.cols=3
wks.from_list(2, [sum(i) for i in zip(data, data1)], comments = 'A+B')

Import Data

import originpro as op
f=op.path('e')+r'Samples\Curve Fitting\Enzyme.dat'
#assume active worksheet
wks=op.find_sheet()
wks.from_file(f)
print(wks.shape)

DataFrame and Column Format

DataFrame allows both column names and column data format, like categorical, or date-time. With originpro, it is just a matter of calling from_df and to_df.

Make sure you've installed pandas before trying the following sample. To install the module, open the Script Window (Shift+Alt+3), type the following and press Enter:

pip install pandas

The following will check and install:

pip -chk pandas
import originpro as op
import pandas as pd
df = pd.DataFrame({
    'Date': ['10/25/2018','02/21/2019','04/01/2020'],
    'Gender':['Male','Male','Female'],
    'Score': [75.5, 86.7, 91],
})

df['Date'] = pd.to_datetime(df['Date'])
df['Gender']= pd.Categorical(df['Gender'])

wks=op.new_sheet()
wks.from_df(df)
#can also create book and get first sheet like this
wks2=op.new_book('w', 'Copy using DF')[0]
#column formats like date is automatically handled
df1=wks.to_df()
wks2.from_df(df1)

Split Dataset to Training and Testing Data

This example splits a dataset with multiple columns to two datasets named Train and Test, using the package sklearn. To check for and install if needed, open the Script Window (Shift+Alt+3), type the following and press Enter.

pip -chk pandas sklearn

This example will import one of our sample datasets and randomly split it into training and testing datasets.

import numpy as np
import pandas as pd
import originpro as op
from sklearn.model_selection import train_test_split


# Import data and get the independent and dependent data to X and y respectively
ws=op.new_sheet()
ws.from_file(fname=op.path('e')+r"Samples\Statistics\Fisher's Iris Data.dat", keep_DC=False)
X = ws.to_df(c1=0, numcols=4)  # Get first 4 columns as X
y = ws.to_df(c1=4, numcols=1)  # Get the last column as y

# Split the dataset into train and test datasets
# train dataset contains 70% samples, and test dataset contains 30% samples
# shuffle the data before splitting
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, shuffle=True, random_state=1)

# Create worksheet for the splitted datasets
wks = op.new_sheet('w', 'Split')
Num = X_train.columns.shape[0]
wks.from_list(Num, y_train.iloc[:, 0].tolist(), comments='Train', lname=y_train.columns[0])
wks.from_list(Num*2+1, y_test.iloc[:, 0].tolist(), comments='Test', lname=y_train.columns[0])
for idx in range(Num):
	wks.from_list(idx, X_train.iloc[:, idx].tolist(), comments='Train', lname=X_train.columns[idx])
	wks.from_list(Num+1+idx, X_test.iloc[:, idx].tolist(), comments='Test', lname=X_train.columns[idx])

Matrix Data Manipulation

An Origin matrix sheet can hold multiple matrix objects, which are all 2D arrays of the same shape, so a matrix sheet can hold a 3D array. This section we focus on data transfer between Origin Matrix Sheet with NumPy arrays. To read more, see matrix.py

Matrix Dot Product using numpy

This sample uses NumPy. Since Pandas includes NumPy, and you need it sooner or later, best to just install Pandas. So to check for and install if needed, open the Script Window (Shift+Alt+3), type the following and press Enter:

pip -chk pandas

This sample shows basic data transfer between Origin matrix and a NumPy array.

#create 3 matrix sheets so m3 = m1*m2
import numpy as np
import originpro as op
#integer matrix data
aa = np.array([	[1, 2, 3], [4, 5, 6] ])
bb = np.array([	[10,11], [20,21], [30,31] ])
#create a new hidden matrix book, and get the matrix sheet
ma=op.new_sheet('m')
#matrix sheet can hold a 3D array, shape and data type is automatically set 
ma.from_np(aa)
#another sheet in same book
mb = ma.get_book().add_sheet()
mb.from_np(bb)

#put result into 3rd sheet
mc = ma.get_book().add_sheet('Dot Product')
#do the actual calculation using numpy
#here each sheet has only one matrix object, so we get it as 2d array
cc = np.dot(ma.to_np2d(), mb.to_np2d())
mc.from_np(cc)

Use OpenCV to Load TIFF Images into Matrix Sheet

To install openCV (cv2), do the following from Script Window

pip install opencv-python

This example shows how to import tif images into a 3d numpy array and then pass into Origin matrix book.

import originpro as op
import numpy as np
import cv2

# import tifs into array
# Assume all images share the same dimesion
ImArray = np.array([])
for idx in range(7):
	fname = op.path('e') + f'Samples\\Image Processing and Analysis\\myocyte{idx+1}.tif'
	array = np.array(cv2.imread(fname, cv2.IMREAD_UNCHANGED))
	ImArray = np.dstack((ImArray, array)) if ImArray.size else array

# put this 3d array into Origin Matrix Sheet
ms = op.new_sheet('m')
ms.from_np(arr=ImArray, dstack=True)
ms.show_slider(True)
ms.show_image(True)

Graphing

Origin can create complex graphs. So to take full advantage of the graphing features, it is best that you prepare a project with the graphs already made and just push in new data. We have several examples of that in the Sample Projects with Attached Python Codes page.

The following samples show that originpro package has some basic support for making plots and performing simple customizations.

Line Plot with Log Scale

The following example requires certain Python packages. To check for and install if needed, open the Script Window (Shift+Alt+3), type the following and press Enter:

pip -chk scipy numpy

The following example creates a sample signal and uses this package to create a periodogram power spectral density plot.

import numpy as np
from scipy import signal
import originpro as op

fs = 10e3
N = 1e5
amp = 2*np.sqrt(2)
freq = 1234.0
noise_power = 0.001 * fs / 2
time = np.arange(N) / fs
x = amp*np.sin(2*np.pi*freq*time)
x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
f, Pxx_den = signal.periodogram(x, fs)

wks = op.new_sheet(type='w', lname='Periodogram Power Spectral')
wks.from_list(0, f, lname='Freq', units='Hz')
wks.from_list(1, Pxx_den, lname='PSD', units='V\+(2)/Hz')

graph = op.new_graph(template='line')
graph[0].yscale = 2   #log scale
graph[0].set_xlim(begin=0, end=5000, step=1000)
graph[0].set_ylim(1e-7, 1e2, 2) #step=2 in log
graph[0].label('legend').remove()
graph.set_int('aa', 1)#page.aa in LT, anti-alias -> On

plot = graph[0].add_plot(wks, coly=1, colx=0, type='line')
plot.color = '#167BB2'

Project

Export Graphs as Images from Sample Projects

Generate an image from a graph from a sample project. Please note that a file named my_py_test.png will be replaced by running this sample.

To read about save_fig, see graph.py

import originpro as op
#from Learning Center folder
op.open(op.path('c')+ r'\Graphing\Trellis Plots - Box Charts.opju')
gg=op.find_graph(0)
f=''
if gg:
    f=gg.save_fig(op.path()+'my_py_test.png',width=500)

import os
if len(f):
    os.startfile(f)

Extract Image Colors

Pick all colors from an image such as a graph from a publication. The RGB values for each color is output to a worksheet. This example requires Python package extcolors to be preinstalled.

import extcolors
import numpy as np
import originpro as op

file_path = op.file_dialog('*.png;*.jpg;*.bmp','Select an Image')
if len(file_path) ==0:
    raise ValueError('user cancel')
    
colors, pixel_count = extcolors.extract_from_path(file_path)

colors = np.array(colors)
#rgb = colors[:,0]
rgb,pixel = map(list, zip(*colors))
#print(rgb)
r = []
g = []
b = []
for row in rgb:
    r.append(row[0])
    g.append(row[1])
    b.append(row[2])
#output colors
wks = op.new_sheet()
wks.from_list(0, r)
wks.from_list(1, g)
wks.from_list(2, b)


See Also: