Python Scripting in Peak
Table of contents
The Python programming language
Scripting in Peak is done with the Python programming language www.python.org. Python is a very powerful, general purpose programming language that has been widely adopted by the scientific programming community. Most importantly for Peak, the Python numerical processing package, named 'numpy', includes a complete Linear Algebra library.
There are a lot of excellent books, on-line documentation and tutorials about Python. This document will not spend any time documenting the Python language, because there are so many resources readily available. Here are links to the official documentation and tutorial:
Peak uses Python 2.7.8, and it is this version of Peak and numpy that are available to Peak scripts. Python 2.7.8 and numpy are embedded within Peak, so it is not necessary for Peak users to install Python separately. If you want to use other Python modules/packages with Peak, such as Scientific Python (www.scipy.org), you need to install Python and the needed packages, and then import them directly into your script.
Python script 'run' function
All scripts for Peak must define a 'run' function with this function signature:
def run(listOfFiles=[], **kwargs): pass # do nothing
'listOfFiles' is the actual spectrum objects passed into the script from the User Scripts tool in Peak. **kwargs is a list of Python keyword arguments, and is not used at this time.
If the script defines 'exitAfterRun' to be True, Peak will exit after the script is done. This is useful when driving Peak from the command line or batch files.
exitAfterRun=True def run(listOfFiles=[], **kwargs): pass # do nothing
Peak command line options
Peak can be sent commands on the command line, often for the purpose of running scripts in a batch mode.
Command line options are preceded by a dash '-'. The options are: -r "scriptname.py" or "batchSequenceFilename.batch" -r "path/to/script.py" or "batchSequenceFilename.batch" -t "tool name": display this tool on startup -h if present on the command line, and only if a script or batch sequence is specified with -r, Peak is hidden while it runs the script. This is useful when 'exitAfterRun' is specified in the script file (see below) or -x is on the command line, allowing Peak to be launched by other programs to perform some task through the script, and then exit upon completion. If '-h' were not included, the user would see the Peak UI flash up on thes screen and then disappear. -o (see below) "batchAnalyisiReportFilename" -w (see below) "batchSpectrumResultFilename"" -x (see below) example: peak.exe -r "c:/path/folder/scriptfile.py". where the .py file is a python script formatted as per a user script, described in the peakScripting.html document. If the script contains the line 'exitAfterRun=True', Peak will automatically exit after the script returns. (The full path to the script is not needed if the file is located in the "C:\Users\Public\Documents\peakSpectroscopy\scripts" or "sequences" folder.) For example, here are the contents of an Peak script file, 'testExit.py': ---------------------- exitAfterRun=True def run(files=[], **kwargs): eftir.msgBox('goodbye') ---------------------- then, from the the command line, run: peak -r "testExit.py" -t toolname Start Peak with the specified tool example: Peak -t "Search Spectra" Note: the Peak 'Favorites' feature can also be used to open a specific tool when Peak is launched. -o, -w, -x These options are only used when executing a batch sequence from the command line with the '-r' option. Note: -o, -w and -x are all optional when running a batch sequence. -o specifies where to put any results generated by batch analysis steps (ie, peak picking, integration, etc) the filename extension determines the format. .csv is 'Command Separated Format. .json is JSON format. -w specifies where to save the spectrum that results from running the batch file. -x Peak will exit after the specified batch sequence is run Note: when executing a batch sequence from the command line, the name of one and only one spectral file must also be provided on the command line. You can also create a desktop shortcut for the script and have it launch automatically when Peak starts. On the windows desktop, right click on the Peak icon, and click 'Copy'. Then click 'Paste' and you will have a new shortcut named 'Copy of Peak'. Right click on this icon, and on the General tab, name the shortcut 'QCP' or whatever you like. Then click on the 'Shortcut' tab. In the "Target" field, enter this: "C:\Program Files (x86)\peakSpectroscopy\peak.exe" -r "C:\Users\Public\Documents\peakSpectroscopy\scripts\QCP_027.py" Be sure to include quote marks, which are necessary if there are spaces in the file paths. Also, the script filename is case sensitive, the command line must match exactly the name of the .py file. The 'Public' directory may be named something else on some windows systems. When you click this desktop icon, peak will start and run the script automatically.
The Spectrum class
Spectrum is a Python class which combines spectral data with properties of that data. Peak scripting operates on Spectrum objects. Given an instance of a Spectrum object, called 'spectrum', here are the most important things to know about it.
Member variable | Data type | Description |
firstX | double | The 'X' value of the first point in the spectral data array |
lastX | double | The 'X' of the last point in the spectral data array |
points | 32 bit integer | The number of points in the spectral data array |
deltaX | double | The spacing between points in the spectral data array, in 'X' units. Calculated as:(lastX-firstX)/(points-1) |
data | Array of double | The spectral data array |
title | String | Text information associated with the spectrum |
filename | String | The name of the file on disk |
xDataType | String | The 'X' units of the spectral data array |
dataType | String | The 'Y' units of the spectral data array |
xDataType is one of these values:
'cm-1' | Wavenumbers |
'nm' | Nanometers |
'um' | Micrometers (microns) |
'points' | Data points |
'raman' | Raman shift |
'?' | Arbitrary units |
yDataType is one of these values:
'abs' | Absorbance |
'trn' | Transmittance |
'sbm' | Sample singlebeam |
'rsb' | Reference (background) singlebeam |
'ifg' | Sample interferogram |
'rif' | Reference (background) singlebeam |
'refl' | Reflectance |
'logir' | Log reflectance |
'drt' | Kubelka Munk |
'counts' | Counts |
'?' | Arbitrary units |
Spectral data in peak is always evenly spaced. If an unevenly spaced array of data is read into memory, it is always interpolated to even spacing. The member variable 'deltaX' is the spacing between every point in the spectral data array. NOTE: if a script does anything to change the point spacing an a data array, deltaX must be recalculated by the scripts using this formula: deltaX = (lastX-first)/(points-1).
The eftir namespace
Python has the concept of 'namespaces', which is an abstract container that provides a context for the symbols within the namespace. This avoids name collisions with similarly names things elsewhere in a software program. In technical terms, a namespace allows disambiguation of items having the same name but contained in different namespaces.
The namespace is 'eftir' because the peak software grew out of the Essential FTIR software (eFTIR). For backwards compatibility, the namespace is still called 'eftir'.
All the internal functions that peak makes available to scripts are contained with the 'eftir' namespace, and automatically imported by peak into all users scripts before they are run. Typically, in a Python program, code modules that the script uses have to be explicitly imported into the script, but peak does this for all user scripts that are run through peak. For instance, to load a spectrum from disk into memory, there is a function named 'loadSpectrum', but to call it the script writer must refer to this function as 'eftir.loadSpectrum'.
numpy
The Python numeric library numpy is automatically imported into all peak scripts, so there is no need to explicitly import it.
Function Objects
Some of the functions available to scripting are the same as those available to the 'Batch Processor'. These functions are not just functions in the strict sense. They are 'Function Objects', that is, they are code associated with properties and data that pertain to the code. But they are also simply callable as functions. Function objects always operate on spectrum objects, and return modified spectrum objects. All function objects have these member functions:
editOptions() | Allows users to interactively edit the options associated with the function. |
Save(filename) | Save the options to a file |
Load(filename) | Load the options from a file |
optionsToDictionary() | Returns the current options setting as a Python dictionary |
Calling fft.optionsToDictionary() will return a Python dictionary of the option settings:
{'laserSamplingInterval': 1.0, 'phaseCorrection': 'mertz', 'interferogramDirection': 'Automatic Detection', 'normalizeSinglebeam': False, 'zeroFill': 1, 'firstX': 500.0, 'interferogramSymmetry': 'Automatic Detection', 'apodization': 'triangle', 'laserFrequency': 0.63299000000000005, 'lastX': 4500.0 }
Such a dictionary is useful because it can be used as 'keyword arguments' to the function itself, to modify the actions of the function, as in:
fftOptions = fft.optionsToDictionary fftOptions['apodization'] = 'boxcar' Result = eftir.fft(spectrum, fftOptions)
Much more is written about keyword arguments later in this document.
These function objects always modify a spectrum in place, and the return value of the function call is the modified spectrum. For instance, result=fft(spectrum) will modify the spectrum object in place, and return the modified object. In this case, 'result' and 'spectrum' actually are one and the same object. The reason the function objects return the spectrum object is so that functions can be chained together, as in:
result = eftir.trnToAbs(eftir.ratio(eftir.fft(eftir.scan()), reference=background))Which statement does a complete FTIR data acquisition and processing in one line of code! A table of all the 'function objects' is below.
Functions
These are straight functions, they are not function objects, and if a spectrum is passed into the function, they do not modify it, they usually so some kind of analysis on the spectrum and report on it. These functions fall into broad categories of loading/saving/collecting spectra, managing windows in Peak, and analyzing spectra and returning the results. If arguments are required as inputs to a function, they are provided as 'keyword arguments', about which more is written below.
A table of all the 'functions' is below.
Keyword Arguments
Many of the function signatures in the eftir namespace include '**kwargs'. Kwargs is a python idiom that stands for 'keyword arguments'. For instance, the function signature for 'pickPeaks' is: pickPeaks(spectrum, sens = 100, threshold = 25, interpolate=False) Where the keyword arguments are sensitivity, threshold and interpolate, with the default values as shown. Keyword arguments are usually optional, and only need to be over-ridden when the defaults are not what are needed. In this example, if you wanted to just change the threshold to fifty percent, it would be done like this:
peaks = eftir.pickPeaks(spectrum, threshold=50)Alternatively, the keyword arguments can be supplied as a python dictionary:
peaks = eftir.pickPeaks(spectrum, {'threshold':50, 'sens':90, 'interpolate':True})The reader is encouraged to read one of the beginning Python tutorials for more information about keyword arguments.
Math Operations
Spectrum objects can be inserted directly into math equations that use the fundamental operators '+', '-', '/', '*', '**', which of course are addition, subtraction, division, multiplication, and power.For instance, to multiply two spectra together, you would write:
Spectrum1 = spectrum1 * spectrum2 # (alternatively, using 'c' style notation, 'spectrum1 *= spectrum2')Which multiplies spectrum1 by spectrum2 and places the result in spectrum1.
Or, one can supply constants as operands. Here we multiply a spectrum by 2:
Spectrum1 = spectrum1 * 2 (alternatively, spectum1 *= 2)
Note: spectral arrays must be of the same length (and should usually span the same range of X units), or these operators will throw an exception. If they are not the same length, and exception will be thrown by Python. Use the 'match' function to make spectra the same size.
Note: beware of division by zero when dividing one spectrum by another. Division by zero will throw a Python exception.
Example Scripts
These scripts are installed by the setup_eftir_scripting.exe installation program:Filename | Description |
testAutoSubract.py | Sequentially subtracts H2O and CO2 from a contaminated spectrum, revealing the presence of methanol. |
testCompare.py | Load s a file from disk and uses the 'compare' function to compare it to a folder full of spectral data files, displaying the results as a table in the 'Results' tab of the User Scripts tool. |
testFFT.py | FFTs a background and sample interferogram, ratios the singlebeams, and displays the results. |
testFunctions.py | Tests every spectral manipulation function object. |
testHelpers.py | Prompts user for a list of files, displays them in a new workspace, makes copies of them , prompts the user for a directory and saves the files to that directory, then closes the workspace. |
testInputFileList.py | Displays information about the list of spectra passed to the script from the User Scripts tool. |
testMathOperations.py | Shows how to use simple math operations on spectra. |
testOptionSave.py | Shows function object edit, save, and load. |
testPrint.py | Very simple script shows how Python 'print' statements appear in the 'Output' window of the User Scripts tool. |
testReports.py | Loads a canned sample, generates a peak table, puts the table in a report, prints the report, and plots the spectrum. |
testScan.py | Prompts for which instrument to connect to, collects a background and then repeatedly collects samples while doing a noise analysis on them and placing the results into the results table. Shows how to use the data collection functions, and the progress dialog to cancel an otherwise endless loop. |
eFTIR Function Index
Function Objects
absToTrn
eftir.absToTrn ( spectrum ) Implements Absorbance to Transmittance Modifies the spectrum object in-place, and returns the modified spectrum object
atrCorrection
eftir.atrCorrection ( spectrum, **keywordAguments) Implements Advanced ATR Correction Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: angle ( In degrees ) : Floating Point Number Default Value = 45.0 Rs ( Refractive Index of Sample ) : Floating Point Number Default Value = 1.5 Rc ( Refractive Index of Crystal ) : Floating Point Number Default Value = 2.4 reflections ( Number of reflections ) : Integer number between 1 and 100 inclusive Default Value = 1 thickness ( Transmission Pathlength for result ) : Floating Point Number between 1e-08 and 1.0 inclusive Default Value = 0.0001
autoBLC
eftir.autoBLC ( spectrum, **keywordAguments) Implements Automatic Baseline Correction Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: algorithm ( The algorithm to use to correct the baseline ) : Integer index from this list [ 0 = 'Function Fit', 1 = 'GIFTS Auto-Leveling', 2 = 'airPLS' ] Default Value = 2 order ( Number of terms in the correction matrix for Function Fit only ) : Integer index from this list [ 0 = 'Offset', 1 = 'Linear', 2 = 'Quadratic', 3 = 'Quintic' ] Default Value = 1 normalize ( Offset the data min to 0 after correction ) : Boolean (true/false) value represented by 1 or 0 Default Value = False
derivative
eftir.derivative ( spectrum, **keywordAguments) Implements Derivative Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: order ( The order of the derivative, 1-4 ) : Integer number between 1 and 4 inclusive Default Value = 1 points ( The number of smoothing points, 5-99 ) : Integer number between 5 and 99 inclusive Default Value = 21 method ( How to do the smoothing ) : Integer index from this list [ 0 = 'Quadratic/Cubic Savitsky-Golay', 1 = 'Quartic/Quintic Savitsky-Golay' ] Default Value = 1 tailHandling ( How to handle the end points ) : Integer index from this list [ 0 = 'Use Closest Value', 1 = 'Fill with Zero', 2 = 'Truncate', 3 = 'Extrapolate, then Truncate' ] Default Value = 3
fft
eftir.fft ( spectrum, **keywordAguments) Implements FFT Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: apodization ( The apodization function to use in the FFT ) : String value from this list [ 'triangle', 'boxcar', 'Beer-Norton Med', 'Beer-Norton Weak', 'Beer-Norton Strong', 'Happ-Genzel', 'Bessel', 'Cosine', 'Blackman-Harris 3 Term', 'Blackman-Harris 4 Term', 'Cosine 3' ] Default Value = triangle phaseCorrection ( The phase correction method to use in the FFT ) : String value from this list [ 'mertz', 'magnitude', 'none' ] Default Value = mertz firstX ( From 0 to 31596 wavenumbers. The first wavenumber value to save in the FFT'd data ) : Floating Point Number between 0.0 and 31596.0 inclusive Default Value = 500.0 lastX ( From 0 to 31596 wavenumbers. The last wavenumber value to save in the FFT'd data ) : Floating Point Number between 0.0 and 31596.0 inclusive Default Value = 4500.0 zeroFill ( Increase the resolution of the processed data through zero-filling ) : Integer value from this list [ 1 = '1', 2 = '2', 4 = '4', 8 = '8', 16 = '16' ] Default Value = 1 laserFrequency ( The wavelength of the laser in microns (default 0.63299 for HeNe laser) ) : Floating Point Number Default Value = 0.63299 laserSamplingInterval ( How often samples are taken relative to the laser wavelength (interval of 1 = 2 zero crossings ) : Floating Point value from this list [ 0.250000,0.500000,1.000000,2.000000,4.000000,8.000000 ] Default Value = 1.0 interferogramDirection ( Is data collected during forward or reverse mirror travel? ) : String value from this list [ 'Automatic Detection', 'Forward', 'Reverse', 'Both' ] Default Value = Automatic Detection interferogramSymmetry ( When the ADC is turned on ) : String value from this list [ 'Automatic Detection', 'Single-Sided', 'Double-Sided' ] Default Value = Automatic Detection normalizeSinglebeam ( After the FFT, scale the singlebeam to normalize it ) : Boolean (true/false) value represented by 1 or 0 Default Value = 0 ifgBlcOrder ( How to correct the interferogram baseline ) : String value from this list [ 'Offset', 'Linear' ] Default Value = Offset mertzPoints ( How many interferogram points to use in Mertz Phase Correction ) : Integer value from this list [ 64 = '64', 128 = '128', 256 = '256', 512 = '512', 1024 = '1024' ] Default Value = 256 truncateInterferogram ( Limit the spectral resolution by truncating the interferogram before the FFT ) : Boolean (true/false) value represented by 1 or 0 Default Value = False truncateInterferogramPoints ( If 'Truncate the Interferogram' is checked, this many points will be used. Use the calculator to set. ) : Integer number between 512 and 65536 inclusive Default Value = 4096
interpolate
eftir.interpolate ( spectrum, **keywordAguments) Implements Interpolate Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: operation ( How to Interpolate ) : Integer index from this list [ 0 = 'Digital Spacing', 1 = 'Points' ] Default Value = 0 resolution ( The digital point spacing in the result spectrum ) : Floating Point Number between 0.0 and 100000000.0 inclusive Default Value = 1.0 points ( The number of points in the result spectrum ) : Integer number between 10 and 100000000.0 inclusive Default Value = 1801
kkTransform
eftir.kkTransform ( spectrum ) Implements Kramers-Kronig Transform Modifies the spectrum object in-place, and returns the modified spectrum object
manualBLC
eftir.manualBLC ( spectrum, **keywordAguments) Implements Manual Baseline Correction Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: calcMode ( How to use the points to create a baseline ) : String value from this list [ 'Follow Data', 'Absolute Position' ] Default Value = Follow Data baselineFit ( How to fit the baseline ) : String value from this list [ 'Straight Lines', 'Cubic Spline' ] Default Value = Straight Lines liveUpdate ( Update the display as the markers are moved ) : Boolean (true/false) value represented by 1 or 0 Default Value = True regions: List of x-values defining the regions to operate on
match
eftir.match ( spectrum, **keywordAguments) Implements Match Spectra Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: firstX ( First X value ) : Floating Point Number Default Value = 3999.97554227 lastX ( Last X value ) : Floating Point Number Default Value = 10003.7556262 deltaX ( Exact Digital resolution in cm-1 ) : Floating Point Number between 0.03 and 32.0 inclusive Default Value = 3.8167705556 match ( Match start, end cm-1 and resolution ) : unhandled input type ... Default Value = Spectra\Lactose anhydrous_01_abs.spc
normalize
eftir.normalize ( spectrum, **keywordAguments) Implements Vector Normalize Spectra Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: useRegion ( Calculate factors using the wavelength region ) : Boolean (true/false) value represented by 1 or 0 Default Value = False regions: List of x-values defining the regions to operate on
normalizeToPeak
eftir.normalizeToPeak ( spectrum, **keywordAguments) Implements Normalize To Peak Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: normalizeTo ( The peaks will be scaled to this height ) : Floating Point Number Default Value = 1.0 offsetToZero ( Offset the spectra to zero before the peak normalization ) : Boolean (true/false) value represented by 1 or 0 Default Value = True findPeak ( Search for the nearest peak, otherwise use exact value at peak position ) : Boolean (true/false) value represented by 1 or 0 Default Value = True limitSearch ( If 'Find Peak', limit the search to this many points on each side ) : Integer number between 1 and 99 inclusive Default Value = 2 regions: List of x-values defining the regions to operate on
offsetBy
eftir.offsetBy ( spectrum, **keywordAguments) Implements Offset By Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: factor ( Offset the data by this amount ) : Floating Point Number Default Value = 1.0
offsetTo
eftir.offsetTo ( spectrum, **keywordAguments) Implements Offset To Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: factor ( Offset the data so the minimum data value is this number ) : Floating Point Number Default Value = 1.0
ramanShift
eftir.ramanShift ( spectrum, **keywordAguments) Implements Raman Shift Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: freq ( In wavenumbers (cm-1) ) : Floating Point Number Default Value = 0.0
ratio
eftir.ratio ( spectrum, **keywordAguments) Implements Ratio Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: background ( Where to obtain a background spectrum for the ratio ) : unhandled input type ... Default Value = reference: This function needs a reference file (for instance, ratio needs a background and subtract needs a subtrahend) The reference may be the filename of a spectrum, or an in-memory Spectrum instance
scaleBy
eftir.scaleBy ( spectrum, **keywordAguments) Implements Scale By Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: factor ( Scale the data by this number ) : Floating Point Number Default Value = 1.0
scaleTo
eftir.scaleTo ( spectrum, **keywordAguments) Implements Scale To Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: factor ( Scale the data so this becomes the dynamic range of the data ) : Floating Point Number Default Value = 1.0
smooth
eftir.smooth ( spectrum, **keywordAguments) Implements Smoothing Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: points ( The number of smoothing points, 5-99 ) : Integer number between 5 and 99 inclusive Default Value = 25 method ( How to do the smoothing ) : Integer index from this list [ 0 = 'Quadratic/Cubic Savitsky-Golay', 1 = 'Quartic/Quintic Savitsky-Golay', 2 = 'Moving Average', 3 = 'Running Median', 4 = 'Hanning Window', 5 = 'Hamming Window' ] Default Value = 2 fullSpectrumSmooth ( Smooth the entire spectrum ) : Boolean (true/false) value represented by 1 or 0 Default Value = True tailHandling ( How to handle the end points ) : Integer index from this list [ 0 = 'Use Closest Value', 1 = 'Fill with Zero', 2 = 'Truncate', 3 = 'Extrapolate, then Truncate' ] Default Value = 0 regions: List of x-values defining the regions to operate on
subtract
eftir.subtract ( spectrum, **keywordAguments) Implements Subtract Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: factor ( Scale the subtrahend spectrum by this number ) : Floating Point Number Default Value = 1.0 reference: This function needs a reference file (for instance, ratio needs a background and subtract needs a subtrahend) The reference may be the filename of a spectrum, or an in-memory Spectrum instance
trnToAbs
eftir.trnToAbs ( spectrum ) Implements Transmittance to Absorbance Modifies the spectrum object in-place, and returns the modified spectrum object
truncate
eftir.truncate ( spectrum, **keywordAguments) Implements Truncate Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: allowExtension ( Allow Spectral Limits to be Extended. ) : Boolean (true/false) value represented by 1 or 0 Default Value = False regions: List of x-values defining the regions to operate on
wavelengthToWavenumbers
eftir.wavelengthToWavenumbers ( spectrum ) Implements Wavelengths To Wavenumbers Modifies the spectrum object in-place, and returns the modified spectrum object
wavenumbersToMicrons
eftir.wavenumbersToMicrons ( spectrum ) Implements Wavenumbers To Microns Modifies the spectrum object in-place, and returns the modified spectrum object
wavenumbersToNanometers
eftir.wavenumbersToNanometers ( spectrum ) Implements Wavenumbers To Nanometers Modifies the spectrum object in-place, and returns the modified spectrum object
xShift
eftir.xShift ( spectrum, **keywordAguments) Implements X-Axis Shift Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: amount ( The amount to shift the x axis ) : Floating Point Number Default Value = 0.0 shiftMode ( How to shift the X Axis ) : Integer index from this list [ 0 = 'Shift Entire Spectrum', 1 = 'Pin Left Side', 2 = 'Pin Right Side', 3 = 'Pin Zero' ] Default Value = 0
zap
eftir.zap ( spectrum, **keywordAguments) Implements Zap Regions Modifies the spectrum object in-place, and returns the modified spectrum object Keyword Options: fill ( What to fill zapped regions with ) : String value from this list [ 'Zero', 'Interpolated Line', 'Mean', 'Left-most value', 'Right-most value' ] Default Value = Interpolated Line noise ( Gaussian distribution expressed as standard deviation around 0 ) : Floating Point Number Default Value = 0.0 regions: List of x-values defining the regions to operate on
Functions
addSpectrumToWorkspace
eftir.addSpectrumToWorkspace(w, spectrum) Add a spectrum to workspace w.
autoscale
eftir.autoscale(w=None) Autoscale the workspace given by w. If w is not provided, use the current active workspace.
autoscaleX
eftir.autoscaleX(w=None) Autoscale the workspace given by w along the X axis. If w is not provided, use the current active workspace.
autoscaleY
eftir.autoscaleY(w=None) Autoscale the workspace given by w along the Y axis. If w is not provided, use the current active workspace.
bkgscan
eftir.bkgscan() Collect a background spectrum according to the instrument settings. See the example 'testScan.py' script.
buildBatchPipeline
eftir.buildBatchPipeline(sequenceFilename) sequenceFilename is the filename of a batch processing sequence, as created and saved in the Advanced / Batch Processor tool. The full path to sequenceFilename must be provided. The sequence is built into an executable pipeline, which is to be used with the eftir.runBatchSequence function. This function returns the pipeline for execution with the eftir.runBatchSequence function.
chkKeyboard
chkKeyboard() Waits for the user to press a key, and returns that key's scan code.
chooseFromList
eftir.chooseFromList(caption, listOfOptions, multiSelect=False) Displays a dialog box with a list of choices. 'caption' will be the title of the dialog box, it can be used as a hint to the user. 'listOfOptions' is a list of strings to display. if 'multiSelect' is False, the user may select only one item. If true, the user can select multiple items. Returns the None if the user clicks Cancel or clicks 'OK' without selecting anything, otherwise it returns the selected string (if mutliSelect is False) or a list of strings (if multiSelect is True)
cloneSpectrum
eftir.cloneSpectrum(spectrum) Returns a copy of the peakLib.
closeAllWindows
eftir.closeAllWindows() Close all workspace windows.
closeWorkspace
eftir.closeWorkspace(w) Close the workspace w.
commandLineFilenames
commandLineFilenames() Returns the list of filenames that were passed in on the command line when the program was started. Returns an empty list of there were none.
compare
eftir.compare(spectrum, path, recurse=False) calculate the correlation coefficient using the spectrum object agains all spectra found on the provided path
correlationCoefficient
eftir.correlationCoefficient(spectrum1, spectrum2) returns the correlation coefficient calculated using the two Spectrum objects
editText
eftir.editText(prompt, txt, caption="") Displays a simple dialog with a single text edit control on it. The edit control is intialized with 'txt' Returns the empty string "" if the user clicks Cancel, otherwise it returns the edited string.
errMsg
eftir.errMsg(message, caption="") Display a Windows Error Message Box with the message and caption. The Message Box has a single 'OK' button.
expand
eftir.expand(w, x1, x2, y1, y2) Expand the display in window w. If x1 equals x2, the window will be autoscaled along the x axis. If y1 equals y2, the window will be autoscaled along the y axis.
exportBatchReport
eftir.exportBatchReport(spectrum, pipeline, outputFormat, destination) Analytical results generated by a batch sequence can be formatted in various ways. 'outputFormat' can be one of ',' (comma), ';' (semicolon), ' ' (tab), or any single character. That character is used as the field delimiter for ASCII output. 'reportFilename' can have the extension .csv or .json. The results of the analysis stages in the pipeline will be written to that file.
generateBatchResultsTable
eftir.generateBatchResultsTable(spectrum, pipeline) After the runBatchSequence function is called, any analytical results generated by the pipeline can be generated into a report table. The table is a list of lists. It can be turned into a text string like this: delimiter = ',' text = " ".join([delimiter.join([str(field) for field in line]) for line in reportTable])
getBackgroundWorkspace
eftir.getBackgroundWorkspace() Return the handle of the background data collection window. (the background data collection window is the one that holds the last collected background)
getCurrentWorkspace
eftir.getCurrentWorkspace() Return the handle of the current active data workspace.
getDataCollectionWorkspace
eftir.getDataCollectionWorkspace() Get the data collection window. The data collection window holds newly collected data.
getDirectoryFromUser
eftir.getDirectoryFromUser(path) Prompt the user to select a directory. Returns the chosen directory, or the empty string if user cancels.
getDocPath
None
getDocumentsDirectory
getDocumentsDirectory() Returns the path to the program's documents directory (usually located under C:\Users\Public\Documents).
getFileFromUser
eftir.getFilesFromUser(path) Prompt the user for a single spectral data files. The dialog will be initialzed at the folder 'path' Returns the filename, or the empty string if user cancels.
getFilenameForRead
eftir.getFilenameForRead(prompt, extension=".*") Display a dialog that allows the user to select an existing file to read from. The extension is used to filter the files that are displayed in the dialog. The extension should include the period. Returns an empty string if the user cancels.
getFilenameForWrite
eftir.getFilenameForWrite(prompt, extension=".*") Display a dialog that allows the user to select a file for write. The extension is used to filter the files that are displayed and that the user may select from. The extension should include the period.
getFilesFromUser
eftir.getFilesFromUser(path) Prompt the user for multiple spectral data files. The dialog will be initialzed at the folder 'path'. Returns a list of filenames, or the empty list if user cancels.
getInstrumentSettings
eftir.getInstrumentSettings: Return the current instrument settings as a Python dictionary. This can be modified and used in the call to eftir.initializeInstrument(). This can also be used to store and restore instrument settings back to a known state. see the example 'testScan.py' script
getNumSubfiles
eftir.getNumSubfiles(filename) Returns the number of subfiles contained in the file.
getProgramDirectory
getProgramDirectory() Returns the path to the program directory (where the .exe is located).
getSpectraInWorkspace
eftir.getFilesInWorkspace(w=None) Returns a list of all the spectra held in the workspace 'w'. If 'w' is not specified, it uses the current workspace.
initializeInstrument
eftir.initializeInstrument(**kwargs) Set the instrument options to kwargs. See eftir.getInstrumentSettings. See the example 'testScan.py' script.
integrate
eftir.integrate(spectrum, startX, endX, toZero=False) Performs integration over the specified region using the so-called 'composite Simpson Rule' (see 'Numerical Algorithms in C, 2nd Ed.' page 133). if 'toZero' is True, the integration is performed using zero as the baseline, otherwise a baseline between startX and endX is used.
isKnownFile
eftir.isKnownFile(filename): Returns True if the file extension of filename is recognized by eFTIR. Otherwise it returns False.
loadInstrumentSettings
eftir.initializeInstrument(**kwargs) Set the instrument options to kwargs. See eftir.getInstrumentSettings. See the example 'testScan.py' script.
loadMultifile
eftir.loadMultifile(filename) Returns a list of all the spectra in the multifile. For instance: multfile = eftir.loadMultifile('filename)' for subfile in multifile: # do some processing on the subfile
loadSpectrum
eftir.loadSpectrum(filename, subfile=0) Loads the spectrum from disk given the filename. Returns a Spectrum object. Returns None if there was an error.
measurePeak
eftir.measurePeak(spectrum, baseline1, baseline2, peakPos, interpolate, peakSearchLimit, peaksGoUp) Calculates the Full-Width at Half-Max (FWHM) of a peak. Returns a list of [peak height, peak center, and FWHM]. baseline1 and baseline2 are the peak start and end positions. peakPos is the nominal peak position. If interpolate is True the peak position is determined using a cubic spline. Otherwise the actual data value at the peak is returned. peakSearchLimit determines how many data points to search on each side of the nominal peak position for the actual peak. if peakSearchLimit is zero, no peak search is performed. peaksGoUp is True or False, to tell the function whether 'peaks' are maxima or minima. This function returns a list of [peakHeight, peakCenter, peakFWHN ]
msgBox
eftir.msgBox(message, caption="") Display a Windows Message Box with the message and caption. The Message Box has a single 'OK' button.
msgBoxOkCancel
eftir.msgBox(message, caption="") Display a Windows Message Box with the message and caption. The Message Box has 'OK' and 'Cancel' buttons. Returns True if the user clicks OK, False if user clicks Cancel.
msgBoxYesNo
eftir.msgBox(message, caption="") Display a Windows Message Box with the message and caption. The Message Box has 'Yes' and 'No' buttons. Returns True if the user clicks Yes, False if user clicks No.
msgBoxYesNoCancel
eftir.msgBox(message, caption="") Display a Windows Message Box with the message and caption. The Message Box has 'Yes', 'No', and 'Cancel' buttons. Returns 1 if the user clicks Yes, 0 if user clicks No, or -1 for Cancel.
netA
eftir.netA(spectrum, baseline1, baseline2, peakPos) calculate the Net Absorbance of the peak at 'peakPos' to a baseline drawn between the two baseline points
newDataWorkspace
eftir.newDataWorkspace(label) Create a new data workspace (tab) and label it. Returns the window handle of the new workspace.
overlay
eftir.overlay(w=None): Display the workspace given by w in overlay mode. If w is not provided, use the current active workspace.
pagemode
eftir.pagemode(w=None): Display the workspace given by w in pagemode (active sample only) mode. If w is not provided, use the current active workspace.
peakAt
eftir.peakAt(spectrum, wavenumber) peakAt searches for a peak, as defined by 5 point window with the middle point greater than the 2 on each side. It assumes that (1) wavenumber is close to the peak position, and (2)the data is not very noisy, otherwise it could be thrown off by random noise.
pickPeaks
eftir.pickPeaks(spec, sens = 100, threshold = 25, interpolate=False, xLimits=None) returns a table of peaks as a list of lists threshold is expressed as percent of full height. if interpolate is True, the peak position is determined using a cubic spline centered around the nominal peak position.
plot
eftir.plot(workspace, quickPrint = True) Print the workspace given by w. If workspace is None, use the current active workspace. if quickPrint is False, the plot layout dialog is presented using the default plot layout, and populated with the data from the workspace. If quickPrint is True, the data in the workspace is printed using the default plot layout and the default Windows printer.
processUIEvents
eftir.processUIEvents() Give the eFTIR user interface the chance to update itself. This is useful in tight loops that use a progress dialog. See the 'testProgressDialog.py' example
progressDialog
eftir.progressDialog(prompt, steps) Display the a progress dialog. Created, displays, and returns a progress dialog. The progress dialog has these member functions: setLabelText(text) setProgress(progress) # progress is an integer between 0 and the 'steps' passed in when the progress dialog was created. wasCanceled() # user clicked the 'cancel' button close() # close the progress dialog. NOTE: It is the programmers responsibility to call .close() on the progress dialog when the script is done with it. NOTE: To make sure the progress dialog is updated during tight processing loops, call eftir.processUIEvents() example: See the testProgressDialog example script.
raiseWorkspace
eftir.raiseWorkspace(w) Make the workspace w the active one.
redraw
eftir.redraw(w=None) If w is not provided, use the current active workspace.
removeSpectrum
eftir.removeSpectrum(spectrum) Removes the spectrum from memory.
removeSpectrumFromWorkspace
eftir.removeFileFromWorkspace(w, spectrum) Remove the spectrum object from the window w.
report
eftir.report(data, printit = True) Puts data in the 'Results' table in the user script tool in eFTIR. 'data' is a list of lists. Each list in the list of lists becomes a row in the results table. Each element in a row becomes a column. The list elements can be strings or numbers. For instance: [["Wavenumbers", "Absorbance"], [3000, 1.5] ]
rmsNoise
eftir.rmsNoise(spectrum, startX, endX) Calculate the Root Mean Square Noise of the spectrum between the two X values. In Mid-IR spectroscopy, the region used for noise analysis is usually 2000 to 2200 wavenumbers.
runBatchSequence
eftir.runBatchSequence(spectrum, pipeline) Pipeline is batch processing sequence create using the eftir.buildBatchPipeline function The pipeline is executed using the spectrum passed in. The modified spectrum is returned. If the batch sequence contains Analysis stages, the eftir.generateBatchResultsTable function can be used to create a report from the results. This also works with command line arguments for automation. If -o "reportFilename" is specified on the command line, and analysis stages are included in the pipeline, the analysis report will be written to the file. If -w "spectrumFilename" is specified on the command line, the result spectrum will be written to the file.
saveASCII
eftir.saveASCII(spectrum, filename, digits=6, delimiter=',') Saves the spectrum in ASCII format. 'digits' specifies the number of digits to the right of the decimal point. Delimiter specifies the character which separates the x,y pairs. returns true/false
saveFile
eftir.saveFile(spectrum, filename) Saves the spectrum in the file.
saveJCAMP
eftir.saveJCAMP(spectrum, filename) Saves the spectrum in JCAMP-DX format. Returns true/false.
savePE
eftir.savePE(spectrum, filename) Saves the spectrum in Perkin-Elmer .SP ASCII format. Returns true/false
scan
eftir.scan() Collect a sample spectrum according to the instrument settings. See the example 'testScan.py' script.
setInstrument
eftir.setInstrument(name) Tells the program which instrument to use. Each instrument has a unique name that is part of the data collection plugin for that intrument. The instrument settings are set to the defaults, which are those showing in the eFTIR user interface. See the example 'testScan.py' script.
setTitle
eftir.setTitle(spectrum, newTitle) Sets the spectrum's title to newTitle and updates the display to reflect the change.
showSpectrum
eftir.showSpectrum(spectrum, show) If 'show' is True, the spectrum is made visible. If 'show' is False, the spectrum is made not visible.
stack
eftir.stack(w=None): Display the workspace given by w in stack mode. If w is not provided, use the current active workspace.
superimpose
eftir.superimpose(w=None): Display the workspace given by w in superimpose mode. If w is not provided, use the current active workspace.
trace
eftir.trace(text) Print the text in the 'Trace' window in the user script tool in eFTIR.
undo
eftir.undo(spectrum) Undoes the last operation performed on the peakLib.
waitMsgBox
eftir.waitMsgBox(message, caption="Please Wait...") Display a modeless Windows Message Box with the message and caption. It returns the message box object. The script must call accept() on the object to make the message disappear. For example: d = waitMsgBox("Wait for this...") .... do some actions here... d.accept() See 'progressDialog' also.