The DIAdem SCRIPT panel allows you to automate repetitive tasks by writing code in either VBScript or Python All of the functionality you see in each of the DIAdem panels is accessible to a script (and more). You may also create custom dialogs with the Dialog Editor that contain powerful controls including channel inputs and data visualization.
The primary SCRIPT tools are the script editor, the recording mode, and the Logfile. You can write to the Logfile by using the 'LogFileWrite()' subroutine in a script. For example: 'Call LogFileWrite("writing to the Logfile")'.
In any dialog other than those from the SCRIPT panel, you can cause DIAdem to write the dialog settings and any function / subroutine calls used by the dialog to the Windows clipboard. In most cases, the information written will be more detailed than what is recorded using the recording mode. The key combination is 'Ctrl-Shift-C'.
You can get the identity of any DIAdem menu, group bar, or toolbar by holding the 'Shift-Ctrl' keys while hovering the mouse over the menu/group bar/toolbar. Use the Bar Manager object to access these items.
Use the single quote ' character to insert a comment. To comment out a block of code, select the code and use 'Ctrl-D'. To un-comment a block of code, select the code and use 'Shift-Ctrl-D'.
All variables should be declared using the 'Dim' statement. Use the keys 'Ctrl-F5' or the SCRIPT toolbar button 'Run Script' to run a script.
Referencing a channel in DIAdem can be done in several ways. Most DIAdem functions / subroutines accept a channel reference in the form of a variable object reference e.g. 'Set oChnX = Data.GetChannel("Example/Time")', or a text reference in the form of '"[1]/Time"' or '"Example/Time"' or '"[1]/[1]'" (without the single quotes). The best method is to configure the object reference, or if using text then use the text '"channel group name/channel name"' format ('"Example/Time"').
Dim oChnX, oChnY, oChnResult
'Assign the X & Y channels to a channel objects oChnX and oChnY
Set oChnX = Data.GetChannel("Example/Time")
Set oChnY = Data.GetChannel("Example/Speed")
'Define the channel where the result of the analysis will go
'by creating a new channel in the same channel group as oChnY
'with the channel name "Result"
Set oChnResult = oChnY.ChannelGroup.Channels.Add("RMS_of_" & oChnY.Name, DataTypeChnFloat64)
'Calculate the RMS of oChnY
'ChnRMS(XW, Y, ResultChannel, RMSWidth)
Call ChnRMS(oChnX, oChnY, oChnResult, 10)
Or using text based channel references:
'Calculate the RMS of oChnY
'ChnRMS(XW, Y, ResultChannel, RMSWidth)
Call ChnRMS("Example/Time", "Example/Speed", "Example/Speed_RMS", 10)
The text based channel references may seem more simple (and they are for a single calculation), BUT they are specific to a particular channels by name. If you want to use your script on data in the Data Portal with different channel group and channel names, it will be necessary to change every channel group and channel name reference. It is better and easier in longer scripts to assign those references once as channel objects, and then use those channel objects throughout the remainder of the script.
DIAdem's SCRIPT recording mode will record all commands and most variables as you perform a task with any of the non-SCRIPT panels. Access the recording mode by clicking on it from the SCRIPT toolbar. You will need to make a choice on how to handle file references. The 'File reference' option in the dialog of 'Absolute path' is the easiest option for a beginner to understand. The 'Path variable' option will configure an array for the filenames used throughout the script, but you need to be comfortable with VBScript arrays if you want to use that option.
When recording DIAdem's dialogs, you can get more information from the dialog settings than just the final function/subroutine call by using the key combination 'Ctrl-Shift-C' before the dialog is closed. For example, if you turn on recording mode and perform descriptive statistics on a channel, the script window will contain the following code:
Call ChnStatisticsChannelCalc("[1]/Speed", 56, 0, 0, False, False, False, "NameName")
But if you use the key combination Ctrl-Shift-C before closing the dialog, you will get the following code snippet:
'StatsSelection = eStatsMinimum + eStatsMaximum + eStatsArithmeticMean
StatsSelection = 56
StatsUsePopulationFormula = False
'------------ Result Storage ------------
StatsResultChn = False
StatsResultChnNames = False
StatsResultChnNameFormat = "NameName"
'------------ Command -------------------
'Set ChnResult = ChnStatisticsChannelCalc("'[1]/Speed'", 56, NOVALUE, NOVALUE, False, False, False, "NameName")
Call ChnStatisticsChannelCalc("[1]/Speed", 56, 0, 0, False, False, False, "NameName")
Everything above the call to ChnStatisticsChannelCalc() in the script shown above is either comments, or assignments to global variable associated with the ChnStatisticsChannelCalc() function (although they are not actually called). They provide supplemental information. In particular, the first line of 'StatsSelection = eStatsMinimum + eStatsMaximum + eStatsArithmeticMean' is very useful because you can look at the help for this function, and then easily add additional statistical functions to be calculated.
This tutorial will teach you how to use the SCRIPT Recording Mode to record a series of actions in DIAdem. Then you will use the 'VBScript Template' provided and adapt that script with the contents from the recording mode script. For this tutorial, be prepared to find the example file that comes with the DIAdem installation named 'Example.tdm' located in 'C:\PROGRAM FILES\NATIONAL INSTRUMENTS\DIADEM 2021\Libr\Data\Example.tdm' and load only the 'Time', 'RPM', and 'Torque' channels using the SCRIPT commands:Call Data.Root.Clear() 'NOTE: Revise the #### with the DIAdem version you have (e.g. 2021) Call DataFileLoadSel("C:\PROGRAM FILES\NATIONAL INSTRUMENTS\DIADEM ####\Libr\Data\Example.tdm","TDM","[1]/[1]|[1]/[3]|[1]/[4]","Load|ChnXYRelation")
This tutorial will use the SCRIPT recording mode to calculate the power as a channel from the channels 'RMS' and 'Speed' from the file 'Example.tdm'. Descriptive statistics will then be calculated on the channel 'Power'.
Activate the SCRIPT panel. Load the channels 'Time', 'RPM' and 'Torque' from the DIAdem example file 'Example.tdm' using the script shown below.
Call Data.Root.Clear()
'NOTE: Revise the #### with the DIAdem version you have (e.g. 2021)
Call DataFileLoadSel("C:\PROGRAM FILES\NATIONAL INSTRUMENTS\DIADEM ####\Libr\Data\Example.tdm","TDM","[1]/[1]|[1]/[3]|[1]/[4]","Load|ChnXYRelation")
Clear the SCRIPT workspace by using the menu 'File', 'New Workspace' (don't save anything). In the SCRIPT panel, click in the recording mode toolbar and set the 'File reference' option to 'Absolute path'. Click the 'Configure Recording Mode' dialog 'OK' button.
The recording mode non-modal dialog will appear.
Recall that to calculate power using the Calculation Manager, it was the product of the channels 'RPM' and 'Torque'. The general formula is: Power [kW] = 2 * Pi() * (1 min / 60 sec) * (1 kW / 1000 W) * (Speed [rpm]) * (Torque [N-m]) Activate the ANALYSIS panel by clicking on it. From the 'Basic' menu, choose '* Multiply...'. In the Data Portal, drag and drop the 'RPM' channel into the dialog 'Multiply' channel control labeled '1st channel:'. Drag and drop the 'Torque' channel from the Data Portal to 'the dialog 'Multiply' channel control labeled 'Other channels:'. Click the 'Calculate' button, and then the 'Close' button. Activate the SCRIPT panel, and you will see the following line added to the script by the recording mode:
Set ChnResult = ChnMul("[1]/RPM", "[1]/Torque", "/Multiplied")
Cleaning that up, a better command would be:
Call ChnMul("Example/RPM", "Example/Torque", "Example/Power")
Edit the script as shown above and try running the script (Ctrl-F5). The revised script will create a channel named 'Power'. Note that the unit for power is '(1/min)*(Nm)', and we want kW. The unit needs to be converted, and the ChMult() function doesn't support quantity-based calculations like other commands such as Calculate(). We will fix that by using another ANALYSIS function named 'Scale'. The recording mode should still be on. Click on the ANALYSIS panel and then select the menu 'Basic' and 'Scale...'. In the Data Portal, select the new channel 'Power' and drag and drop it into the 'Scale' dialog channel control labeled 'Channel:'. The 'Factor' in the dialog multiplies the channel values by a constant, and the 'Offset' adds or subtracts and offset from the channel values. (sort of like Y = mX + b). We need to multiply all of the values in Power by '3.142 * 2 * (1/60) * (1/1000) = 0.0001047' in order to express the power channel in units of kW. Enter the constant of '0.37704' into the 'Factor' text box, check the checkbox labeled 'Store result in original channel'. Click the 'Calculate' button, and then the 'Close' button.
Activate the SCRIPT panel. The recording mode has added a new line to the script as shown below.
Set ChnResult = ChnLinScale("[1]/Power", "/Power", 0.0001047, 0)
A cleaner version of this line of code would be:
'Convert power in (1/min)*(Nm) to kW
Call ChnLinScale("Example/Power", "Example/Power", 0.0001047, 0)
The unit for the channel 'Power' in incorrect. In the Data Portal, click on the channel 'Power', and then in the channel properties window, find 'Unit', click on the unit value, and a '...' button will appear. Click on the '...' button to edit the unit for power.
The warning message shown below should appear. Click the 'No' button.
The 'Channel Unit: Symbol Input Tool' dialog will appear. Click on the drop down box to the right of 'Quantity:' and select 'Power'. Under the list box 'Units', select '[kW]kilowatt'. Click the 'Replace' button, and the dialog will close, and the units for the channel 'Power' will be updated to kW.
Activate the SCRIPT panel and review the script commands added. No additional commands were added to the script for the unit conversion. If you had said 'Yes' to the earlier dialog, then you would have had to first define what the unit '(1/min)*(Nm)' means in terms of the unit catalog's base value of watts. The only way to fix the units for the channel 'Power' using a script is to use the following script:
'Change the channel Power units to kW
Dim oChnY
Set oChnY = Data.GetChannel("Example/Power")
oChnY.UnitSymbol = "kW"
Add the above commands to your recorded script.
The final step will be to calculate descriptive statistics on the channel 'Power'. With the recording mode still on, activate the 'ANALYSIS' panel. Choose the ANALYSIS menu 'Statistics', 'Descriptive statistics...'. In the Data Portal, select the channel 'Power' and then drag and drop it to the 'Descriptive Statistics' dialog, into the channel control to the right of the label 'Channels:'. Configure the 'Characteristic Values 1' tab to have only the following check boxes checked: 'Root mean square'. Click on the 'Result Storage' tab and insure the checkbox 'Store results in channels' is not checked. Now use the key sequence 'Ctrl-Shift-C' to copy the dialog settings to the Windows clipboard. Click the 'Calculate' button, and then the 'Close' button.
Activate the SCRIPT panel. The additional code added to recording mode script should be what is shown below.
'StatsSelection = eStatsSquareMean
StatsSelection = 64
StatsUsePopulationFormula = False
'------------ Result Storage ------------
StatsResultChn = False
StatsResultChnNames = False
StatsResultChnNameFormat = "NameName"
'------------ Command -------------------
'Set ChnResult = ChnStatisticsChannelCalc("'[1]/Power'", 64, NOVALUE, NOVALUE, False, False, False, "NameName")
Call ChnStatisticsChannelCalc("[1]/Power", 64, 0, 0, False, False, False, "NameName")
A clean version of the above code would be what is shown below. Additionally, the RMS value for channel 'Power' is written to the Logfile, just to show you how you could access that value in a script.
'Calculate the RMS of the channel Power
Call ChnStatisticsChannelCalc("Example/Power", eStatsSquareMean, 0, 0, False, False, False, "NameName")
Call LogFileWrite("RMS of Power = " & oChnY.Properties("Result~Statistics~MeanValues~SquareMean").Value & " " & oChnY.UnitSymbol)
Your recorded script with the clean changes proposed, should now look what is shown below. Run this script and observe that a channel 'Power' with the units of 'kW' is created, and it has a maximum value of 128.4 kW.
Call Data.Root.Clear()
'NOTE: Revise the #### with the DIAdem version you have (e.g. 2021)
Call DataFileLoadSel("C:\PROGRAM FILES\NATIONAL INSTRUMENTS\DIADEM ####\Libr\Data\Example.tdm","TDM","[1]/[1]|[1]/[3]|[1]/[4]","Load|ChnXYRelation")
Call ChnMul("[1]/RPM", "[1]/Torque", "/Power")
'Convert power in (1/min)*(Nm) to kW
Call ChnLinScale("Example/Power", "Example/Power", 0.0001047, 0)
'Change the channel Power units to kW
Dim oChnY
Set oChnY = Data.GetChannel("Example/Power")
oChnY.UnitSymbol = "kW"
'Calculate the RMS of the channel Power
Call ChnStatisticsChannelCalc("Example/Power", eStatsSquareMean, 0, 0, False, False, False, "NameName")
Call LogFileWrite("RMS of Power = " & oChnY.Properties("Result~Statistics~MeanValues~SquareMean").Value & " " & oChnY.UnitSymbol)
The VBScript below may be used as a template for processing a file loaded in the Data Portal, or each file specified by the NAVIGATOR search results. In either case, the function bProcessDataPortal() is called, input channels are identified, and a DIAdem ANALYSIS function is performed. If the NAVIGATOR search results are being processed, then the file will be saved before the next file from the search results is processed.
Activate the SCRIPT panel. From the SCRIPT panel menu, choose 'File', 'New VBS'. Delete the default script contents by using the keys 'Ctrl-A' to select everything and then clicking the 'Del' key to delete the selection. Copy the code below to the Windows clipboard (Ctrl-C). Return to the SCRIPT editor, click in the empty sheet, and either use 'Ctrl-V' to paste the Windows clipboard contents, or the SCRIPT menu 'Edit', 'Paste'. Access the SCRIPT menu 'File' and 'Save' and save it to the filename 'VBScriptTemplate.VBS'.
'-------------------------------------------------------------------------------
'-- VBS script file VBScriptTemplate.VBS
'-- Author: Mechatronic Solutions LLC
'-- Comment: Function bProcessDataPortal() demonstrates how to configure input and output
' channel assignments, and then execute a DIAdem ANALYSIS function.
' If data is loaded into the Data Portal, then bProcessDataPortal() is executed
' immediately. If NAVIGATOR search results are found, then each file specified
' by the search results is loaded, function bProcessDataPortal() is executed,
' and then the file is saved.
'
' YOU MUST EDIT CHANNEL ASSIGNMENTS IN FUNCTION bProcessDataPortal()
'-------------------------------------------------------------------------------
Option Explicit
Call LogFileDel()
''Uncomment the lines below to load a DIAdem sample file (for demo).
'Call Data.Root.Clear()
'Call Navigator.Display.CurrDataFinder.Browser.Activate()
'NOTE: Revise the #### with the DIAdem version you have (e.g. 2021)
'Call DataFileLoad("C:\Program Files\National Instruments\DIAdem ####\Examples\Data\ADOExample.tdm","TDM","Load|ChnXYRelation")
If Not bProcessNavSearchResults() Then Call Err.Raise(65535,,"ERROR: bProcessNavSearchResults()")
Function bProcessNavSearchResults()
'Iterate over the NAVIGATOR search results, loading one file at a time, executing
'bProcessDataPortal(), and then saving the file.
'If no NAVIGATOR search results and data exists in the Data Portal, then simply
'execute bProcessDataPortal().
bProcessNavSearchResults = False
Call LogFileWrite("bProcessNavSearchResults()...")
Dim oSearchResult, oSearchResults, sFilePath
Dim bCmdNoWarningDisp, bCmdNoMsgDisp
'The two boolean global variables below supress pop up warnings.
'Save the current state to a temporary variable so it may be restored upon exit.
bCmdNoWarningDisp = CmdNoWarningDisp: bCmdNoMsgDisp = CmdNoMsgDisp
If Data.Root.ChannelGroups.Count > 0 AND Navigator.Display.CurrDataFinder.ResultsList.IsActive = False Then
If Data.Root.ChannelGroups(1).Channels.Count > 0 Then
'No NAVIGATOR search results, but the Data Portal has data
Call LogFileWrite(String(1,vbTab) & "Processing data in the Data Portal ...")
If Not bProcessDataPortal() Then
Call LogFileWrite(String(1,vbTab) & "ERROR processing the Data Portal")
Exit Function
End If
bProcessNavSearchResults = True
Exit Function
End If
End If
If Navigator.Display.CurrDataProvider.IsKindOf(eDataStore) Then Call Err.Raise(65535,,"ERROR: You are connected to a DataStore, not a DataFinder")
If Not Navigator.Display.CurrDataFinder.QueryForm.ResultsMode = eResultsModeElements Then Call Err.Raise(65535,,"ERROR: The DataFinder search results are not elements (files), but rather properties")
If Navigator.Display.CurrDataFinder.ResultsList.ResultsElements.IsIncomplete Then Call Err.Raise(65535,,"WARNING: Not all of the NAVIGATOR search results are displayed.")
If Navigator.Display.CurrDataFinder.ResultsList.ResultsElements.Count < 1 AND Data.Root.ChannelGroups.Count = 0 Then
Call Err.Raise(65535,,"ERROR: No NAVIGATOR search results to process, and no data loaded into the Data Portal.")
Else 'Search results exist
Call LogFileWrite(String(1,vbTab) & "Processing " & Str(Navigator.Display.CurrDataFinder.ResultsList.ResultsElements.Count) & " search results (files) from the NAVIGATOR search results...")
Set oSearchResults = Navigator.Display.CurrDataFinder.ResultsList.ResultsElements
For Each oSearchResult In oSearchResults
'Get the path to the file from oSearchResult
sFilePath = oSearchResult.Properties("folder").Value & "\" & oSearchResult.Properties("filename").Value
Call LogFileWrite(String(1,vbTab) & "Analyzing file '" & NameSplit(sFilePath,"N") & "." & NameSplit(sFilePath,"E") & "'...")
'Clear the contents of the Data Portal
Call Data.Root.Clear()
'Load the data file sFilePath into the Data Portal
Call DataFileLoad(sFilePath, uCase(NameSplit(sFilePath,"E")), "Load|ChnXYRelation")
If Not bProcessDataPortal() Then
Call LogFileWrite(String(1,vbTab) & "ERROR processing file '" & NameSplit(sFilePath,"N") & "." & NameSplit(sFilePath,"E") & "'...")
Exit Function
End If
'Save the file with any changes from bProcessDataPortal()
CmdNoWarningDisp = True: CmdNoMsgDisp = True
Call DataFileSave(sFilePath, uCase(NameSplit(sFilePath,"E")), True)
'Restore the global variable state
CmdNoWarningDisp = bCmdNoWarningDisp: CmdNoMsgDisp = bCmdNoMsgDisp
Next 'oSearchResult
'Clean up..
Call Data.Root.Clear()
Set oSearchResult = Nothing: Set oSearchResults = Nothing
End If
bProcessNavSearchResults = True
End Function 'bProcessNavSearchResults()
Function bProcessDataPortal()
bProcessDataPortal = False
Call LogFileWrite("bProcessDataPortal()...")
Dim oChnX, oChnY, oChnResult
'Edit the X and Y channel assignments below:
Set oChnX = Data.GetChannel("Measurement_A/Time")
Set oChnY = Data.GetChannel("Measurement_A/MeasurementChannel_1")
'Define the channel where the result of the analysis will go
'by creating a new channel in the same channel group as oChnY
'with the channel name "Result"
Set oChnResult = oChnY.ChannelGroup.Channels.Add("Result", DataTypeChnFloat64)
'ChnOffset(Y, ResultChannel, ChnOffsetValue, ChnOffsetMode)
Call ChnOffset(oChnY, oChnResult, 0, "min. value offset")
'Update the description property for oChnResult
Call oChnResult.Properties.Add("description", "ChnOffsetVal() min value offset. Source: " & oChnY.GetReference(eReferenceNameName))
'Clean up
Set oChnX = Nothing: Set oChnY = Nothing: Set oChnResult = Nothing
bProcessDataPortal = True
End Function 'bProcessDataPortal()
To run the demo, un-comment the lines shown below. Run the script with the keys 'Ctrl-F5' or the SCRIPT toolbar button 'Run Script'. The script will load a DIAdem example file and then execute the ANALYSIS function 'Offset Corrrection' or 'ChnOffset()' on the channel 'Measurement_A/MeasurementChannel_1'.
''Uncomment the lines below to load a DIAdem sample file (for demo).
Call Data.Root.Clear()
Call Navigator.Display.CurrDataFinder.Browser.Activate()
'NOTE: Revise the #### with the DIAdem version you have (e.g. 2021)
Call DataFileLoad("C:\Program Files\National Instruments\DIAdem ####\Examples\Data\ADOExample.tdm","TDM","Load|ChnXYRelation")
In this tutoral, the prior recording mode script generated will be integrated into a copy of the script 'VBScriptTemplate.VBS'. Save the script 'VBScriptTemplate.VBS' to a new file named 'Power from RPM & Torque.VBS' by choosing the SCRIPT menu 'File', and 'Save As...' Uncomment the three lines in the beginning that clear the data portal, activate the NAVIGATOR browser, and load a data file. Replace the DataFileLoad() command with a reference to the 'Example.tdm' file as used in the recording mode tutorial.
''Uncomment the lines below to load a DIAdem sample file (for demo).
Call Data.Root.Clear()
Call Navigator.Display.CurrDataFinder.Browser.Activate()
'NOTE: Revise the #### with the DIAdem version you have (e.g. 2021)
Call DataFileLoadSel("C:\PROGRAM FILES\NATIONAL INSTRUMENTS\DIADEM ####\Libr\Data\Example.tdm","TDM","[1]/[1]|[1]/[3]|[1]/[4]","Load|ChnXYRelation")
If you adjust the script with the additional script content from the recording mode tutoral, and make the other changes as shown below, the script will calculate power from RPM and Torque.
Function bProcessDataPortal()
bProcessDataPortal = False
Call LogFileWrite("bProcessDataPortal()...")
Call ChnMul("Example/RPM", "Example/Torque", "Example/Power")
'Convert power in (1/min)*(Nm) to kW
Call ChnLinScale("Example/Power", "Example/Power", 0.0001047, 0)
'Change the channel Power units to kW
Dim oChnY
Set oChnY = Data.GetChannel("Example/Power")
oChnY.UnitSymbol = "kW"
'Calculate the RMS of the channel Power
Call ChnStatisticsChannelCalc("Example/Power", eStatsSquareMean, 0, 0, False, False, False, "NameName")
Call LogFileWrite("RMS of Power = " & oChnY.Properties("Result~Statistics~MeanValues~SquareMean").Value & " " & oChnY.UnitSymbol)
'Clean up
Set oChnY = Nothing
bProcessDataPortal = True
End Function 'bProcessDataPortal()
The function bProcessDataPortal() may also be re-written to use channel object references, as shown below:
Function bProcessDataPortal()
bProcessDataPortal = False
Call LogFileWrite("bProcessDataPortal()...")
Dim oChnRpm, oChnTrq, oChnPwr
Set oChnRpm = Data.GetChannel("Example/RPM")
Set oChnTrq = Data.GetChannel("Example/Torque")
'Create a new channel Power
Set oChnPwr = oChnRpm.ChannelGroup.Channels.Add("Power", DataTypeChnFloat64)
Call ChnMul(oChnRpm, oChnTrq, oChnPwr)
'Convert power in (1/min)*(Nm) to kW
Call ChnLinScale(oChnPwr, oChnPwr, 0.0001047, 0)
'Change the channel Power units to kW
oChnPwr.UnitSymbol = "kW"
'Calculate the RMS of the channel Power
Call ChnStatisticsChannelCalc(oChnPwr, eStatsSquareMean, 0, 0, False, False, False, "NameName")
Call LogFileWrite("RMS of Power = " & oChnPwr.Properties("Result~Statistics~MeanValues~SquareMean").Value & " " & oChnPwr.UnitSymbol)
'Clean up
Set oChnRpm = Nothing: Set oChnTrq = Nothing: Set oChnPwr = Nothing
bProcessDataPortal = True
End Function 'bProcessDataPortal()
Do you need help with your project? Send me an email requesting a free phone / web share consultation.
Copyright © 2021,2022,2023 Mechatronic Solutions LLC, All Rights Reserved