Scripting in Peak

Table of contents

The Python language
Python scripts in Peak
The Peak command line
The Spectrum class
The eftir namespace
The Python numeric library
Function Objects
Functions
Keyword Arguments
Math Operations
Example Scripts
Index to Functions and Function Objects
List of Function Objects
List of Functions

Python

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.6.6 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 Scripts in Peak

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"
  -t "tool name": 
  -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 "batchAnalyisiReportFilename" 
  -w "batchSpectrumResultFilename""
  -x 

-r "path/to/script.py" or "batchSequenceFilename.batch"

  example: epeak.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 variableData typeDescription
firstXdoubleThe 'X' value of the first point in the spectral data array
lastXdoubleThe 'X' of the last point in the spectral data array
points32 bit integerThe number of points in the spectral data array
deltaXdoubleThe spacing between points in the spectral data array, in 'X' units. Calculated as:(lastX-firstX)/(points-1)
dataArray of doubleThe spectral data array
titleStringText information associated with the spectrum
filenameStringThe name of the file on disk
xDataTypeStringThe 'X' units of the spectral data array
dataTypeStringThe '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:
FilenameDescription
testAutoSubract.pySequentially subtracts H2O and CO2 from a contaminated spectrum, revealing the presence of methanol.
testCompare.pyLoad 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.pyFFTs a background and sample interferogram, ratios the singlebeams, and displays the results.
testFunctions.pyTests every spectral manipulation function object.
testHelpers.pyPrompts 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.pyDisplays information about the list of spectra passed to the script from the User Scripts tool.
testMathOperations.pyShows how to use simple math operations on spectra.
testOptionSave.pyShows function object edit, save, and load.
testPrint.pyVery simple script shows how Python 'print' statements appear in the 'Output' window of the User Scripts tool.
testReports.pyLoads a canned sample, generates a peak table, puts the table in a report, prints the report, and plots the spectrum.
testScan.pyPrompts 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

absToTrn addSpectrumToWorkspace atrCorrection autoBLC
autoscale autoscaleX autoscaleY bkgscan
buildBatchPipeline chkKeyboard chooseFromList cloneSpectrum
closeAllWindows closeWorkspace commandLineFilenames compare
correlationCoefficient derivative editText errMsg
expand exportBatchReport fft fileConverter
generateBatchResultsTable getBackgroundWorkspace getCurrentWorkspace getDataCollectionWorkspace
getDirectoryFromUser getDocPath getDocumentsDirectory getFileFromUser
getFilenameForRead getFilenameForWrite getFilesFromUser getInstrumentSettings
getNumSubfiles getProgramDirectory getSpectraInWorkspace initializeInstrument
integrate interpolate isKnownFile kkTransform
loadInstrumentSettings loadSpectrum manualBLC match
measurePeak msgBox msgBoxOkCancel msgBoxYesNo
msgBoxYesNoCancel netA newDataWorkspace normalize
normalizeToPeak offsetBy offsetTo overlay
pagemode peakAt pickPeaks plot
processUIEvents progressDialog raiseWorkspace ramanShift
ratio redraw removeSpectrum removeSpectrumFromWorkspace
report rmsNoise runBatchSequence saveASCII
saveFile saveJCAMP saveMeter savePE
scaleBy scaleTo scan setInstrument
setTitle showSpectrum smooth stack
subtract superimpose trace trnToAbs
truncate undo waitMsgBox wavelengthToWavenumbers
wavenumbersToMicrons wavenumbersToNanometers xShift zap

Function Objects


absToTrn


   eftir.absToTrn ( spectrum )
   Implements  Absorbance to Transmittance
   Modifies the spectrum object in-place, and returns the modified spectrum object
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


kkTransform


   eftir.kkTransform ( spectrum )
   Implements  Kramers-Kronig Transform
   Modifies the spectrum object in-place, and returns the modified spectrum object
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index


