1 External Python Code Samples
The following well-documented samples all use the originpro package for interacting with Origin via External Python.
The main difference between using External Python and the Embedded Python interpreter is the addition of this "wrapper" code for External Python:
import originpro as op
# Ensures that the Origin instance gets shut down properly.
import sys
def origin_shutdown_exception_hook(exctype, value, traceback):
op.exit()
sys.__excepthook__(exctype, value, traceback)
if op and op.oext:
sys.excepthook = origin_shutdown_exception_hook
# Set Origin instance visibility.
if op.oext:
op.set_show(True)
# YOUR CODE HERE
# Exit running instance of Origin.
if op.oext:
op.exit()
For reference, API documentation is available via the Python originpro Reference.
| If you ultimately want to hide Origin as part of your script, it is suggested that, during development, you first launch Origin as visible (see Samples below for how to do this). During development, if you have errors in your script, Origin is not always able to shutdown. By developing with Origin visible, it will be much easier to detect this and manually shut down Origin.
|
Sample #1
A sample to illustrate the basics of using the originpro package. It highlights:
- Required additions for external Python.
- Opening an existing project and reading data.
- Writing data to a new project.
import originpro as op
import numpy as np
import pandas as pd
# Very useful, especially during development, when you are
# liable to have a few uncaught exceptions.
# Ensures that the Origin instance gets shut down properly.
# Note: only applicable to external Python.
import sys
def origin_shutdown_exception_hook(exctype, value, traceback):
'''Ensures Origin gets shut down if an uncaught exception'''
op.exit()
sys.__excepthook__(exctype, value, traceback)
if op and op.oext:
sys.excepthook = origin_shutdown_exception_hook
# Set Origin instance visibility.
# Important for only external Python.
# Should not be used with embedded Python.
if op.oext:
op.set_show(True)
# Example of opening a project and reading data.
# We'll open the Tutorial Data.opju project that ships with Origin.
src_opju = op.path('e')+ r'Samples\Tutorial Data.opju'
op.open(file = src_opju, readonly = True)
# Simple syntax to find a worksheet.
src_wks = op.find_sheet('w', 'Book1A')
# Pull first column data into a list and dump to screen.
lst = src_wks.to_list(0)
print(*lst, sep = ", ")
# Pull entire worksheet into a pandas DataFrame and partially dump to screen.
# Column long name will be columns name.
df = src_wks.to_df()
print(df.head())
# Start a new project which closes the previous one.
op.new()
#Examples of writing data to a project and saving it.
# We'll reuse the data objects we previously created.
# Simple syntax to create a new workbook with one sheet
dest_wks = op.new_sheet('w')
# Insert list data into columns 1
dest_wks.from_list(0, lst)
# Add another sheet top above workbook and add the DataFrame data.
# DataFrame column names with be Origin column Long Names.
dest_wks.get_book().add_sheet().from_df(df)
# Save the opju to your UFF.
op.save(op.path('u')+ 'Ext Python Example 1.opju')
# Exit running instance of Origin.
# Required for external Python but don't use with embedded Python.
if op.oext:
op.exit()
Sample #2
A practical example illustrates batch processing of datasets using an analysis template and exporting result graphs.
import originpro as op
import os
import re
# Very useful, especially during development, when you are
# liable to have a few uncaught exceptions.
# Ensures that the Origin instance gets shut down properly.
# Note: only applicable to external Python.
import sys
def origin_shutdown_exception_hook(exctype, value, traceback):
'''Ensures Origin gets shut down if an uncaught exception'''
op.exit()
sys.__excepthook__(exctype, value, traceback)
if op and op.oext:
sys.excepthook = origin_shutdown_exception_hook
# Set Origin instance visibility.
# Important for only external Python.
# Should not be used with embedded Python.
if op.oext:
op.set_show(True)
# Load analysis template book that ships with Origin.
at = op.load_book(op.path('e') + r'Samples\Batch Processing\Sensor Analysis.ogwu')
# Get 1st worksheet in book.
wks = at[0]
# Get folder for data files that ship with Origin.
data_folder = op.path('e') + r'Samples\Curve Fitting'
# Iterate data file folder for file names to import.
for file in os.listdir(data_folder):
# Filter for specific data files.
if re.search('^Sensor[0-9]{2}.dat$', file):
# Full path to file to import.
imp_file = os.path.join(data_folder, file)
# Import the file into the worksheet and removing the Data Connector.
wks.from_file(imp_file, False)
# Wait for analysis operation to complete.
op.wait()
# Wait a bit more for the graph to update.
op.wait('s', 0.1)
# Get the graph in the analysis template.
gp = op.find_graph('Graph2')
# Build a path to the file to export the graph to.
exp_file = os.path.join(op.path('u'), os.path.splitext(file)[0] + '.png')
# Export the graph and print the full path to the exported file.
gp.save_fig(exp_file, width=800)
print(f'Graph exported: {exp_file}')
# Exit running instance of Origin.
# Required for external Python but don't use with embedded Python.
if op.oext:
op.exit()
Sample #3
This sample illustrates setting book, sheet, and columns properties.
import originpro as op
import pandas as pd
# Very useful, especially during development, when you are
# liable to have a few uncaught exceptions.
# Ensures that the Origin instance gets shut down properly.
# Note: only applicable to external Python.
import sys
def origin_shutdown_exception_hook(exctype, value, traceback):
'''Ensures Origin gets shut down if an uncaught exception'''
op.exit()
sys.__excepthook__(exctype, value, traceback)
if op and op.oext:
sys.excepthook = origin_shutdown_exception_hook
# Set Origin instance visibility.
# Important for only external Python.
# Should not be used with embedded Python.
if op.oext:
op.set_show(True)
# Create a new workbook containing by default 1 sheet with 2 columns.
book = op.new_book('w')
# Set book long name.
book.lname = 'Experimental Data'
# Get 1st sheet from book.
wks_1 = book[0]
# Set sheet short name.
wks_1.name = 'Data'
# Work at column-level.
# 1st column: set column data, label rows, and designation at one time at one time.
# Use column index to identify target column.
wks_1.from_list(0, [1,2,3,4,5], lname ='Time', units = '(sec)', comments = 'Expended time', axis = 'X')
# 2nd column: set data and properties separately.
# Use column short name to identify target column.
wks_1.from_list('B', [5.7,6.8,7.2,9.9,11.3])
wks_1.set_label('B', val='Intensity', type = 'L')
wks_1.set_label('B', 'arb. units' 'U')
wks_1.set_label('B', 'After correction', 'C')
wks_1.cols_axis('Y', c1 = 'B')
# Add a new column, setting data and properties.
# Using an out of range index adds the column.
wks_1.from_list(2, [0.1,0.15,0.1,0.2,0.125], lname ='Error', axis = 'E')
# Add a new sheet to the book, setting it's short name. Don't activate.
wks_2 = book.add_sheet('Addl Data', active = False)
# Set which label rows to display.
wks_2.header_rows('L')
# Use a dataframe to fill the sheet.
# Uses DataFrame column names as Origin column Long Name.
df = pd.DataFrame({'Time': [1,2,3,4,5],'Dataset 1': [0, 100.3, 210.7, 343, 4.56],'Dataset 2': [1, 107, 211.3, 307.8, 445]})
wks_2.from_df(df)
# Set designations to XYY.
wks_2.cols_axis('XYY')
# Save the opju to your UFF.
op.save(op.path('u')+ 'Ext Python Example 3.opju')
# Exit running instance of Origin.
# Required for external Python but don't use with embedded Python.
if op.oext:
op.exit()
Sample #4
This sample illustrates plotting into a graph template.
import originpro as op
import numpy as np
# Very useful, especially during development, when you are
# liable to have a few uncaught exceptions.
# Ensures that the Origin instance gets shut down properly.
# Note: only applicable to external Python.
import sys
def origin_shutdown_exception_hook(exctype, value, traceback):
'''Ensures Origin gets shut down if an uncaught exception'''
op.exit()
sys.__excepthook__(exctype, value, traceback)
if op and op.oext:
sys.excepthook = origin_shutdown_exception_hook
# Set Origin instance visibility.
# Important for only external Python.
# Should not be used with embedded Python.
if op.oext:
op.set_show(True)
# Example of plotting into a graph template.
# Generate some data.
arr_x = np.arange(100)
arr_y1 = np.random.exponential(scale=2, size=100)
arr_y2 = np.random.exponential(scale=3, size=100)
# Create a new book with sheet and add generated data.
wks = op.new_sheet()
wks.from_list(0, arr_x, lname='X Values')
wks.from_list(1, arr_y1, lname='Y1 Values')
wks.from_list(2, arr_y2, lname='Y2 Values')
# Create a new graph object based on a graph template.
# Provide path to the template. We'll use a built-in
# one but you can certainly use your own!
gr = op.new_graph(template=op.path('e') + 'doubley.otp')
# Add plots with data from worksheet to layer 1 and layer 2
# and then rescale.
gl_1 = gr[0]
p1 = gl_1.add_plot(wks, coly='B', colx='A', type=202) # X is col A, Y is col B. 202 is Line + Symbol.
p1.color = '#335eff'
gl_1.rescale()
gl_2 = gr[1]
p2 = gl_2.add_plot(wks, 'C', 'A', type=202) # X is col A, Y is col C. 202 is Line + Symbol.
p2.color = '#ff5833'
gl_2.rescale()
# Save the opju to your UFF.
op.save(op.path('u')+ 'Ext Python Example 4.opju')
# Exit running instance of Origin.
# Required for external Python but don't use with embedded Python.
if op.oext:
op.exit()
Sample #5
This example plots whole sheet as XY plot and control plots in group
import os
import originpro as op
# Very useful, especially during development, when you are
# liable to have a few uncaught exceptions.
# Ensures that the Origin instance gets shut down properly.
# Note: only applicable to external Python.
import sys
def origin_shutdown_exception_hook(exctype, value, traceback):
'''Ensures Origin gets shut down if an uncaught exception'''
op.exit()
sys.__excepthook__(exctype, value, traceback)
if op and op.oext:
sys.excepthook = origin_shutdown_exception_hook
# Set Origin instance visibility.
# Important for only external Python.
# Should not be used with embedded Python.
if op.oext:
op.set_show(True)
wks = op.new_sheet()
wks.from_file(os.path.join(op.path('e'), 'Samples', 'Graphing', 'Group.dat'))
graph = op.new_graph(template='scatter')
gl=graph[0]
# plot whole sheet as XY plot
plot = gl.add_plot(f'{wks.lt_range()}!(?,1:end)')
# group the plots and control plots setting in group
gl.group()
plot.colormap = 'Candy'
plot.shapelist = [3, 2, 1]
gl.rescale()
# Exit running instance of Origin.
# Required for external Python but don't use with embedded Python.
if op.oext:
op.exit()
|