Académique Documents
Professionnel Documents
Culture Documents
Application Builder
Introduction to Application Builder
19982014 COMSOL
Protected by U.S. Patents listed on www.comsol.com/patents, and U.S. Patents 7,519,518; 7,596,474; 7,623,991; and
8,457,932. Patents pending.
This Documentation and the Programs described herein are furnished under the COMSOL Software License
Agreement (www.comsol.com/comsol-license-agreement) and may be used or copied only under the terms of the
license agreement.
COMSOL, COMSOL Multiphysics, Capture the Concept, COMSOL Desktop, and LiveLink are either registered
trademarks or trademarks of COMSOL AB. All other trademarks are the property of their respective owners, and
COMSOL AB and its subsidiaries and products are not affiliated with, endorsed by, sponsored by, or supported by
those trademark owners. For a list of such trademark owners, see www.comsol.com/trademarks.
Version: October 2014 COMSOL 5.0
Contact Information
Visit the Contact COMSOL page at www.comsol.com/contact to submit general inquiries, contact
Technical Support, or search for an address and phone number. You can also visit the Worldwide
Sales Offices page at www.comsol.com/contact/offices for address and contact information.
If you need to contact Support, an online request form is located at the COMSOL Access page at
www.comsol.com/support/case.
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Future Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
The Application Builder Desktop Environment . . . . . . . . . . . . . . 9
Running an Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Password Protection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
The Form Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
The Forms Settings Window. . . . . . . . . . . . . . . . . . . . . . . . . . 25
The Individual Form Settings Windows . . . . . . . . . . . . . . . . . 25
Form Editor Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Form Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Button. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Input Field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Text Label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Data Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
The Main Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Menu Bar and Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Ribbon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Events at Startup and Shutdown. . . . . . . . . . . . . . . . . . . . . . . 55
Global Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Form and Form Object Events . . . . . . . . . . . . . . . . . . . . . . . . 57
|3
Using Local Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Scalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Array 1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Array 2D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Choice List. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
The Method Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Converting a Command Sequence to a Method . . . . . . . . . 77
Recording Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Model Code Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Model Data Access. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Language Elements Window. . . . . . . . . . . . . . . . . . . . . . . . . . 86
Checking Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Find and Replace. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Model Expressions Window . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Extracting Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Syntax Highlighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Method Editor Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Ctrl+Space and Tab for Code Completion . . . . . . . . . . . . . 91
Local Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Methods with Input and Output Arguments. . . . . . . . . . . . . 93
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
The Model Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Language Element Examples . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
4|
Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Appendix AForm Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
List of All Form Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Check Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Combo Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Web Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Progress Bar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Message Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Results Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Form Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Card Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
File Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Array Input. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Radio Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Selection Input. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
List Box. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Slider. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Toolbar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Spacer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Appendix BGrid Layout Mode . . . . . . . . . . . . . . . . . . . . . . . 168
Appendix CKeyboard Shortcuts . . . . . . . . . . . . . . . . . . . . . . 172
|5
Appendix DBuilt-in Functions and Methods . . . . . . . . . . . . 174
Appendix EGuidelines for Building Applications . . . . . . . . . 206
Appendix FThe Application Library Examples. . . . . . . . . . . 209
6|
Introduction
Introduction |7
Future Versions
You can look forward to exciting additions and significant improvements to the
Application Builder during the upcoming year. There will be two new releases:
V5.1 in February 2015, and V5.2 in the fall of 2015.
Some things that will be done for V5.1:
FORM E DITOR
Copy forms and form objects between applications
Modify multiple form objects at the same time
Background image for forms
Better progress GUI support
M ETHOD E DITOR
Code folding (+)
Add Ctrl-Alt-double-click in method editor code to open clicked method in
method editor
G ENERAL
Merge the.mph and .mphapp formats to .mph
Microsoft Excel file export/import with LiveLink for Excel
COMSOL S ERVER
The COMSOL Server will be released shortly after the release of V5.0.
8 | Future Versions
The Application Builder Desktop Environment
The screenshot above is what you will see when you first start working with the
Application Builder. The main components of the Application Builder desktop
environment are:
Application Builder window and ribbon tab
COMSOL Desktop environment
Form Editor
Method Editor
Use the Form Editor for user interface layout by creating forms with form objects
such as input fields, graphics, and buttons.
The main components of the Form Editor are:
Form ribbon tab
Explorer window with the application tree
Form window
Settings window
Use the Method Editor to write methods for actions not covered by the standard
use of the model tree nodes.
The main components of the Method Editor are:
Method and Debug ribbon tabs
Explorer window with the application tree
Method window
Model Expressions, Language Elements, and Model Code windows
Settings window
If a method already exists, say with the name method1, then you open the Method
Editor using, for example, any of these ways:
In the application tree, double-click the method1 node.
In the application tree, right-click the method1 node and select Edit.
Below the command sequence in the Settings window of a form object or an
event, click Go to Method.
You can associate objects such as buttons, menu items, ribbon buttons, forms, and
form objects with actions triggered by an event. An action can be a sequence of
commands including global methods or local methods that are not visible outside
the object where it is defined. The events that can be associated with an object
depend on the type of object and include: button click, keyboard shortcut, load of
a form (On load), and change of the value of a variable (On data change).
In COMSOL Multiphysics, you run an application using any of these three ways:
Click Test Application in the Application tab in the ribbon.
Select Run Application from the File menu.
Double-click an MPHAPP-file.
TESTING AN A PPLICATION
Test Application is available in the Application tab and is used for quick tests. It
opens a separate window with the application user interface while keeping the
Application Builder desktop environment running.
While testing an application, you can apply changes to forms and methods by
clicking the Apply Changes button. To test the layout of a form without running
the application, click Test Form in the ribbon of the Form Editor.
When Test Application is used, all methods are automatically compiled with the
built-in Java compiler. Any syntax errors will generate error messages and the
process of testing the application is stopped. To check for syntax errors before
testing an application, click the Check Syntax button in the ribbon of the Method
Editor.
Check Syntax finds syntax errors by compiling the methods using the built-in
Java compiler. Any syntax errors will, in this case, be displayed in the Errors and
Warnings window in the Method Editor. For more information, see The Method
Editor on page 77.
R UNNING AN A PPLICATION
Run Application is available from the File menu and starts the application in the
COMSOL Desktop, replacing the Application Builder desktop environment.
Select Run Application to use an application for production purposes. For
14 | Running an Application
example, you can run an application that was created by someone else that is
password protected from editing, but not from running.
As an alternative, you can add a button or menu item with a command to save the
application. For more information, see page 53.
Running an Application | 15
A PPLICATION L IBRARIES
From the File menu, select Application Libraries to run and explore the example
applications that are included in the COMSOL installation. Many of the
screenshots in this book are taken from these examples.
16 | Running an Application
You run an application or open it for editing by clicking the corresponding
buttons below the Application Libraries tree.
Pas sword P ro t e c t i o n
Running an Application | 17
When you open a password-protected MPHAPP-file, for editing or running, a
dialog box prompts you for the password:
18 | Running an Application
Getting Started
If you dont have a model loaded, select File>New, and then click Application
Wizard.
Getting Started | 19
Select a model (.mph) from the Model Libraries or click Browse to select from
some other location, and then click Open.
A dialog box with progress bar appears with the text Creating new application
from model.
When the progress bar has finished, the New Form window will open.
C REATING A N EW FORM
The New Form window aids in the initial user interface layout and is displayed by
the Application Wizard after a model is saved or selected for use as an application.
When a model is saved as an application, the New Form window is displayed as a
dialog box. The New Form window assists you with adding the most common
user interface components, so-called form objects, to the first form of your
application. It has three tabs:
Inputs/outputs
20 | Getting Started
Graphics
Buttons
Double-click a node or click the Move to Selected button to move a node from
the Available area to the Selected area. The selected nodes will become form
objects in the application, and a preview of the form is shown in the Preview area
to the right. The size as well as other settings for form objects can be edited after
exiting the Application Wizard.
You can also choose to exit the New Form window at this stage by clicking Done.
Getting Started | 21
In the figure below, three parameters Length, Width, and Applied voltage have
been selected to serve as input fields:
After exiting the Application Wizard, you can edit the size and font color as well
as other settings for input fields and data display objects.
22 | Getting Started
The Graphics Tab
The Graphics tab displays the model tree nodes that can serve as graphics objects:
Geometry, Selection, Mesh, and Results. In the figure below, two such nodes have
been selected.
Getting Started | 23
In the figure below, three buttons have been added for plotting the Geometry,
plotting the Mesh, and running a Study.
Using the Form Editor, you can add buttons that run your own custom command
sequences or methods.
S AVING AN A PPLICATION
To save an application, from the File Menu, select File>Save As. Browse to a folder
where you have write permissions, and save the file in the MPHAPP-file format.
The MPHAPP-file contains all the information about the model and the
application.
24 | Getting Started
The Form Editor
Use the Form Editor for user interface layout to create forms with form objects
such as input fields, graphics, buttons, and more.
T h e Fo r m s S e t t i n g s W i n d ow
The Settings window for forms is displayed when you click the Forms node in the
application tree. It lets you change the overall appearance of forms with settings
for text color, background color, and font.
T h e I n d i v i d u a l For m S e t t i n g s W i n d ow s
Each form has its own Settings window with sections for:
a Name used to reference the form in other form objects and methods
a form Title that is used in applications with several forms
when to store changes in dialog boxes (Store changes in dialogs)
the Initial size of the form when used as a dialog box or when the Main
Window is set to have its size determined by the form
if the form should be Resizable when used as a dialog box
the Margins with respect to the upper-left corner
viewing sections in expanded or collapsed format (Section Settings)
Double-click a form node to open its window in the Form Editor. Right-click a
form window tab to see its context menu with options for closing, floating, and
tiling form windows.
For m Ed i t o r Prefe re n c es
To access Preferences for the Form Editor, choose File>Preferences and select the
Form Editor section.
The Form Editor section in Preferences includes settings for changing the defaults
for Layout mode, Margins, and Sketch grid.
D ELETING AN O BJECT
To delete an object, click to select it and then press Delete on your keyboard. You
can also click the delete button in the quick access toolbar.
The remainder of this section The Form Editor describes the types of form
objects that are added by the Application Wizard:
Button
Graphics
Input Field
Text Label
Unit
Data Display
For information on the other form objects, see Appendix AForm Objects on
page 106.
Button
A button is triggered by a button click event. The main section of the Settings
window for a button allows you to:
Edit the form object name of the button.
Edit the text displayed on the button.
Use a picture instead of the default rendering of a button.
Change the button size from normal to large.
Add a tooltip with a text that is shown when hovering over the button.
Add a keyboard shortcut by clicking the input field and enter a combination
of the modifier keys Shift, Ctrl, and Alt together with a keyboard key. Alt
must be accompanied by at least one additional modifier.
Some commands require an argument, such as the different plot commands. The
argument to a plot command defines which of the different graphics objects the
plot should be rendered in.
The example below shows the Settings window and command sequence for a
Compute button as created by the Application Wizard.
This button has a command sequence with two commands: Compute Study 1 and
Plot Temperature. Plot commands are generated automatically by the Application
Wizard corresponding to the graphics objects that are added in the wizard. The
Plot Temperature command has one argument graphics1. To add or edit an
When you click the button in the application, the following dialog box
corresponding to form2 is displayed.
In the Settings window, the Dialog Actions section has two check boxes:
Close dialog
Store changes
In the example above, the Close dialog check box is selected. This ensures that the
form2 window is closed when the OK button is clicked. Since form2 does not
have any user inputs, there is no need to select the Store changes check box.
Typical dialog box buttons and their associated Dialog Actions are:
A dialog box is modal and blocks any other user interaction with the application.
This means that in a form that is used as a dialog box you need to create at least
one button with the Close dialog check box selected.
In order to control when data entered in a dialog box is stored, there is a list in
the top section of the Settings window of a form where you can select whether to
G r ap h i c s
Each graphics object gets a default name such as graphics1, graphics2, etc.
These names are used to reference graphics objects in command sequences for
buttons, menu items, and in methods. To reference graphics objects in a specific
form, use the syntax: /form1/graphics2, /form3/graphics1, etc.
In addition to Results plot nodes, you can also use Selection, Geometry, and Mesh
nodes as the Selected source.
A PPEARANCE
For a graphics object, the Appearance section of the Settings window allows you
to:
include the standard plot toolbar
include an icon such as a logo image in the upper-right corner
set the background color for 2D plots
set a flat or graded background color for 3D plots
An input field allows a user to change the value of a parameter or variable. In the
Application Wizard, when a parameter or variable is selected, three form objects
are created:
a text label object for the parameter or variable description
an input field object for the value
a unit object (if applicable)
To insert an additional input field, use the Insert Object menu in the ribbon Form
tab and select Input Field. In the Form Editor, you link it to a certain parameter
or variable by selecting it from the model tree in the Source section. In the Source
section you can also set an Initial value. The figure below shows the Settings
window for an input field.
If the Editable check box is cleared, then the Initial value will be displayed by the
application and cannot be changed.
The Filter list for option Append unit to number only allows for the Double and
Integer options.
The Double and Integer options filter the input based on a Minimum and
Maximum value. If the input is outside of these values, an error message is
displayed.
The Regular expression option allows you to use a regular expression for matching
the input string and to also generate a custom Error message. For more
information on regular expressions, see the dynamic help. Click the help icon in
the upper-right corner of a window and search for regular expression.
You need to enable Model Data Access this way because a model typically contains
hundreds or even thousands of properties that could be accessed and the list would
be too long to be practical.
Model Data Access can also be used for Data Display, Combo Boxes, and other
form objects.
Unit
In the Settings window for a unit object you can set the unit to a fixed expression
or link it to an input field. Click the Go to Source button to the right of the Unit
When adding an input field using the Application Wizard a unit object is
automatically added when applicable. By default, the unit is displayed using
Unicode rendering. As an alternative, you can use LaTeX rendering by selecting
the LaTeX markup check box. Then the unit display does not rely on the selected
font.
Tex t L a b el
A text label object simply displays text in a form. When adding an input field using
the Application Wizard a text label object is automatically added for the
description text of the associated parameter or variable. There is a check box
To insert an additional text label, use the Insert Object menu in the ribbon Form
tab and select Text Label.
D a t a D i s p l ay
A data display object is used to display the output from a Derived Values node
such as Global Evaluation or Volume Maximum. In the Application Wizard,
when a Derived Values node is selected, two form objects are created based on the
corresponding Derived Values node variable:
a text label object for the description of the variable
a data display object for the value of the variable
The settings for these form objects can be edited after exiting the Application
Wizard. To insert an additional data display object, use the Insert Object menu in
the ribbon Form tab and select Data Display.
By default, the unit of a data display object is displayed using Unicode rendering.
As an alternative, you can use LaTeX rendering by selecting the LaTeX markup
check box. Then the data display does not rely on the selected font.
In the application tree, the Main Window node represents the main window of an
application and is also the top-level node for the user interface. It contains the
window layout, the main menu specification, and an optional ribbon specification.
G ENERAL S ETTINGS
The Settings window contains a General section with settings for the:
Title
Icon
Menu type
Status bar
The Title is the text at the top of the Main Window in an application, with the
Icon shown to the left of this text. By default, it is the same as the title of the model
used to create the application.
In the Icon field, select an image from the library or add an image (*.png)
from the local file system to the library and use it as an icon. If you add a new
image, it will be added to the image library and thereby embedded into the
application.
There is one child node to the Main Window called Menu Bar. With the Menu
type setting, you can switch from Menu Bar to Ribbon.
The Status bar list controls what is shown in the status bar: Select Progress for
displaying a progress bar when applicable (the default) or None.
M e nu B a r a n d To o l b a r
The Menu Bar node can have Menu child nodes that represent menus at the top
level of the Main Window.
A Menu node can have child Menu nodes that represent submenus.
The Settings window for the Save As item is shown in the figure below.
Ribb on
You can opt to add a Ribbon to the Main Window instead of a Menu Bar. The
Ribbon node contains the specifications of a ribbon with tabs.
You can associate objects such as buttons, menu items, ribbon buttons, forms, and
form objects with actions triggered by an event. An action can be a sequence of
commands including global methods or local methods that are not visible outside
the object where it is defined. The events that can be associated with an object
depend on the type of object and include: button click, keyboard shortcut, load of
a form (On load), and change of the value of a variable (On data change).
Using Ctrl-Alt-click on the form object opens the method in the method editor.
If there is no method associated with the form object, a new local method will be
created, associated with the form object, and opened in the method editor.
In the application tree, the Events node contains all global events that are
triggered by changes to the various data entities, such as global parameters or
string variables. Global events can also be associated with the startup and
shutdown of an application. In addition to the global events, form and form
objects can have associated events defined in their Settings windows.
E ve n t s a t S t a r t u p a n d S h u t d ow n
Global or local methods can be associated with the events of startup (On startup)
and shutdown (On shutdown) of an application. To access these events, click the
Events node in the application tree.
Events | 55
A method run at a shutdown event can, for example, automatically save critical
data or prompt the user to save data.
G l o b a l E ve n t s
Right-click the Events node and choose Event to add an event to an application.
An event listens for a change in a running application. If a change occurs, it runs
a sequence of commands. You can, for example, use events to control which
method to run when the value of the combo box is changed by the user. In the
figure below, when the value of the string variable svar is changed, method1 is
run.
Note that since this type of event has global scope and is not associated with a
particular form, the full path: /form1/graphics1 needs to be used when
referencing graphics objects.
56 | Events
The following sections describe the options available in the Event Settings
window.
C HOOSE C OMMANDS TO R UN
This section is similar to that of a button and enables you to define a sequence of
commands. For more information, see Button on page 32.
Form and form object events are similar to global events but are defined for forms
or individual form objects. These events have no associated command sequence
but refer directly to one global or local method.
The list On data change contains None (the default), any available methods under
the Methods node, or a local method.
The form objects supporting this type of event are:
input field
check box
combo box
Events | 57
file import
radio button
text
list box
slider
This type of event is available in the Settings window of a form and is typically used
when a form is shown as a dialog box or to activate forms used as panes in a form
collection.
Events can call local methods that are not displayed in the application tree. For
more information on local methods, see Local Methods on page 92.
58 | Events
Declarations
The Declarations node in the application tree is used to declare global variables in
addition to the global parameters and variables already defined in the model.
Variables under the Declarations node are used in form objects and methods. In
form objects, they store values to be used by other form objects or by methods.
Variables that are not passed between form objects and methods, but that are
internal to methods, do not need to be declared in the Declarations node. In
methods, variables defined under the Declarations node have global scope and can
be used directly with their name (without any access methods).
There are five different types of declarations:
Scalar
Array 1D
Array 2D
Choice List
File
In addition, the first three types of declarations can be of the following types:
String
Boolean
Integer
Double
Scalar
Declarations | 59
parameter or variable in a model. You can use a string variable as a double, integer,
or Boolean by using conversion functions in a method; for more information see
Conversion Functions on page 175.
S TRING
You can use a string variable as a source in many of the form objects, such as input
fields, combo boxes, and check boxes. A global parameter or variable in a model
has the restriction that its value has to be a valid model expression, while a scalar
string variable has no such restriction.
The figure below shows the Settings window in Declaration for two string
variables svar_results and svar_mat.
60 | Declarations
The figure below shows the Settings window for a combo box with the string
variable svar_mat used as the source.
Declarations | 61
The figure below shows the Settings window for a string variable distance used
as the source for an input field.
The Default value of an input field will overwrite a Default value in a declaration.
62 | Declarations
B OOLEAN
You can use a Boolean variable as a source in check boxes, other form objects, and
methods. A Boolean variable can have two states: on or off (true or false). The
default value is off.
Example Code
In the example code below, the boolean variable bvar has its value controlled by
a check box. If bvar is on (or true) then plot group 4 (pg4) is plotted in
graphics1, else plot group 1 (pg1) is plotted.
if (bvar) {
useGraphics(model.result("pg4"),"graphics1");
} else {
useGraphics(model.result("pg1"),"graphics1");
}
Declarations | 63
I NTEGER AND D OUBLE
Integer and double variables are similar to strings, with the additional requirement
that the value is an integer or double, respectively.
For an input field linked to an integer variable, an error message is displayed if the
entered value is not an integer:
A rr ay 1 D
The Array 1D node declares one or more named arrays of strings, Booleans,
integers, or doubles that you can access from form objects and methods. The
number of elements in a 1D array is not restricted in any way, and you can, for
example, use a 1D array to store a column in a table with variable number of rows.
The Settings window contains a single table, where you specify one variable array
64 | Declarations
per row. In the figure below, two double arrays are declared, xcoords and
ycoords.
The New element value is assigned to new elements of the array in certain add
operations, such as when adding a row to a table. Arrays for strings, Booleans, and
integers are functionally similar to arrays of doubles.
I NITIAL VALUES
The initial value can be a 1D array of arbitrary length. To edit the initial values,
click the Edit Default button below the List of Variables. This opens a dialog box
for typing the value of each component. See the figure below for an example of a
1D array of integers.
Declarations | 65
A RRAY S YNTAX
An array definition must start and end with curly braces ({ and }), and you
separate each element with a comma. In the cases where you need any of these
special characters inside an array element (spaces and commas, for example),
surround the element with single quotes ('). The table below shows a few
examples of 1D arrays:
A rr ay 2 D
The Array 2D node declares one or more 2D arrays that you can access from form
objects and methods. In the figure below, a 2D double array xycoords is
declared.
66 | Declarations
I NITIAL VALUES
The default (or initial) value can be a 2D array of arbitrary size. To edit the initial
values, click the Edit Default button below the List of Variables. This opens a
dialog box for typing the value of each component; see the figure below.
A RRAY S YNTAX
The table below shows a few examples of 2D arrays:
Choice List
The Choice List node contains a list of choices for combo boxes, radio button, and
list boxes. The Settings window contains a Name field and a table with a Value
column and a Display name column. Enter the property values in the first column
and the corresponding text to display to the user in, for example, a combo box list
Declarations | 67
in the second column. The value is always interpreted as a string. In the example
below, mat1 will become the string mat1 when returned from the combo box.
A CTIVATION C ONDITION
You can right-click the Choice List node to add an Activation Condition subnode.
Use an activation condition to switch between two or more choice lists contingent
on the value of a variable. For an example of using choice lists with activation
conditions, see Using a Combo Box to Change Material on page 115.
68 | Declarations
File
A File declaration node is typically used in a file import object, although it can
also be used in methods. The figure below shows the Settings window of a file
declaration.
A file import object allows the user of an application to browse and select a file to
be uploaded to the application at run time. The file chosen by the user can be
referenced in a method by using the syntax upload:///file1,
upload:///file2, etc. This syntax can also be used in any file browser text fields
in a model. The figure below shows a file reference used in the Filename field of
the Import model tree node for a model using geometry import.
For an example of using a file import object, see File Import on page 140.
Declarations | 69
F ILE S CHEME S YNTAX
In addition to the file scheme syntax upload:///, there are file schemes for
temporary files and shared files. The table below summarizes all available file
schemes.
For more information on how to use the embedded:/// syntax, see Libraries
on page 102.
The table below summarizes the usage of the different file schemes. In the table,
a check mark means that this scheme is available, and (r) means that it is the
recommended scheme.
70 | Declarations
You can set the preferences for the paths to temporary, user, and common files in
the Files page of File>Preferences, as shown in the figure below.
Declarations | 71
Commands>File Commands>Save File As. As an input argument to the
command, use the file scheme syntax temp:/// shown in the figure below.
72 | Declarations
This example saves a cut line plot from the Export node in the model tree. The
figure below shows the Settings window for the corresponding Export>Plot node.
As an alternative to using the temp:/// scheme, you can select the check box
Always ask for filename. This allows you to leave the Filename field blank and also
Declarations | 73
skip the call to Save File As in the button command sequence as shown in the
figure below.
C REATING R EPORTS
The example below shows an application where a report in the Microsoft Word
format (.docx) can be saved by the user. The figure below shows the Simulation
tab in the ribbon of the application. In this tab, there is a Create button in the
Report section.
74 | Declarations
The associated application tree node is shown in the figure below.
The following figure shows how the syntax temp://file was used in the
Filename field in the Settings window of the Report node.
In this application, the check box Open finished report is selected, which means
that the Word document will open after the report has been created. The user of
the application can then save the report from the Word file menu.
In this example, the file schemes user:/// or common:/// could have been used
in the same way if the check boxes Always ask for filename or Open finished report
Declarations | 75
had not been selected. The user and common file schemes are primarily useful
when the same files are used repeatedly by an application.
The figure below shows the Settings window of the Create Microsoft Word
Report ribbon item.
The file scheme syntax can also be used in methods. The code below is from a
method used to export an HTML report.
String answerh = request("Enter file name","File Name", "Untitled.html");
if(answerh != null){
model.result().report("rpt1").set("format","html");
model.result().report("rpt1").set("filename","user:///"+answerh);
model.result().report("rpt1").run();
}
76 | Declarations
The Method Editor
Use the Method Editor to write methods for actions not covered by the standard
run commands of the model tree nodes. By using built-in functions and methods,
you can modify a model object. The model object is the data structure that stores
the state of the COMSOL Multiphysics model that is embedded in an application.
You can also write methods that, for example, include for-loops, process inputs
and outputs, and messages and alerts sent to the user of an application. For more
information see, Appendix DBuilt-in Functions and Methods on page 174.
The Java programming language is used to write COMSOL methods, which
means that Java statements and syntax in general can be used.
A number of tools and resources are available to help you create code for
methods. These are covered in the following sections and will make you
more productive by allowing you to copy-paste or auto-generate blocks of
code.
C o nve r t i n g a C o m m a n d S e q u e n c e t o a M e t h o d
In the Form Editor, click the Convert to New Method button in the command
sequence of a Settings window. The command sequence is automatically replaced
by an equivalent method.
In the method editor, add a second line that plays the library sound
success.wav.
The newly added line is indicated with a green bar to the left.
Using Ctrl-Alt-click on the form object opens the method in the method editor.
If there is no method associated with the form object a new local method will be
created, associated with the form object, and opened in the method editor.
In this example, both the check box called Find prong length and the Compute
button have associated methods.
R e c o rd i n g C o d e
Click the Record Code button in the Method tab of the Method Editor to record
a sequence of operations that you perform using the model tree in the Application
Builder window, as shown in the figure below.
The code is recorded in the active method window, if any. If no method window
is opened, a new method will be created.
In the Model Code window in the Method Editor, right-click a model tree node
to generate code associated with that node. Depending on the node, up to eight
different options are available:
- Get
- Set
- Set All
- Create
- Run
- Enable
- Disable
- Edit Node
Selecting one of the first seven options will add the corresponding code to the
currently selected method. The Edit Node option brings you to the Settings
window for the model tree node.
The figure below shows an example of a node with six options.
if you position the cursor in surf1 and press F11 on the keyboard, the
corresponding Surface plot node is highlighted in the Model Code window. Click
the Edit Node to open its Settings window. For more information on keyboard
shortcuts, see Appendix CKeyboard Shortcuts on page 172.
To access individual properties of a model tree node, click the Model Data Access
button in the Declarations section of the Application ribbon tab:
The reason you need to enable Model Data Access this way is that a model
typically contains hundreds or even thousands of properties that could be accessed
and the list would be too long to be practical.
In the above example, Get and Set for the Heat transfer coefficient and the
External temperature properties will generate the following code:
model.physics("ht").feature("hf1").getString("h");
model.physics("ht").feature("hf1").set("h", "htc");
model.physics("ht").feature("hf1").getString("Text");
model.physics("ht").feature("hf1").set("Text", "293.15[K]");
The Language Elements window in the Method Editor shows a listing of some
Language Constructs. Double-click or right-click one of the items in the list to
insert template code in the currently selected method:
Checking Syntax
Click Check Syntax in the ribbon to see messages in the Errors and Warnings
window related to syntax errors or unused variables.
Click Find in the ribbon Method tab to open a dialog box used to find and replace
strings in methods, as shown in the figure below.
The Model Expressions window in the Method Editor shows a list of Model
Expressions used as input and output arguments. Double-click or right-click one
of the items in the list to insert the corresponding expression:
If you click Extract Variable in the Method tab, then the method editor checks the
source code at the cursor, and if it corresponds to an expression of a certain form,
the method editor creates a variable and replaces all subsequent uses of the
expression with that variable. When you click the button, an Extract Variable
dialog box opens where you can enter a suitable variable name in the Name field.
Click the Extract Variable button to transform the source code into what is shown
in the figure below.
The expression corresponding to the feature part of the source code has been
extracted into the variable mslc1.
Syntax Highlighting
Different language elements in the code are displayed using different styles:
You can customize the syntax highlighting theme in the Preferences dialog box.
See Method Editor Preferences below.
M e t h o d E d i t o r P re fe re n c e s
To access the Preferences for the Method Editor, choose File>Preferences and
select the Method Editor section.
By default, the Method Editor only shows the most relevant code. To see all code
in a method, select the Show all code check box.
The check box Close brackets automatically controls if the Method Editor should
automatically add closing brackets such as curly brackets {, brackets [, and
parentheses (.
The check box Generate compact code using with statements controls the
utilization of with statements in automatically generated code. For more
information, see The With Statement on page 99.
C t r l + S p a c e a n d Ta b fo r C o d e C o m p l e t i o n
While typing code in the Method Editor, you can get suggestions for code
completions. The list of possible completions are shown in a separate completion
list that opens. In some situations, detailed information appears in a separate
window when an entry is selected in the list. Code completion can always be
requested with the keyboard shortcut Ctrl+Space. When accessing parts of the
model object you will get a list of possible completions automatically, as shown in
the figure below:
Select a completion by using the arrow keys to select an entry in the list and press
the Tab or Enter key to confirm the selection.
If the list is long, you can filter by typing the first few characters of the completion
you are looking for.
If you enter the first few characters of, for example, a variable or method name and
press Ctrl+Space, the possible completions are shown:
Local Methods
You can add local methods to buttons, menu items, and events. Local methods do
not have nodes displayed under the Methods node in the application tree. In the
Method Editor window for a local method, its tab displays the path to its
associated user interface component, as shown in the figure below for the case of
a check box.
To avoid any risk of corrupting code in a local method, it is not allowed to use
Extract to New Method when there is a local method present in the command
sequence.
To open an existing local method in the Method Editor, click the Go to Source
button. Click the Remove Local Method button to delete the local method.
By using events, methods can be local to a form or form object. Such methods are
not displayed under the Methods node. For more information, see Events on
page 55.
A method is allowed to have several input arguments and one output argument.
You define input and output arguments in the Settings window of an active
method window. If the Settings window is not visible, click Settings in the
Method tab. The figure below shows a method randomize with two input
Debu gging
Click the Debug tab in the Method Editor to view the tools available for
debugging methods. Click in the gray column to the left of the code line numbers
to set breakpoints. When you run the application, the method will stop at the
In the Main group of the Debug tab, click the Step button to go to the next line
in the method. Click Continue to run the method up until the next breakpoint.
Click Stop to stop running the method. Click Step Into to step into the next
method, if possible. Use Remove All to remove all break points. Instead of
removing, you can disable all break points by clicking Disable All. Click the Debug
Use the debugLog command to display the value of variables in the Debug Log
window. The code below illustrates using the debugLog command to display the
values of strings and components of a 1D double array.
int len=xcoords.length;
if (selected==0) {
The model object provides a large number of methods, including methods for
setting up and running sequences of operations. Convert to Method, Record
Code, Model Code, and Language Elements produce statements using such
model object methods. For more information on and example code related to the
model object and its methods, see Appendix CLanguage Elements and
Reserved Names in the book Introduction to COMSOL Multiphysics, as well as
the COMSOL Programming Reference Manual.
La ng uage E le me nt Exa m p l es
4 [] unit
5 * / binary: multiplication, division
6 + - binary: addition, subtraction
7 < <= > >= comparisons: less-than, less-than or equal,
greater-than, greater-than or equal
8 == != comparisons: equal, not equal
9 && logical and
10 || logical or
11 , element separator in lists
T HE IF S TATEMENT
if(a<b) {
alert(toString(a));
} else {
alert(toString(b));
}
T HE FOR S TATEMENT
// Iterate i from 1 to N:
int N=10;
for (int i = 1; i <= N; i++) {
// Do something
}
T HE W HILE S TATEMENT
double t=0,h=0.1,tend=10;
while(t<tend) {
//do something with t
t=t+h;
}
T HE W ITH S TATEMENT
// Set the global parameter L to a fixed value
with(model.param());
set("L", "10[cm]");
endwith();
C OMPARING S TRINGS
Comparing string values in Java has to be done with .equals() and not with
the == operator. This is due to the fact that the == operator compares if the strings
are the same objects and does not consider their values. The below code
demonstrates string comparisons:
boolean streq=false;
String a="string A";
String b="string B";
streq=a.equals(b);
// In this case streq==false
b="string A";
streq=a.equals(b);
// In this case streq==true
Remove a series of geometry objects (circles) with tags c1, c2, ..., c10:
for(int n=1;n<=10;n=n+1) {
model.geom("geom1").feature().remove("c"+n);
}
Create a circle with tag c1, build the circle object (run the node), and create a
rectangle with tag r1:
model.geom("geom1").create("c1", "Circle");
model.geom("geom1").run("c1");
model.geom("geom1").create("r1", "Rectangle");
Example
This is a larger block of code that removes, creates, and accesses physics interface
feature nodes:
String[] flowrate = column1;
String[] Mw = column2;
if (flowrate != null) {
for (int i=0; i<flowrate.length; i++) {
if (flowrate[i] != "") {
if (Mw[i] != "") {
int d = 1+i;
model.physics("pfl").create("inl" +d, "Inlet");
model.physics("pfl").feature("inl" +d).setIndex("spec", "3", 0);
model.physics("pfl").feature("inl" +d).set("qsccm0", flowrate[i]);
model.physics("pfl").feature("inl" +d).set("Mn", Mw[i]);
model.physics("pfl").feature("inl" +d).selection().set(new int[]{d});
}
}
}
}
The need to remove and create model tree nodes is fundamental when writing
methods because the state of the model object is changing each time a model tree
node is run. In the method above, the number of physics feature nodes are
dynamically changing depending on user inputs. Each time the simulation is run,
old nodes are removed first and then new nodes are added.
In the application tree, the Libraries node contains images, sounds, and files to be
embedded in an MPHAPP-file so that you do not have to distribute them along
with the application. In addition, the Libraries node may contain Java utility
class nodes and nodes for external Java and C libraries.
I m age s
The Images library contains a number of preloaded sample images in the PNG-file
format. If you wish to embed other image files, click the Add File to Library icon.
A larger selection of images is available in the COMSOL installation folder at the
102 | Libraries
location data/images. Images are referenced in image form objects or in
methods.
To preview an image, click the name of the image and then click the Preview
button below the List of Images. This opens a dialog box displaying the image, as
shown in the figure below.
Sounds
The Sounds library contains a few preloaded sounds in the WAV-file format. If you
wish to embed other sound files, click the Add File to Library icon. A larger
Libraries | 103
selection of sounds is available in the COMSOL installation folder at the location
data/sounds.
To play a sound, click the name of the sound and then click the Preview button
below the List of Sounds.
To play a sound in an application, write a method containing a call to the function
playSound, such as:
playSound("success.wav");
104 | Libraries
Files
The Files library is empty by default. Click the Add File to Library icon to embed
files of any type in your application.
Libraries | 105
Appendix AForm Objects
This appendix provides information about form objects and expands upon the
section The Form Editor on page 25.
L i s t o f A l l For m O b j e c t s
Input
- Input Field*
- Button*
- Check Box
- Combo Box
Labels
- Text Label*
- Unit*
- Equation
- Line
Display
- Data Display*
- Graphics*
- Web Page
- Image
- Progress Bar
- Log
- Message Log
- Results Table
Subforms
- Form
- Form Collection
Che c k Box
A check box has two values: on for selected and off for cleared. The state of a
check box is typically stored in a Boolean variable in the Declarations node.
In this example, the variable controls whether the title and color legend are
included in a plot (on) or not included (off).
If a global parameter from the model serves as the data source, then it is necessary
to add two parameters, on and off, with values 1 and 0, respectively. Otherwise,
you will get an error when the expected parameters on and off are missing.
You associate a check box with a declared variable by selecting it from the tree in
the Source section.
The text label for a check box gets its name, by default, from the Description field
of the Boolean variable that it is associated with. The name in this case is Include
title and color legend.
The Default value of the variable bvar is overwritten by the Value for selected (on)
or the Value for cleared (off) and does not need to be edited. When used in
methods, the values on and off are aliases for true and false, respectively. These
values can be used as Booleans in if statements, for example.
A combo box can serve as either a combination of a drop-down list box and an
editable text field or as a drop-down list box without the capability of editing.
The figure below shows the Settings window for this combo box.
In the Initial value list, choose a method to define a default value for the combo
box. The options are First allowed value (the default) and Custom default. For the
Custom default option, enter a default value in the associated field. The default
value that you enter must exist among the allowed values.
The string variable svar is allowed to have one of these six values: 7, 8, 9, 10, 11,
or 12. The text strings in the Display name column are shown in the combo box.
You can select the Allow other values check box to get a combo box where you
can type arbitrary values. Such combo boxes can accept any value and are not
restricted to the values defined by the choice lists. In this example, however, only
six predefined values are allowed.
The quickest way to learn the syntax for changing a parameter to a plot group is
to use the Record Code function. While recording code, change the value of the
parameter you wish to control and then stop the recording. In this case, the string
svar takes the values "7", "8", "9", "10", "11", or "12".
Each material is indexed with a string: mat1, mat2, ..., mat5. An event listens for
changes to the value of the global variable alloy, where the value is controlled by
a combo box. When the value is changed, the method listed below is run.
with(model.material("matlnk1"));
set("link", alloy);
endwith();
The application utilizes three choice lists: Aluminum Alloys, Steel Alloys, and
Material. An activation condition is used for the Aluminum Alloys and Steel Alloys
choice lists, as shown in the figure below.
Note that the Material combo box uses the material string variable as its source.
The Material choice list is used to define a discrete set of allowed values for the
Clicking Model Data Access in the ribbon gives access to the combo box for
predefined element size, as shown in the figure below.
Select the green check box to the left of the list to make it available as a source to
the combo box.
Changing the Initial value to From data source ensures that the element size
setting of the model, in this case Normal, is used as the default element size in the
application. A virtual choice list is created, Predefined size (hauto), which
corresponds to the list in the model. To use a more limited set of choices, delete
To learn which values are used by the Element size list in the model, use Record
Code and change the value from Normal to Fine and then to Coarse. Stop the
recording and read the values in the auto-generated code. The values for Fine,
Normal, and Coarse are 4, 5, and 6, respectively.
An equation object can display a LaTeX equation by entering the expression in the
Enter equation in LaTeX syntax field.
A preview is shown of the rendered LaTeX syntax after leaving the text field.
Use the line form object to add a horizontal or vertical line to a form, which can
be used, for example, to separate groups of form objects. For the horizontal line
option, you can also add text that appears within the line.
We b Page
A web page object can display the contents of a web page as part of the user
interface. You can specify the page source in three different ways from the Source
list:
Use the default option Page to enter HTML code in a text area below the
list, enclosed by the <html> and </html> start and end tags.
I m age
Use an image form object to add an image to a form. Choose an image file by
typing its name in the Image text field or by clicking the Browse button to select
a file from the local file system. The figure below shows the Settings window for
If you select an image file from your file system, this file will be embedded in the
application and added to the list of Images under the Libraries node.
While you can change the x- and y-position of the image, the width and height
settings are determined by the image file.
You can paste images from the Windows clipboard to a form window by
using Ctrl+V. Such images will be added automatically to the Images
library and embedded in the application. The names for pasted images are
automatically set to: pasted_image_1.png, pasted_image_2.png, etc.
Prog ress B ar
Note that the built-in progress bar that is visible in the status bar of an application
is controlled by the Settings window of the Main Window node. The built-in
progress bar shows the progress of the built-in COMSOL Multiphysics core
algorithms such as geometry operations, meshing, and solving.
L og
The log form object adds a log window that displays messages from the built-in
COMSOL Multiphysics core algorithms such as geometry operations, meshing,
and solving.
Me ssage Log
The message log object adds a window where you can display messages to inform
the user about operations that the application carries out. Implement this feature
using the built-in message method with syntax: message(String message).
See also GUI-Related Methods and Functions on page 188.
The Include standard message log toolbar check box is selected by default. When
selected, the toolbar in the Messages window that you see in the COMSOL
Results Table
The Include standard results table toolbar check box is selected by default. When
selected, the toolbar is included in the application as it would appear in a Table
window in the COMSOL Desktop.
For m
Within a form, you can embed a subform by creating a link to it. You do this by
selecting the form you would like to link to from the Form Reference section of
For m C o l l e c t i o n
There are three different layout options. From the Type list, choose between:
Tabs, which is the default setting, displays the forms using tabbed panes.
In the Panes section, in the Use selected forms as panes list, each form represents
a pane. These will be displayed in the application in the order they appear in the
list.
You can control which tab (or list) is active by linking to a string variable in the
section Active Pane Selector, as shown in the figure below.
When an Active Pane Selector is selected, the Default pane setting will initialize
the chosen string variable, overriding the initial value set in the string variable
declaration. The string variable needs to be equal to one of the form names in the
form collection such as temperature or conversion in the example above.
Otherwise, it will be ignored.
For a form collection with the Type set to Sections, the Active Pane Selector has
no effect. Using an Active Pane Selector is optional and is only needed if you wish
to control which tab is active by some method other than clicking its tab. To
remove a string variable used as an Active Pane Selector, click the Clear source
toolbar button under the tree.
C a rd S t a c k
A card stack is a form object that contains cards. Cards are another type of form
object that are only defined in the context of being used in a card stack. Flip
between cards in a card stack to show one at a time. You associate a card stack with
a data source that controls which card to show. Each card specifies a value that is
compared against the data source of the card stack. The card stack shows the first
card with the matching value. If no cards match, nothing is shown.
The table in the Cards section contains the cards in the Card column and their
associated activating values in the Activating value column. The stack decides
which card to display based on their activating values. In this example, the
Activating values are the strings card1 and card2 (not to be confused with the
identical names of the card objects).
The figure below shows the declaration of the string variable image and its default
value card1.
The figure below shows card1 with its image form object.
The method below flips between the two cards by changing the value of the string
variable image based on the value of a Global Evaluation node gev1. The value of
the string is set to either card1 or card2, as shown in the example below.
double[][] parr = model.result().numerical("gev1").getReal();
double p = parr[0][0];
if (p < 760)
image="card1";
else
image=card2;
File Import
A file import object is used to display a file browser with an associated input field
for browsing to a file or entering its path and name. It is used to enable file import
by the user of an application at run time, when the file is not available in the
application beforehand.
In this application, the File types table specifies that only CSV files are allowed.
Note that the file extension .csv used in the declaration is optional.
In order to make it possible to run the application without having to first provide
experimental data, a file containing default experimental data is embedded in the
application. This default data file is used by the application by accessing it with the
embedded:/// file scheme syntax, as shown in the figure below. In this example,
the application performs a least-squares fit to the experimental data.
Note that the geometry import method importData() is not automatically run
by the method model.geom("geom1").run(). Any method performed by the
application that includes solving would also need to include a call to this geometry
import method (if not, then the previously imported geometry will be used.)
An array input object has an input table used to enter array or vector-valued input
data. An array input object supports string arrays as data sources. You can add an
optional label, symbol, and unit.
A radio button object has a fixed number of options from which you can choose
one. It is most useful when you have just a handful of options.
In a selection input object, you can copy, paste, remove, clear, and zoom in to
selections.
You can choose to use a graphics object as the source of a selection without
having any selection input object.
A text object is a text field with default text that is taken from a string variable. The
Settings window for a text object is shown below.
In the Value field, enter the initial text. By default, the initial text is set to the initial
value of the string variable used as a source.
The check box Editable is cleared by default. If selected, the text object can be
used, for example, to type comments in a running application. If the text is
changed by the user, it is stored in the string variable that is used as the data
source.
The check box Wrap text is selected by default. Clear this check box to disable
wrapping of the text; a scroll bar appears if the text does not fit.
A list box object is similar to a radio button object except that it allows for the
simultaneous selection of multiple options.
As an alternative, the following figure shows that a list can be displayed as a dialog
box.
The Select values in list allows you to choose between two alternatives, List box
or Dialog, for displaying the list.
If you use a string array as the source, you can, in the running application, select
more than one item in the list using Shift-click or Ctrl-click. For other sources, you
In the Choice List section, you can add choice lists that contribute allowed values
to the list box. The figure below shows the choice list used in this example.
The vibrational modes 16 correspond to trivial rigid body modes and are not of
interest in this application, hence the list of values starts at 7. The choice list allows
you to hide the actual mode values in the model from the user by only displaying
the strings in the Display name column; the first non-rigid body modes are named
Mode 1, the second Mode 2, etc.
with(model.result("pg7").feature("surf1").feature("def"));
setIndex("expr", withstru, 0);
setIndex("expr", withstrv, 1);
setIndex("expr", withstrw, 2);
endwith();
model.result("pg7").run();
useGraphics(model.result("pg7"),"/form1/graphics8");
zoomExtents("/form1/graphics8");
Note that you can use the Record Code functionality to learn how to change
between different modes.
Assuming the user selected the modes 1, 3, and 5 by using the list box, the method
creates an expression with(1,u)+with(3,u)+with(5,u). This expression is
then used for the x-displacement (dependent variable u) in a displacement plot. In
a similar way, the method automatically creates expressions for the variables v and
w associated with the y- and z-displacement, respectively. Note that the command
with(), used in results as in the example above, is different from the built-in
with() command used to shorten syntax that is described in With, Get, and Set
on page 194.
A table object represents a table with rows and columns that can be used to define
input or output. The figure below shows an example of a running application with
a table object used to accept input:
The string arrays define the initial values for the rows corresponding to the two
columns as shown in the figure below:
Slider
A slider is a form object for choosing numerical input using a slider control.
In this example, the slider is accompanied by an input field that is used to display
the selected value.
Toolbar
A toolbar object contains the specifications of a toolbar with toolbar buttons. The
figure below shows a toolbar with buttons for Save, Save As, and Exit.
Each row in the Toolbar Items table contains either an item, corresponding to a
toolbar button, or a separator. Use the buttons below the table to add items or
separators, change row order, or to delete a row. Click the Edit button to display
The text in the Text field will be shown as a tooltip when hovering over the toolbar
button. The Icon list and the Keyboard shortcut field represent the same
functionality as for a button object. For more information, see Button on page
32.
Spacer
A spacer object is invisible in the user interface and is only used when working in
grid layout mode. It defines a space of fixed size that you can use to ensure that
neighboring form objects have enough space to show their contents. Typically,
you would use a spacer next to a table or graphics object to ensure that they are
The Application Builder defaults to sketch layout mode, which lets you use fixed
positions and sizes of objects. Use grid layout mode to position and size objects
based on a background grid. This layout mode is more suitable for designing a
resizable user interface.
Switch to grid layout mode by clicking Grid in the Layout group in the ribbon.
The buttons and menus in the Grid group give you easy access to commands for:
Changing the row and column growth rules between Fit, Grow, and Fixed,
which determine the layout when the user interface is resized
Inserting or removing rows and columns
Aligning form objects within grid cells
Merging and splitting cells
Similarly for selecting a column, click the cell at the top. This cell cannot contain
any form objects. The figure below shows the third column highlighted. In this
case, the Column Settings menu is enabled in the ribbon tab.
The Row Settings and the Column Settings have the same three options:
Fit sets the row height or column width to the smallest possible value given
the size of the form objects in that row or column
You can interactively change the row height and column width by dragging the
grid lines.
In this case, the number of pixels will be displayed and the Row Settings or
Column Settings growth policy will be changed automatically to Fixed.
You can select Merge Cells and Split Cells to adjust the cell size and layout to your
form objects. The Align menu gives you options for aligning form objects within
The table below lists the keyboard shortcuts available in the Application Builder.
This appendix contains listings of all built-in functions and methods for use in the
Method Editor, except for methods that operate on the model object. For more
information on the model object and its methods, see the COMSOL
Programming Reference Manual.
The syntax rules are those of the Java programming language. Note that each
valid programming sentence needs to end with a semi-colon (;), but the
semi-colon is omitted in the listings below.
Example Code
The code below reads user provided experimental data in a .csv file. A file import
object is used to allow the user of an application to upload the file. The file is then
input to the physics interface for least-squares fitting. If the file doesnt exist, the
user is asked to confirm that default data will be used.
Example Code
The line of code below plays one of the sounds available in the data/sounds
folder of the COMSOL installation and that has been embedded in the application
and stored in the Sounds library.
playSound("embedded:///success_1.wav");
As an alternative, a method with an input argument can be written and called from
a command sequence of a menu item or button, as shown in the example below.
The figure below shows a method b_open_pdf that opens a file with filename
as input argument.
Example Code
This line of code displays the visualization of plot group 5 (pg5) in the graphics
object graphics1 in the form with the name Temperature.
useGraphics(model.result("pg5"), "/Temperature/graphics1");
The code below displays the mesh in the model tree node mesh1 in the graphics
object graphics1 contained in the card of a card stack. The second line runs a
zoom extents command to ensure proper visualization of the mesh.
useGraphics(model.mesh("mesh1"), "/mesh/cardstack1/card1/graphics1");
zoomExtents("/mesh/cardstack1/card1/graphics1");
The code below displays a request dialog box that lets the user type in a file name
used for an HTML report. If the user has typed a file name, then a report is
generated.
String answerh = request("Enter file name","File Name", "Untitled.html");
if(answerh != null){
model.result().report("rpt1").set("format","html");
model.result().report("rpt1").set("filename","appuser:///"+answerh);
model.result().report("rpt1").run();
}
The code below is similar to the code above, but in this case the report is saved in
Microsoft Word format (.docx).
String answerw = request("Enter file name","File Name", "Untitled.docx");
if(answerw != null){
model.result().report("rpt2").set("format","docx");
model.result().report("rpt2").set("filename","appuser:///"+answerw);
model.result().report("rpt2").run();
}
Example Code
The code below adds the string Aluminum 3004 to the choice list from the
example in the section Using a Combo Box to Change Material on page 115.
Note that the choice list index starts at 0 whereas the material tags start at 1 (mat1,
mat2, mat3, and mat4).
ChoiceList choiceList = getChoiceList("choicelist1");
choiceList.setListRow("mat4", "Aluminum 3004", 3);
Example Code
The line of code below saves a document to the user folder (as specified in the
Preferences).
fileSaveAs("user:///mixer.docx");
Example Code
The code below sets the global parameter L to a fixed value.
with(model.param());
set("L", "10[cm]");
endwith();
The code below sets the title and color legend of a plot group pg2.
with(model.result("pg2"));
set("titletype", "auto");
endwith();
with(model.result("pg2").feature("surf1"));
set("colorlegend", "on");
endwith();
model.result("pg2").run();
The code below changes the visualization of a plot group pg2 by setting the
property looplevel that controls the solution parameter, to the string variable
svar, as defined under the Declarations node.
with(model.result("pg1"));
set("looplevel", new String[]{svar});
endwith();
model.result("pg1").run();
The code below sets the material link index to the string variable alloy, defined
under the Declarations node.
with(model.material("matlnk1"));
set("link", alloy);
endwith();
The code below sets the coordinates of a cut point data set cpt1 to the values of
the 1D array samplecoords[].
with(model.result().dataset("cpt1"));
set("pointx", samplecoords[0]);
set("pointy", samplecoords[1]);
set("pointz", samplecoords[2]);
endwith();
Debug Methods
Example Code
The code below prints strings and doubles to the Debug Log window.
xcoords[i] = Math.cos(2.0*Math.PI*divid);
ycoords[i] = Math.sin(2.0*Math.PI*divid);
debugLog("These are component values for case 1:");
debugLog("x:");
debugLog(xcoords[i]);
debugLog("y:");
debugLog(ycoords[i]);
Example Code
This example will open a dialog containing a progress bar that is updated after one
second to 30% and a little later to 80%. Then finally the dialog is closed:
try {
startProgress();
Thread.sleep(1000);
setProgress(30);
Using the technique shown below, it is possible to show a custom message in the
Progress dialog box:
try {
startProgress(true, "Doing heavy calculations");
Thread.sleep(5000);
closeProgress();
} catch ( InterruptedException e) {
// this is required because of the Thread.sleep used in the example to
wait a little
// between updates to Progress Dialog
}
General
Ask for relevant input data.
Produce useful output. Include reports to files with input data and
corresponding output data.
Make it intuitive. Provide help, hints, and documentation as necessary.
Make it foolproof: Safe I/O, Reset to default data,
Save a thumbnail image with the model.
Include a description text (it will be visible in the COMSOL Server library).
Test the application on the computer platforms it is intended for.
Be minimalistic. From the developers point of view it makes it much easier
to make sure logic works, to organize, to debug, to maintain, and to develop
further. From a users point of view it makes it easier to use the application.
The minimalistic approach requires more care while developing but much
less maintenance later on and much higher adoption among users.
Embed libraries in the model if they are of manageable size.
Password protect as needed. (Remember: No one can help you if you forget
the password.)
Methods
Dont create more methods than necessary.
Fewer methods gives you a shorter list of methods to browse through when
looking for something. Fewer methods usually means fewer lines of code to
worry about.
- If several methods you wrote do essentially the same thing, consider merging
them into one method and deal with the different cases by input arguments.
- Dont create a method if it is only called from one place. Insert the code right
into that place instead.
Create a local method if it is only used in a form, triggered by a form event
or a form object event.
Give methods descriptive names, and name them so that similar methods are
grouped together when sorted alphabetically. You will need to remember
Forms
Dont create more forms than necessary.
Dont create a subform unless it is used in more than one form. If it is used
in only one form, include the pieces in that form instead.
Give forms descriptive names. Same reasoning as for methods.
Make good use of the many different types of form objects. Some are good
for some things, some are good for others.
Dont insert more form objects than necessary. Too many options for input
data may make the application hard to use. Too much output data makes it
hard to find important information.
Insert a text field for the user to leave comments to save with the users set
of input and output data when saving the application.
Consider inserting a button with a method to reset to default data.
Apply Safe I/O:
- For input fields, alert the user about input data that are out of bounds. You
can do that either by an alert triggered by an On Data Change event set on
an input field, or by setting limits in the form objects settings window (which
Tubular Reactor
This application is designed for students to investigate how the activation energy,
heat of reaction, and thermal conductivity in a non-ideal tubular reactor influence
the axial and radial conversion and temperature profiles in the reactor.
The model embedded in the application is defined using the Chemical Species
Transport interface included in COMSOL Multiphysics and does not require any
add-on products.
The model definition is included in an exercise from Scott Foglers text book
Elements of Chemical Reaction Engineering, which is used in most western
universities in undergraduate and graduate courses in the subject of chemical
reaction engineering. It describes a non-ideal tubular reactor for the exothermic
reaction of propylene oxide with water to form propylene glycol. The reactor has
a fully developed laminar flow profile and it is equipped with a cooling jacket
around the outer walls of the reactor. These effects are clearly visualized in the
output of the application.
array 2D 66 methods 13
| 211
description text, for derived value 46 main 38
displayed text 29 form collection 50, 135
double variable 64, 65 Form Editor
double-click, MPHAPP-file 14 desktop location 9
drag and drop, form objects 28, 171 overview 10
preferences 27
E embedded, file scheme 70, 102, 143
using 25
equation 126
form event 57
error message 64
form object 10, 31, 59, 106
errors and warnings window 86
event 57
event 13, 31, 55, 57, 92
with associated methods 80
button click 33
form reference 50
form 57
form tab, in ribbon 10
form object 57
form window 10
global 55
Forms node 25
keyboard shortcut 32
On close 58 G geometry 23
On data change 57 geometry import 147
On load 58 geometry operations 130, 132
On shutdown 55 global evaluation 47
On startup 55 global event 55
Event node 56 go to method 79
exit button 164 graphics object 21, 23, 38
explorer window 10, 12 initial 38
export node 73 graphics tab 23
grid layout mode 27, 168
F file declaration 69
grow, row and column setting 168
file import 69, 140
file reference syntax 102 H HTML
file scheme code 127
common 75 report 76, 191
embedded 70, 102, 143
I icon 39, 49, 102, 166
temp 72, 75
if statement 99
upload 69, 144, 146
image 102, 128
user 75
images library 102
files library 105
initial size, of main window 50
fit, row and column setting 168
initial values, of array 65
fixed, row and column setting 168
input argument, to method 93
for statement 99
input field 62
form 25, 133
adding 41
212 |
text object 46 Method Editor 174
inputs/outputs desktop location 9
forms 20 overview 12
tab 21 preferences 90
integer 65 using 77
integer variable 64 method tab, in ribbon 12
item method window 12
menu 92 Microsoft Word format 71, 74
item, menu 51 model code window 12, 82
item, toolbar 165 model data access 43, 57
model expressions window 12, 88
J Java programming language 77, 97,
Model Library 20
174
model object 97, 174
K keyboard shortcut 83, 91, 172
move down 35
keyboard shortcut event 32, 52, 166
move up 35
L language elements window 12, 86, 97 MPHAPP-file
LaTeX 46, 48, 126 format 14, 24
layout mode 27, 168 running 14
layout options, form collection 135 MPH-file format 19
Libraries node 102, 129 multiline text 47
line 127
N name, of form object 30
list box 157
new form 11
local method 32, 55, 57, 58, 80, 92, 93
new method 13
logo image 39
number format 48
M main form 38 number of digits 48
main window 50, 130
O off 108
Main Window node 49
on 108
material 115
On close event 58
math functions 99
On data change event 57
menu 51, 54
On load event 58
menu bar 49, 50
On shutdown event 55
menu item 38, 92
On startup event 55
merging cells 168
operators 97, 98
mesh 23
output argument, to method 93
meshing 130, 132
P panes 136
method 12, 30, 38, 59, 77, 174
parameter, input fields and 41
event 56, 57
parameter, text objects and 46
form object 80
parentheses 90
local 32, 55, 58, 80, 92
| 213
password protected application 17 sketch layout mode 27, 168
pixels 29 slider 163
playSound 104 solving 130, 132
PNG-file format 102 sounds library 103
position and size 29 spacer 166
positioning form objects 28 splitting cells 168
precedence, of operators 98 status bar 130
precision 48 string variable 64
preferences 27, 71, 90 syntax errors 86
progress bar 129 syntax highlighting 90
built-in 130
T table 64, 161
R radio button 151 temp, file scheme 72, 75
recording code 80 temporary files 71
regular expression 43 test application 14
report, creating 74 test form 14
request 100 text object 41, 46, 47, 156
resizing form objects 29 title 108
results plot 23 toolbar 51, 164
ribbon 49, 54 item 165
ribbon section 54 separator 165
ribbon tab 54 tooltip
row settings 169 for button 32
run application 14 for toolbar button 166
tubular reactor, Application Library ex-
S save 164
ample 209
application 24
tuning fork, Application Library exam-
model as application 19
ple 210
running application 15
save as 53, 164 U Unicode 46, 48
scalar variable 59 unit object 41
selection input 153 Untitled.mphapp 15
separator upload, file scheme 69, 144, 146
menu 51 URL 128
ribbon 54 use as source 48
toolbar 165 user interface layout 10
settings window user, file scheme 75
button 30
V variable, input fields and 41
form editor 10
variable, text objects and 46
method editor 12
volume maximum 47
214 |
W WAV-file format 103
web browser 7
web implementation of an application 7
web page 127
while statement 99
with statement 90, 99
wrap text 47
| 215
216 |