trnToAbs


   eftir.trnToAbs ( spectrum )
   Implements  Transmittance to Absorbance
   Modifies the spectrum object in-place, and returns the modified spectrum object
  

Back To Function Index


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
  

Back To Function Index


wavelengthToWavenumbers


   eftir.wavelengthToWavenumbers ( spectrum )
   Implements  Wavelengths To Wavenumbers
   Modifies the spectrum object in-place, and returns the modified spectrum object
  

Back To Function Index


wavenumbersToMicrons


   eftir.wavenumbersToMicrons ( spectrum )
   Implements  Wavenumbers To Microns
   Modifies the spectrum object in-place, and returns the modified spectrum object
  

Back To Function Index


wavenumbersToNanometers


   eftir.wavenumbersToNanometers ( spectrum )
   Implements  Wavenumbers To Nanometers
   Modifies the spectrum object in-place, and returns the modified spectrum object
  

Back To Function Index


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
  

Back To Function Index


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
  

Back To Function Index

Functions


addSpectrumToWorkspace


    eftir.addSpectrumToWorkspace(w, spectrum)
      Add a spectrum to workspace w.
    

Back To Function Index


autoscale


    eftir.autoscale(w=None)
      Autoscale the workspace given by w.
      If w is not provided, use the current active workspace.
    

Back To Function Index


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.
    

Back To Function Index


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.
    

Back To Function Index


bkgscan


    eftir.bkgscan()
      Collect a background spectrum according to the instrument settings.
      See the example 'testScan.py' script.
    

Back To Function Index


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.
    

Back To Function Index


chkKeyboard


    chkKeyboard()
    Waits for the user to press a key, and returns that key's scan code.
    

Back To Function Index


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) 
    

Back To Function Index


cloneSpectrum


    eftir.cloneSpectrum(spectrum)
      Returns a copy of the peakLib.
    

Back To Function Index


closeAllWindows


    eftir.closeAllWindows()
     Close all workspace windows.
    

Back To Function Index


closeWorkspace


    eftir.closeWorkspace(w)
      Close the workspace w.
    

Back To Function Index


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.
    

Back To Function Index


compare


    eftir.compare(spectrum, path, recurse=False)
    calculate the correlation coefficient using the spectrum object agains all spectra found on the provided path
    

Back To Function Index


correlationCoefficient


    eftir.correlationCoefficient(spectrum1, spectrum2)
    returns the correlation coefficient calculated using the two Spectrum objects
    

Back To Function Index


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.
    

Back To Function Index


errMsg


    eftir.errMsg(message, caption="")
    Display a Windows Error Message Box with the message and caption.
    The Message Box has a single 'OK' button.
    

Back To Function Index


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.
    

Back To Function Index


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.
    

Back To Function Index


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])
    

Back To Function Index


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)
    

Back To Function Index


getCurrentWorkspace


    eftir.getCurrentWorkspace()
    Return the handle of the current active data workspace.
    

Back To Function Index


getDataCollectionWorkspace


    eftir.getDataCollectionWorkspace()
      Get the data collection window.
      The data collection window holds newly collected data.
    

Back To Function Index


getDirectoryFromUser


    eftir.getDirectoryFromUser(path)
      Prompt the user to select a directory.
      Returns the chosen directory, or the empty string if user cancels.

    

Back To Function Index


getDocPath

None

Back To Function Index


getDocumentsDirectory


    getDocumentsDirectory()
    Returns the path to the program's documents directory (usually located under C:\Users\Public\Documents).
    

Back To Function Index


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.
    

Back To Function Index


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.
    

Back To Function Index


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.
    

Back To Function Index


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.
    

Back To Function Index


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
    

Back To Function Index


getNumSubfiles


    eftir.getNumSubfiles(filename)
    Returns the number of subfiles contained in the file.
    

Back To Function Index


getProgramDirectory


    getProgramDirectory()
    Returns the path to the program directory (where the .exe is located).
    

Back To Function Index


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.
    

