introduction to programming in visual basic scripts for ... · introduction to programming in...

30
LECTURE 3 Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing of ElecNet scripts using the Visual Basic Script language. Basic notions and operators of the language are presented firstly, then, some simple scripts and one fully commented script for creation of ECT sensor are given. The information here about Visual Basic Script language is based on the ElecNet VB Scripting Manual [2]. Why is scripting nesessary? The goal of the scripting is to provide a convenient tool to automate modeling, solving, and post-processing tasks with ElecNet. Complex and repetitive tasks can be simplified with a script by reducing a series of many commands to several lines of code. The scripts can be fully parameterized introducing variables, and such scripts can be used for variant computations and for optimization. User scripts and forms Within the various Infolytica applications (MagNet, ElecNet, ThermNet), two types of scripts can be generated: - Scripts that are created by a user or recorded by ElecNet scripting utilities - Script forms that are designed and coded by the user. Scripts are text files that contain a series of scripting commands, written in Visual Basic Script language. Script files can be created or modified with a text editor (Notepad, Notepad++) or can be automatically generated using Infolytica application scripting utilities and later modified by the user. The user scripts must be saved in text format with the .vbs extension. We recommend using the Notepad++ text editor, which is free, has good features as coloring the VB operators, has multi-documents interface and others. In order to automatically create a user script, select 'Start Recording User Script' from the Scripting menu in the horizontal menu bar and choose a name for the script. The application then records all of the commands and actions carried out by the user until the user stops or pauses the script. Then, the script can be run by selecting 'Run Script' from the Scripting menu and choosing the desired script file. These recorded user scripts can be used as a starting point in generating scripts that are more functional, adding variables, loops, etc. A scripting form provides a graphical user interface (GUI) similar to a Windows application, such that the user can interact with the script and affect the result that are obtained from a given script. Forms can take in user input and return values based on this input. This makes the form more flexible than the user scripts. Furthermore, user scripts can be incorporated into a form in order to facilitate coding for the user. Forms can be written in either VBScript or in JScript. Below, a script form for Example 1 from the first lecture is shown: 1

Upload: hoangtruc

Post on 12-Jun-2018

249 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

LECTURE 3

Introduction to programming in Visual Basic Scripts for Elecnet

The aim of this lecture is to present shortly the writing of ElecNet scripts using the Visual Basic Script language. Basic notions and operators of the language are presented firstly, then, some simple scripts and one fully commented script for creation of ECT sensor are given. The information here about Visual Basic Script language is based on the ElecNet VB Scripting Manual [2].

Why is scripting nesessary?

The goal of the scripting is to provide a convenient tool to automate modeling, solving, and post-processing tasks with ElecNet. Complex and repetitive tasks can be simplified with a script by reducing a series of many commands to several lines of code. The scripts can be fully parameterized introducing variables, and such scripts can be used for variant computations and for optimization. User scripts and forms

Within the various Infolytica applications (MagNet, ElecNet, ThermNet), two types of scripts can be generated:

- Scripts that are created by a user or recorded by ElecNet scripting utilities - Script forms that are designed and coded by the user.

Scripts are text files that contain a series of scripting commands, written in Visual Basic

Script language. Script files can be created or modified with a text editor (Notepad, Notepad++) or can be automatically generated using Infolytica application scripting utilities and later modified by the user. The user scripts must be saved in text format with the .vbs extension. We recommend using the Notepad++ text editor, which is free, has good features as coloring the VB operators, has multi-documents interface and others.

In order to automatically create a user script, select 'Start Recording User Script' from the Scripting menu in the horizontal menu bar and choose a name for the script. The application then records all of the commands and actions carried out by the user until the user stops or pauses the script. Then, the script can be run by selecting 'Run Script' from the Scripting menu and choosing the desired script file.

These recorded user scripts can be used as a starting point in generating scripts that are more functional, adding variables, loops, etc.

A scripting form provides a graphical user interface (GUI) similar to a Windows application, such that the user can interact with the script and affect the result that are obtained from a given script. Forms can take in user input and return values based on this input. This makes the form more flexible than the user scripts. Furthermore, user scripts can be incorporated into a form in order to facilitate coding for the user. Forms can be written in either VBScript or in JScript. Below, a script form for Example 1 from the first lecture is shown:

1

Page 2: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

The creation of scripting forms will not be covered here as these are more advanced

features. Sufficient information on scripting forms can be found in the VB Scripting Manual [2] (reached via the Help menu).

Three more manuals on ElecNet can be accessed via the Help menu: • Introduction to ElecNet [1] ( Highly recommended ! Read it entirely ! ) • Tutorials [3] • Getting Started Guide

Session log

ElecNet automatically generate a script file ( ElecNetSessionLog.vbs ) every time it is accessed. This session log, located by default in the folder “C:\Documents and Settings\USERNAME\Application Data\Infolytica\elecnet(64-bit)\LogFiles”, can also be used as a user script and run from within the application. The file contains a log of all the activities from the moment one enters the program until the program is closed. The ElecNet backup the session log for up to ten times before the file is removed. The phrase 'Backup-' followed by a number is appended to the front of the session log file name). One can view the contents of the session file by selecting 'View ElecNetSessionLog' from the Help menu. Scripting info