Back To Function Index


initializeInstrument


    eftir.initializeInstrument(**kwargs)
      Set the instrument options to kwargs.
      See eftir.getInstrumentSettings.
      See the example 'testScan.py' script.
    

Back To Function Index


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.
    

Back To Function Index


isKnownFile


    eftir.isKnownFile(filename):
    Returns True if the file extension of filename is recognized by eFTIR.
    Otherwise it returns False.
    

Back To Function Index


loadInstrumentSettings


    eftir.initializeInstrument(**kwargs)
      Set the instrument options to kwargs.
      See eftir.getInstrumentSettings.
      See the example 'testScan.py' script.
    

Back To Function Index


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.
    

Back To Function Index


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 ]
  

Back To Function Index


msgBox


    eftir.msgBox(message, caption="")
    Display a Windows Message Box with the message and caption.
    The Message Box has a single 'OK' button.
    

Back To Function Index


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.
    

Back To Function Index


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.
    

Back To Function Index


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.
    

Back To Function Index


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
    

Back To Function Index


newDataWorkspace


    eftir.newDataWorkspace(label)
      Create a new data workspace (tab) and label it.
      Returns the window handle of the new workspace.
    

Back To Function Index


overlay


    eftir.overlay(w=None):
      Display the workspace  given by w in overlay mode.
      If w is not provided, use the current active workspace.
    

Back To Function Index


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.
    

Back To Function Index


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.
    

Back To Function Index


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.

    

Back To Function Index


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. 
    

Back To Function Index


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
    

Back To Function Index


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.
    

Back To Function Index


raiseWorkspace


    eftir.raiseWorkspace(w)
      Make the workspace w the active one.
    

Back To Function Index


redraw


    eftir.redraw(w=None)
      If w is not provided, use the current active workspace.
    

Back To Function Index


removeSpectrum


    eftir.removeSpectrum(spectrum)
      Removes the spectrum from memory.
    

Back To Function Index


removeSpectrumFromWorkspace


    eftir.removeFileFromWorkspace(w, spectrum)
      Remove the spectrum object from the window w.
    

Back To Function Index


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]
    ]
    

Back To Function Index


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.
    

Back To Function Index


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.
    

Back To Function Index


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
    

Back To Function Index


saveFile


    eftir.saveFile(spectrum, filename)
      Saves the spectrum  in the file.
    

Back To Function Index


saveJCAMP


    eftir.saveJCAMP(spectrum, filename)
      Saves the spectrum in JCAMP-DX format.
    Returns true/false.
    

Back To Function Index


savePE


    eftir.savePE(spectrum, filename)
      Saves the spectrum in Perkin-Elmer .SP ASCII format.
    Returns true/false
    

Back To Function Index


scan


    eftir.scan()
      Collect a sample spectrum according to the instrument settings.
      See the example 'testScan.py' script.
    

Back To Function Index


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.
    

Back To Function Index


setTitle


    eftir.setTitle(spectrum, newTitle)
        Sets the spectrum's title to newTitle and updates the display to reflect the change.
    

Back To Function Index


showSpectrum


    eftir.showSpectrum(spectrum, show)
        If 'show' is True, the spectrum is made visible.
        If 'show' is False, the spectrum is made not visible.
    

Back To Function Index


stack


    eftir.stack(w=None):
      Display the workspace  given by w in stack mode.
      If w is not provided, use the current active workspace.
    

Back To Function Index


superimpose


    eftir.superimpose(w=None):
      Display the workspace  given by w in superimpose mode.
      If w is not provided, use the current active workspace.
    

Back To Function Index


trace


    eftir.trace(text)
    Print the text in the 'Trace' window in the user script tool in eFTIR.
    

Back To Function Index


undo


    eftir.undo(spectrum)
      Undoes the last operation performed on the peakLib.
    

Back To Function Index


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.
    

Back To Function Index

Copyright © 2022 Operant LLC. All rights reserved.