ElecNet 's scripting technology lets you use ElecNet to communicate with any application on your desktop that supports OLE Automation, such as Microsoft Word, Microsoft Excel, MATLAB or Mathcad. The implementation of Microsoft's ActiveX Scripting specifications allows running ElecNet using VBScript (Microsoft Visual Basic, Scripting Edition) or JScript (Microsoft's version of a Java scripting language).

Once the script has been built, it can be interfaced to a scripting form. The scripting form, which operates much like a dialog box, allows to hide the programming from the user and to leave him to operate only with several controls of the GUI.

2

Page 3: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Scripting syntax guidelines: 1. All commands are prefaced with a CALL statement. The default CALL statement used in the ElecNet scripting commands is "CALL getDocument()".

CALL getDocument().newDocument() 2. Arguments should be enclosed in parentheses.

CALL getDocument().selectAt(-1.0, -2.0, 3.0) 3. Parentheses should be included even when empty.

CALL getDocument().undo() 4. Strings must be enclosed in quotes (" ").

CALL getDocument().setDescription ("Sensor") 5. Strings are case-sensitive (for example, material names are strings). 6. Comments can follow to the right of an REM statement or an apostrophe (').

REM rotate by 10 degrees ' rotate by 10 degrees

7. Extra blank lines, spaces, and tabs are ignored by VBScript. 8. A line of code can be continue to the next line, using underscore sign _ at the end of that line.

Declaring constants and variables

Constants are values within formulas that need to be used many times, without need of changing their values (e.g., the number pi=3.14159265, the permittivity of the air eps0=8.854E-12, etc.). To declare a constant pi, the following syntax should be used:

Const pi=3.14159265

Variables are items used to store data within a program. For example, if input data must be read, you could simply declare a variable and equate it to the value being read in from the user form (or file). The values of the variables can be changed during program execution.

In order to declare a variable, one uses the Dim command. The Dim command reserves space in memory such that the variable can store any type of data.

Dim Variable The variable here is automatically declared as a variant such that it can store a string, numerical data, an array or any other variable type. Option Explicit

In VBScript, one may use variables without first defining them. In order to have a program that only allows the use of variables that have been previously declared, the ‘Option Explicit’ command must be used. The Option Explicit command is placed before all other statements in a script, apart from any sub or function. The advantage to using the Option Explicit command is that it prevents one from misspelling the names of variables. Declaring Arrays

An array is a special type of variable that can hold several different values. In order to declare an array that can hold a given number of values, you need only enter the index of the last element in the array in parentheses, directly after the variable declaration. Since the first element in the array has an index value of zero, you would declare a value one less than the total number of elements in the array. For example, to declare an array with 10 values, you would use the statement:

Dim ArrayName(9)

3

Page 4: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

The indices of the data within the array would range from zero to nine inclusive, a total of 10 separate values.

Once an array is declared with a given number of inputs, the same array name can later be declared again with a different number of elements using the ReDim command. Furthermore, the ReDim command can be used to declare a previous variant variable as an array. Examples: 1. Dim MyArray1(4)

ReDim MyArray1(9) - Resizing an existing array; 2. Dim MyArray2

ReDim MyArray2(9) - Converting from a variant to an array; 3. Dim MyArray3()

ReDim MyArray3(9) - Adding the size of an empty array. When inputting values into an array, one need only declare the name of the array and

the index and equate it to a value. Each index of a given array can contain values of different types such as strings, integers, dates, etc.

When resizing an array with the ReDim command, all of the information contained in an array is lost. In order to preserve the contents of an array while it is being resized, use the ‘Preserve’ command:

ReDim Preserve MyArray(15) This function call resizes an already existing array to another size while keeping all of the information that was previously stored in the array. Note that this statement can only be used to increase the size of an array and not to decrease it.

In order to delete the contents of an array, one would use the Erase command. The syntax for the Erase command is

Erase MyArray The dimensions of the array remain unchanged after the erase command is executed. You must take care not to name arrays ‘Array’. This is because Array is a function that is defined within VBScript that generates an array from a given list of elements. For example, the statement

MyArray = Array(0,1,2,3,4,5) creates an array called MyArray which contains six elements: 0, 1, 2, 3, 4 and 5. These elements are placed in the array, in the listed order. Note that the array can contain values of different types such as strings, integers and dates. Variable manipulation

When a program contains a variable, this variable can be manipulated by the program code. In addition to equating different values to a variable, in the case of strings, different strings can be concatenated to form one long string. In order to concatenate two or more strings, use the ‘&’ or the ‘+’ symbol between the individual strings. Example:

String1 = “The rain in Spain” String2 = “ falls mainly on the plain.” String3 = String1 & String2

‘String3’ will contain the value “The rain in Spain falls mainly on the plain.” Strings can be concatenated with other strings as well as to any other type of variable such as integers and dates. All concatenated information will be stored as a string by the program. When variables are concatenated to strings, they are not placed in quotation marks.

VBScript contains the following mathematical functions, that can be used in mathematical expressions:

4

Page 5: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Symbol Function

+ Addition

- Subtraction

* Multiplication

/ Division \

Integer Division (keeps only the integer part of the result)

Returns the modulus (remainder) of a division Mod

Exponent (e.g. 2^3 = 23) ^

Cos(value) Cosine – Input value is in radians

Sin(value) Sine – Input value is in radians

Tan(value) Tangent – Input value is in radians

Atn(value) Arctangent – Input value is in radians

Log(value) Natural Logarithm

Exponentiation (evalue) Exp(value)

Sqr(value) Square Root

Abs(value)

Absolute Value

Subs and functions

A Sub refers to a subroutine that does not return a value. It executes a series of statements and then it returns control to the point in the program from which it was called. The syntax for a sub is:

Sub Name(parameters) Code

End Sub A Function, on the other hand, returns a value to the point that it was called in the

program. Its structure is similar to that of subs. In order to return the value calculated by the function, the name of the function must be equated to the result obtained.

Function Name(parameters) Code Name = Result

End Function The names of both functions and subs cannot contain any spaces. The names must

start with a letter and may include underscores and numbers. Parameters are the input values that a sub or a function needs in order to carry out a

task. The parameters are enclosed within brackets after the name of the sub or function. If there are no parameters, no parentheses are necessary.

If a function or a sub has more than one parameter, the different parameters in the list are separated by commas.

5

Page 6: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Subs and functions can be called from within other subs or functions. In order to call a sub, you would merely enter the name of the sub along with any input parameters that the sub would require. In order to call a function, a value must be equated to the function call such that the program stores the returned value. Again, the parameters in the list are separated by commas.

SubName(parameters) Value = FunctionName(parameters)

Writing subs and functions can help to minimize the amount of coding necessary. If there is a series of statements that must be used many times in a script, they can be written once in subroutines and accessed repeatedly. Furthermore, by using these subroutines, the code can be broken down into functional sections such that each subroutine is responsible for a specific task. Scope of a variable

If a single variable or a constant needs to be accessed by more than one subroutine, then the variable can be declared outside of all subroutines. Variables that are defined outside all subs and functions are said to have a scope that includes the entire program. The scope of a variable indicates the region in which the variable can be accessed. Variables and constants that are defined within one sub cannot be accessed in another sub unless it is passed as an input parameter. The if-then-else and select case statements

The If-Then-Else statement is a structure that will execute a series of statements contained within its structure, only if the criterion set within the control statement of the loop is met. The control statement in the loop is a statement that can evaluate to either True or False. Some control loops will be executed only if the control statement evaluates to True while others require the statement to evaluate to False. Within control statements, the most commonly used symbols are mathematical expressions of equality and inequality.

Mathematical Symbols Symbol Meaning < Less than > Greater than

<= Less than and equal to >= Greater than and equal to <> Not equal to = Equal to

Eqv Logically equivalent to

The equality statement can be used to compare two strings of text as well as two numerical values. In instances where more than one criterion must be met, you can compound two statements using the compound operators:

Compound Operators Property And True if both statements are True Or True if either of the two statements preceding is True. Xor Exclusive Or. True if only one of the statements is True. Not Toggles the value of a Boolean statement.

6

Page 7: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Together, these mathematical and compound operators can be used to form control statements for the If-Then-Else statement. The structure of the statement is

If (a >0 And a <> 10) Then a = a –5

Else a = a + 5

End If Only one of the statements is executed when the script is run, dependent upon the Boolean value of the control statement. This structure is additionally flexible in that the Else clause of the statement is optional. If there are more than two possible outcomes, one can nest the If-Then-Else statements within each other. The syntax for the Select Case statement is as follows:

Select Case Variable Case value1

Statements1 Case value2

Statements2 Case value3

Statements3 End Select

This statement will execute one of three different sections of code depending on whether ‘variable’ is equal to value1, value2 or value3. If it is not equal to any of these three values, the code is ignored and the statement after the select case statement is executed. Control loops Control loops are similar to If-Then-Else statements in that they contain a control statement and they are only executed when an initial criterion is met. However, unlike the previous structures, control loops will repeat the series of statements until the criterion is no longer met. There are several different types of control loops: 1. For-Next

For i = 1 To 20 a = a+ 1

Next For i = 1 To 20 Step 2

a = a+ 1 Next

The body of the loop executes the number of times indicated in the first line of the for statement or until an exit statement is reached. The ‘Exit For’ statement may be included within the loop. 2. For Each-Next

For Each Value in ArrayName MsgBox (Value)

Next

7

Page 8: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

This body of the loop executes once for each value in an array or until an exit statement is reached. Within the loop, each array element, in turn, is assigned to the variable ‘Value’. The ‘Exit For’ statement may be included within the loop. 3. Do-Loop

Do a = a +1 If (a > 20) Then

Exit Do End If

Loop In this loop, the exit statement must be included within the statements in the loop or else the loop would continue infinitely. This is accomplished in the example by using an if statement. 4. Do-Loop Until

Do a = a – 1

Loop Until (a <20) The body of this loop executes at least once until the control statement at the end of the loop evaluates to True. The ‘Exit Do’ statement may be used within the Do-Until loop. 5. Do-Loop While

Do While (a < 20) a = a + 1

Loop The body of this loop executes while the control statement at the beginning of the loop evaluates to True. The ‘Exit Do’ statement may be used within the Do-While loop. Further control can be added to a program by nesting loops. Input box

An input box is a function that outputs a screen to the user and returns the user’s input. The input box can only take in one input at a time from a user. Example:

VariableName = InputBox (“Please enter the material name”)

The value input by the user is held in ‘VariableName’ and can then be manipulated by the code once the user hits ‘OK’. If the user hits on the Cancel button, then an empty string, “”, is returned.

In order to change the title of the input box from the default (‘Visual Basic’), a second string needs to be included in the declaration of the input box. If one wishes to declare the input box with default text written within as input, then a third string must be added to the declaration:

VariableName = InputBox (“String Message”, “Input Box title”, “Default input”) Example: Var1 = InputBox (“Enter Material:”, “Materials page”, “Copper”)

8

Page 9: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Message boxes and outputs

Message boxes are small windows in VBScript that output messages to the user. By default, message boxes have an ‘OK’ button. You can change the types of buttons that appear in a message box. Each different type of button has its own value. This value is returned from the Message Box function, indicating to the program code which button was clicked by the user. Since the default form for a message box only has one button, in this instance, it is not necessary to retain the return value and you can call a message box using the following notation

MsgBox(“Place your message here”)

When this is called, a message box will appear with the string appearing as the message and the OK button appearing by default. When a message box appears, it suspends all activity of an application. Therefore, other elements of a given program cannot be accessed until a message box is closed by clicking on one of its buttons. Apart from the default type of message box, in all other types of message boxes there is more than one button that the user may click. In this instance, it is important to note which button the user presses and have the program respond accordingly.

By default, messages boxes output the message string in a single line. In order to have a multiple-lined message, in either a message box or a text box, you need to use the ‘Chr’ array. The ‘Chr’ array is an array that contains all of the different ASCII characters that can be output in a text message. In addition to the printable characters located on the keyboard, the ASCII characters provide for non-printable characters such as tabs and line carriages. The non-printable characters most commonly used are:

• Chr(9) – Horizontal Tab • Chr(10) – Carriage Return (New Line) • Chr(11) – Vertical Tab • Chr(34) – Quotation marks

Since this array already comes pre-defined with the program, you may not declare an array with the same name within the program code. In order to include these characters within an output string, one needs only to concatenate the array name and index of the character with a string. Five fully commented scripts are shown below:

9

Page 10: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Example Script 1 – computing the capacitance of cylindrical capacitor Option Explicit ' Title: Capacitance of cylindrical capacitor with two layers ' Set problem options Call SetLocale("en-us") Call getDocument().setDefaultLengthUnit("Millimeters") Call getDocument().getView().showGrid(True) Call setViewingCurveSmoothnessAngle(1, False) Call getDocument().setNumberOfMultiCoreSolveThreads(7) Call getDocument().setMaxElementSize("", 0.1) Call getDocument().setPolynomialOrder("", 2) Call getDocument().setImproveMeshQuality(True) ' Specify input data Const r1=1 ‘ inner radius Const r2=2 ‘ middle radius Const r3=3 ‘ outer radius Const L=10 ‘ capacitor length Const Volts=1 ‘ potential of the outer electrode Const epsr1=2.5 ‘ permittivity of the outer layer Const epsr2=3.5 ‘ permittivity of the inner layer Const pi=3.141592653589793238462643383 Const e0=8.854e-12 ‘ permittivity of Air Dim path, name, fname1, fname2 name=”ex1” path="C:\Documents and Settings\kosta\My Documents\ElecNet\ElecNet course examples\" fname1=path & name & “.en" ' name of the ElecNet model file ( en-file) fname2=path & name & ”_cap.txt" ' name of capacitance file (text file) ' create 2 new materials, if they do no exist Dim matname1, matname2 matname1="New_2.5" matname2="New_3.5" Call mater_exist(matname1,epsr1, "blue" ) Call mater_exist(matname2,epsr2, "green2" ) ' available colors in the sub are: blue, green, green2, red, violet ' Draw the 3 circles of the capacitor Call getDocument().getView().newCircle(0, 0, r3) Call getDocument().getView().newCircle(0, 0, r2) Call getDocument().getView().newCircle(0, 0, r1) Call getDocument().getView().setScaledToFit(True) ' Create capacitor layer 2 (outside layer) Call getDocument().getView().selectAt( (r2+r3)/2, 0, infoSetSelection, Array(infoSliceSurface)) Call getDocument().getView().makeComponentInALine(L, Array("Component#1"), "Name="+matname1, _ infoMakeComponentUnionSurfaces Or infoMakeComponentRemoveVertices) ' Create capacitor layer 1 (inner layer) Call getDocument().getView().selectAt( (r1+r2)/2, 0, infoSetSelection, Array(infoSliceSurface)) Call getDocument().getView().makeComponentInALine(L, Array("Component#2"), "Name="+matname2, _ infoMakeComponentUnionSurfaces Or infoMakeComponentRemoveVertices) ' Make electrodes

10

Page 11: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

REDIM ArrayOfValues(1) ArrayOfValues(0)= "Component#1,Face#3" ArrayOfValues(1)= "Component#1,Face#4" Call getDocument().makeElectrode(ArrayOfValues) REDIM ArrayOfValues(1) ArrayOfValues(0)= "Component#2,Face#5" ArrayOfValues(1)= "Component#2,Face#6" Call getDocument().makeElectrode(ArrayOfValues) ' Specify voltage 1 V on the Electrode 1 /Volts=1/ Call getDocument().getView().selectObject("Electrode#1", infoSetSelection) Call getDocument().setElectrodeVoltage("Electrode#1", Volts, 0) ' make the construction grid invisible Call getDocument().getView().showGrid(False) ' fit the drawing to screen size Call getDocument().getView().setScaledToFit(True) ' delete construction plane lines and arcs Call getDocument().getView().selectAll(infoSetSelection, Array(infoSliceLine, infoSliceArc)) Call getDocument().getView().deleteSelection() ' Start of code used to start a static solve. ' The subroutines and functions defined below help do the work. Dim Doc ' Make the call to solveStatic2d Set Doc= getDocument() If (Doc.isValidForStatic2dSolver()) Then If (Doc.solveStatic2d()) Then Call RefreshSolutionMeshesInViews(Doc) Call RefreshFieldsInViews(Doc, "Contour", infoScalarField) Call RefreshFieldsInViews(Doc, "Shaded", infoScalarField) Call RefreshFieldsInViews(Doc, "Arrow", infoVectorField) End If End If Set Doc= Nothing ' Post-processing ' save the en-file Call getDocument().save(fname1) ' Compute charges Dim charge, CC, C1, C2, CA, err, L1, sss charge = getDocument().getSolution().getChargeOnElectrode (1, "Electrode#1") CC=abs(charge/Volts) ' Analytical formulas for the capacitance L1=L*1e-3 ' C for the outer cylinder C1=2*pi*epsr1*e0*L1/log(r3/r2) ' C for the inner cylinder C2=2*pi*epsr2*e0*L1/log(r2/r1) ' equivalent C of the series connection CA=C1*C2/(C1+C2) ' relative error in percents err=abs(CA-CC)/CA*100 ' in percents sss="Capacitance from ElecNet: " & CC & vbNewLine & _

11

Page 12: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

"Capacitance analytical : " & CA & vbNewLine & _ "relative error in percents :" & err MsgBox sss ' output a message box with the capacitances ' write the capacitances in a text file Call WriteTextFile(fname2, sss) ' -- end of main program ‘---------------------------------------------------------------------------------------------- Sub mater_exist(matname,epsr, color) ' create new material with specified name, permittivity and color ' first, it checks if the material exists and whether the permittivity is as required Dim mat_exist, epsx, Arr(0,1), c1 epsx=0 if color="green" then c1=Array(128,255,0,255) elseif color="green2" then c1=Array(64,128,128,255) elseif color="blue" then c1=Array(0,128,255,255) elseif color="red" then c1=Array(255,0,128,255) else c1=Array(128,0,255,255) ' violet end if mat_exist=getUserMaterialDatabase().isMaterialInDatabase(matname) if mat_exist then CALL getUserMaterialDatabase().getElectricPermittivity(matname, Arr, infoLinearIsotropicReal) epsx=Arr(0,1) End If if not mat_exist Or epsx <> epsr then if mat_exist then Call getUserMaterialDatabase().DeleteMaterial(matname) End If Call getUserMaterialDatabase().newMaterial(matname) Call getUserMaterialDatabase().setMaterialColor(matname, c1(0), c1(1), c1(2), c1(3) ) Call getUserMaterialDatabase().setMaterialCategories(matname, Array()) REDIM ArrayOfValues(0, 1) ArrayOfValues(0, 0)= 20 ArrayOfValues(0, 1)= epsr Call getUserMaterialDatabase().setElectricPermittivity(matname, ArrayOfValues, infoLinearIsotropicReal) If (hasDocument()) Then Call getDocument().getModelMaterialDatabase().updateMaterial(matname, False) End If End If End Sub

12

Page 13: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Example Script 2 - 32-electrode sensor ------------------------------------------------------------- Option Explicit ' Sensor32 – example script for ' dept KIS standard sensor (4-layer, rectangular, 2 axial shields) ' with inhomogeneity in the center with r=25 mm ' Available cases: ' 1st Case : er_media=3 er_bar=1 ' 2nd Case : er_media=3 er_bar=3 - homogeneous full ' 3rd Case: er_media=1 er_bar=3 ' 4th Case : er_media=1 er_bar=1 – homogeneous empty 'Solving statistics p=2 ' No. of tetrahedra = 430611 ' No. of nodes = 85185 ' No. of Unary Faces = 42726 ' Time 0:01:15 508.7 MB ' options Call SetLocale("en-us") Call newDocument() Call getDocument().setDefaultLengthUnit("Millimeters") Call setViewingCurveSmoothnessAngle(1, False) Call getDocument().setMaxElementSize("", 6) Call getDocument().setPolynomialOrder("", 2) Call getDocument().setImproveMeshQuality(True) Call getDocument().setNumberOfMultiCoreSolveThreads(7) Call getDocument().getView().setScaledToFit(True) ' Input data Const pi=3.141592653589793238462643383 Const r1= 75 ' inner radius of the sensor (mm) Const pipeth= 3 ' pipe thickness [mm] Const thickness=1 ' thickness of the electrode (mm) Const h1=30 ' height of the inner layer electrodes Const h2=70 ' height of the outer layer electrodes Const n=8 ' number of electrodes in a layer Const sh=50 ' height of the guard shields Const d1=1 ' interelectrode angle (degrees) in theta-direction Const d2=1 ' interelectrode distance in z-direction Const dr=14 ' air distance from the electrode to the outer screen Const kind=4 ' kind of analysis: 1-4 Const r0=25 ' radius of the inhomogeneity in the center Const Volts=1 ' electrode voltage Const ElectrodeMaterial = "Copper: 5.77e7 Siemens/meter" Const path="C:\Documents and Settings\kosta\My Documents\ElecNet\ElecNet course examples\" Const name="sensor32" Dim fname1, fname2 fname1=path+name+".en" fname2=path+name+"_cap.txt" Dim Plastic1, Plastic1_5, Plastic3, Plastic, Plastic_media, Plastic_inhom Plastic1 = "EP01: Relative permittivity 1" Plastic1_5 = "EP1.5: Relative permittivity 1.5" Plastic3 = "EP03: Relative permittivity 3"

13

Page 14: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Call mater_exist(Plastic1, 1, "blue") Call mater_exist(Plastic1_5, 1.5, "green") Call mater_exist(Plastic3, 3, "green2") if kind=1 then Plastic_media=Plastic3 Plastic_inhom=Plastic1 elseif kind=2 then Plastic_media=Plastic3 Plastic_inhom=Plastic3 elseif kind=3 then Plastic_media=Plastic1 Plastic_inhom=Plastic3 elseif kind=4 then Plastic_media=Plastic1 Plastic_inhom=Plastic1 else MsgBox " Error in the kind number (1-4)" & vbNewLine & "kind = " & kind _

& vbNewLine & "Default kind=4 is taken !" kind=4 Plastic_media=Plastic1 Plastic_inhom=Plastic1 end if Dim dh, r2, theta, theta1, theta2, x1, y1, x2, y2, x3, y3, x4, y4, r3, r4 dh=dr ' air distance from the top electrode to the outer airbox surface in z r2=r1+thickness ' outer radius of the electrodes (mm) r3=r1-pipeth ' inner radius of the plastic pipe [mm] r4=r2+dr ' the radius of the outer screen ( radius of the airbox) theta=2*pi/n ' one electrode+gap division in radians theta1=d1/180*pi ' the inter-electrode gap angle in radians theta2=theta-theta1 ' the electrode angle in radians 'ATTENTION - all arguments of the trigonometric functions in VBS are in RADIANS ! 'BUT, the angular arguments in ElecNet-functions are in degrees ! 'points coordinates of the cross-section of one electrode x1=r1*cos(0) y1=r1*sin(0) x2=r1*cos(theta2) y2=r1*sin(theta2) x3=r2*cos(0) y3=r2*sin(0) x4=r2*cos(theta2) y4=r2*sin(theta2) ' Draw the cross-section of Electrode 1 ' draw 2 arc segments Call getDocument().getView().newArc(0, 0, x1, y1, x2, y2) Call getDocument().getView().newArc(0, 0, x3, y3, x4, y4) ' draw 2 connecting lines Call getDocument().getView().setSnapMode(infoSnapEndpoint) Call getDocument().getView().newLine(x1, y1, x3, y3) Call getDocument().getView().newLine(x2, y2, x4, y4) ' Copy and rotate the electrode cross-section, to obtain the layer cross-section Call getDocument().getView().selectAll(infoSetSelection, Array(infoSliceLine, infoSliceArc)) Dim thetagr, i, xc, yc, rr, ii, hhh

14

Page 15: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

thetagr=360/n For i=1 to n-1 Call getDocument().getView().rotateSelectedEdges(0, 0, thetagr*i, True) Next ' Create four layers of electrodes by extrusion of the cross-section ' hh1 electrode layers heights ' hh2 distance to move the construction slice for each layer Dim hh1, hh2, j hh1=Array(h2,h1,h1,h2) hh2=Array(0, h2+d2, h1+d2, h1+d2) rr=r1+thickness/2 ' middle point radius of the electrodes ii=0 For j=1 to 4 ' loop on layers ‘ move the construction plane if j > 1 then Call getDocument().getView().getSlice().moveInALine(hh2(j-1)) end if For i=1 to n ' loop on electrodes ii=ii+1 xc=rr*cos(theta*(i-1)+theta2/2) ' the electrode center point x-coord yc=rr*sin(theta*(i-1)+theta2/2) ' the electrode center point y-coord Call getDocument().getView().selectAt(xc, yc, infoSetSelection, Array(infoSliceSurface)) Call getDocument().getView().makeComponentInALine(hh1(j-1), Array("E"+CStr(ii)), _ "Name="+ElectrodeMaterial, infoMakeComponentUnionSurfaces Or infoMakeComponentRemoveVertices) Next Next ' Create the two shields ' move the construction plane to the beginning of the lower shield hhh=-(h2+2*h1+3*d2+d2+sh) Call getDocument().getView().getSlice().moveInALine(hhh) ' Create Shield#1 Call cylinder(0, 0, r1, r2, sh, ElectrodeMaterial, "Shield#1", 2) ' move the construction plane to the beginning of the upper shield hhh=2*h2+2*h1+4*d2+sh+d2 Call getDocument().getView().getSlice().moveInALine(hhh) ' Create Shield#2 Call cylinder(0, 0, r1, r2, sh, ElectrodeMaterial, "Shield#2", 2) ' Create insulation between the electrodes and the outer shield ' first, move the construction plane to the bottom position of the sensor Call getDocument().getView().getSlice().moveInALine(-hhh) Dim hsensor, hpipe, ha hsensor=2*h2+2*h1+2*sh+5*d2 Call cylinder(0, 0, r3, r4, hsensor, Plastic1_5, "Insulation", 2) ' Create the pipe 'first, move the construction plane to the bottom position of the pipe Call getDocument().getView().getSlice().moveInALine(-dh) hpipe=hsensor + 2*dh ' pipe height Call cylinder(0, 0, r1, r3, hpipe, Plastic3, "Pipe", 2) ' Create the Internal content of the pipe (hollow cylinder) Call cylinder(0, 0, r0, r3, hpipe, Plastic_media, "Internal_content", 2)

15

Page 16: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

' Create the Inhomogeneity in the center (cylinder) Call cylinder(0, 0, 0, r0, hpipe, Plastic_media, "Inhomogeneity", 1) ' Create the Airbox Call cylinder(0, 0, 0, r4, hpipe, "AIR", "Airbox", 1) ' make the 32 electrodes For i=1 to 4*n Call getDocument().makeElectrode("E"+CStr(i)) Next ' Set only Electrode #1 to potential 1 V ( Volts=1 ) ' by default the others will have potential 0 V Call getDocument().setElectrodeVoltage("Electrode#1", Volts, 0) ‘ the last parameter is the voltage phase !!! ' Specify boundary conditions Call getDocument().createBoundaryCondition(Array("Airbox,Face#1", "Airbox,Face#2"), "BoundaryCondition#1") Call getDocument().setElectricFluxTangential("BoundaryCondition#1") Call getDocument().createBoundaryCondition(Array("Airbox,Face#3", "Airbox,Face#4"), "BoundaryCondition#2") Call getDocument().setGround("BoundaryCondition#2") Call getDocument().createBoundaryCondition(Array("Shield#1", "Shield#2"), "BoundaryCondition#3") Call getDocument().setGround("BoundaryCondition#3") ' make the construction grid invisible Call getDocument().getView().showGrid(False) ' fit the drawing to screen size Call getDocument().getView().setScaledToFit(True) ' delete construction plane lines and arcs Call getDocument().getView().selectAll(infoSetSelection, Array(infoSliceLine, infoSliceArc)) Call getDocument().getView().deleteSelection() ' Start a static solve. Dim Doc Set Doc= getDocument() If (Doc.isValidForStatic3dSolver()) Then If (Doc.solveStatic3d()) Then Call RefreshSolutionMeshesInViews(Doc) Call RefreshFieldsInViews(Doc, "Contour", infoScalarField) Call RefreshFieldsInViews(Doc, "Shaded", infoScalarField) Call RefreshFieldsInViews(Doc, "Arrow", infoVectorField) End If End If Set Doc= Nothing ' postprocessing ' save the model en-file Call getDocument().save(fname1) ' compute the capacitances Dim charge, CC, sss, nn nn=4*n ' total number of electrodes sss=" Capacitances: " & vbNewLine For i=1 to nn charge = getDocument().getSolution().getChargeOnElectrode (1, "Electrode#"+CStr(i)) CC=abs(charge/Volts)

16

Page 17: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

sss=sss & "C1"+CStr(i)+" = " & CC & vbNewLine Next MsgBox sss ' save the capacitances in text file Call WriteTextFile(fname2, sss) ' End of Main program ‘===== Subroutines ============================== Sub cylinder(cx, cy, ra, rb, h, matname, compname, typ) ‘ create cylinder component 'typ=1 - solid cylinder, only rb used 'typ=2 - hollow cylinder ' delete the arcs and lines in the construction plane Call getDocument().getView().selectAll(infoSetSelection, Array(infoSliceLine, infoSliceArc)) Call getDocument().getView().deleteSelection() ' delete the arcs and lines in the construction plane ' draw and extrude the cylinder ' solid cylinder If typ=1 then Call getDocument().getView().newCircle(cx, cy, rb) ra=0 End If ' hollow cylinder if typ=2 then Call getDocument().getView().newCircle(cx, cy, rb) Call getDocument().getView().newCircle(cx, cy, ra) End If Call getDocument().getView().selectAt(cx+(ra+rb)/2, cy, infoSetSelection, Array(infoSliceSurface)) REDIM ArrayOfValues(0) ArrayOfValues(0)= compname If matname="AIR" then

Call getDocument().getView().makeComponentInALine(h, ArrayOfValues, "Name="+matname, _ infoMakeComponentUnionSurfaces Or infoMakeComponentRemoveVertices Or infoMakeComponentIgnoreHoles )

' it is recommended for Airbox to make active IgnoreHoles Else

Call getDocument().getView().makeComponentInALine(h, ArrayOfValues, "Name="+matname, _

infoMakeComponentUnionSurfaces Or infoMakeComponentRemoveVertices) End if Call getDocument().getView().selectAll(infoSetSelection, Array(infoSliceLine, infoSliceArc)) Call getDocument().getView().deleteSelection() ' delete the arcs and lines in the construction plane End Sub

17

Page 18: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Example Script 3 - Exporting the mesh and the node potentials to text file Option Explicit ‘ Exports the mesh and the potentials in the nodes Const path="C:\Documents and Settings\kosta\My Documents\ElecNet\" Const name="sens4n" Dim Doc, Sol, Mesh, PID, i, j, OutputString, Field, fname fname=path+name+"_mesh.txt" Set Doc = getDocument Set Sol = Doc.getSolution ' Note that this will not work for Transient models. A time instant also has to be included. PID = 1 Set Mesh = Sol.getMesh(PID) Set Field=Sol.getSystemField(Mesh,"V") ' The potentials in the nodes ReDim MeshElements(0), MeshNodes(0) Dim Pot ' To get the coordinates of each of the mesh elements, the values are returned in the array Call Mesh.getElements(MeshElements) ' The node numbers of all mesh elements Call Mesh.getNodes(MeshNodes) ' The coordinates of all mesh nodes Dim NumberOfElements, NumberOfNodes, NumberOfNodesPE, String1, String2 NumberOfElements=Mesh.getNumberOfElements() NumberOfNodes=Mesh.getNumberOfNodes() NumberOfNodesPE=Mesh.getNumberOfNodesPerElement() String1=NumberOfElements & " " & NumberOfNodes & " " & NumberOfNodesPE Dim fso, a Set fso = CreateObject("Scripting.FileSystemObject") Set a = fso.CreateTextFile( fname, True) ' True- means the file can be overwritten a.WriteLine(String1) ' write nodes for every element For i = 0 To NumberOfElements-1 String2 = i for j = 0 to NumberOfNodesPE-1 String2 = String2 & " " & MeshElements(i,j) Next a.WriteLine(String2) Next ' write xyz coordinates of every node and the potential of the node For i = 0 To NumberOfNodes-1 String2 = i for j = 0 to 2 String2 = String2 & " " & MeshNodes(i,j) Next Call Field.getFieldAtPoint(MeshNodes(i,0),MeshNodes(i,1),MeshNodes(i,2),Pot ) String2 = String2 & " " & abs(Pot(0)) a.WriteLine(String2) Next a.Close

18

Page 19: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Example script 4 - Reading / Writing Option Explicit ' example for reading/writing files using ' readTextFile and writeTextFile functions ' the input numbers must be in one line, separated by a space ' specify text file names Const path="C:\Documents and Settings\kosta\My Documents\ElecNet\vbs\" Const name="info" Dim fname1, fname2 fname1=path+name+".txt" fname2=path+name+"_2.txt" Dim xmin, xmax, ymin, ymax, zmin, zmax, npx, npz, r1 Dim Input, results, n ' reads the input text file CALL readTextFile(fname1, results) ' Splits the values on a line based on the token, in this case a white space Input = Split(results, " ") n = UBound(Input)+1 ' specify some text constants, describing the variables Dim sss, i ReDim text(n-1) text(0)="xmin" text(1)="xmax" text(2)="ymin" text(3)="ymax" text(4)="zmin" text(5)="zmax" text(6)="ne" text(7)="npx" text(8)="npy" text(9)="npz" text(10)="npp" ' create a string with the descriptions and the values of the data items sss=" Input data: " & vbNewLine For i=1 to n sss=sss & text(i-1) & " = " & Input(i-1) & vbNewLine Next ' print the string in a message box MsgBox sss ' write the string in a file Call WriteTextFile(fname2, sss)

19

Page 20: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Example script 5 – Getting |E| in arbitrary point, specified by numerical coordinates 'Script to get values of |E| at points in a 2D field Set Mesh = getDocument.getSolution.getMesh(1) Set Field = getDocument.getSolution.getSystemField _ (Mesh,"|E| smoothed") ReDim Value(0) Do X = InputBox("Enter the X co-ordinate:",,0) Y = InputBox("Enter the Y co-ordinate:",,0) Call Field.getFieldAtPoint (X, Y, 0, Value) Response = MsgBox("The value of |E| is " & Value(0) & Chr(10) _ & "Enter another point?", VbYesNo) Loop Until (Response = VbNo)

20

Page 21: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Some pictures of 3D ECT sensors, modelled using ElecNet:

Fig. 1 : Rectangular shape 32-electrode sensor, developed at KIS

21

Page 22: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Fig. 2 : Circular electrodes sensor, shifted layers, minimal gaps

22

Page 23: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Fig. 3: Right-angle triangular elelctrodes

23

Page 24: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Fig. 4: Equilateral triangular elelctrodes

24

Page 25: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Fig. 5: Rectangular electrodes, shifted layers

25

Page 26: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Fig. 6: Rhomboidal electrodes

26

Page 27: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Fig. 7: Trapezoidal electrodes (64-electrode sensor)

27

Page 28: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Fig. 8: Rectangular electrodes with radial strip shields

28

Page 29: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Fig. 9: Rectangular electrodes with radial bar shields

29

Page 30: Introduction to programming in Visual Basic Scripts for ... · Introduction to programming in Visual Basic Scripts for Elecnet The aim of this lecture is to present shortly the writing

Further topics on ElecNet, not covered in these lectures:

1. Parameterization 2. Creating script forms 3. Controlling ElecNet by Excell and Matlab 4. Importing and exporting 3D models 5. Creating animations 6. Current flow problems 7. Time-harmonic problems 8. Transient analysis

Information on these topics can be found in the ElecNet Manuals [1,2,3].

REFERENCES: 1. J. D. Edwards, An Introduction to ElecNet for Static 2D Modeling, Infolytica

Corporation, Montréal, Québec, 2007. 2. MagNet/ElecNet/ThermNet/FullWave Scripting Manual, Infolytica Corporation, 2004. 3. ElecNet v. 6.18, Electrostatic/Current Flow/Time-harmonic/Transient 2D & 3D Tutorials,

Infolityca Corporation, 2008. 4. W. H. Hayt Jr., J. A. Buck, Engineering Electromagnetics, 6th ed., McGraw Hill, New

York, 2000. 5. Z. Popovic, B. Popovic, Introductory Electromagnetics. Prentice Hall, 2000. 6. P.P. Silvester, R.L. Ferrari, Finite Elements for Electrical Engineers, 2nd ed., Cambridge

University Press, 1990.

30