Beruflich Dokumente
Kultur Dokumente
for Matlab
Users Guide
VERSION 4.2
TM
Benelux
India
United Kingdom
COMSOL BV
Rntgenlaan 37
2719 DX Zoetermeer
The Netherlands
+31 (0) 79 363 4230
+31 (0) 79 361 4212
info@comsol.nl
www.comsol.nl
COMSOL Ltd.
UH Innovation Centre
College Lane
Hatfield
Hertfordshire AL10 9AB
+44-(0)-1707 636020
+44-(0)-1707 284746
info.uk@comsol.com
www.uk.comsol.com
Denmark
COMSOL A/S
Diplomvej 381
2800 Kgs. Lyngby
+45 88 70 82 00
+45 88 70 80 90
info@comsol.dk
www.comsol.dk
Finland
COMSOL OY
Arabiankatu 12
FIN-00560 Helsinki
+358 9 2510 400
+358 9 2510 4010
info@comsol.fi
www.comsol.fi
France
COMSOL France
WTC, 5 pl. Robert Schuman
F-38000 Grenoble
+33 (0)4 76 46 49 01
+33 (0)4 76 46 07 42
info@comsol.fr
www.comsol.fr
Germany
COMSOL Multiphysics GmbH
Berliner Str. 4
D-37073 Gttingen
+49-551-99721-0
+49-551-99721-29
info@comsol.de
www.comsol.de
United States
Italy
COMSOL S.r.l.
Via Vittorio Emanuele II, 22
25122 Brescia
+39-030-3793800
+39-030-3793899
info.it@comsol.com
www.comsol.it
Norway
COMSOL AS
Postboks 5673 Sluppen
Sndre gate 7
NO-7485 Trondheim
+47 73 84 24 00
+47 73 84 24 01
info@comsol.no
www.comsol.no
Sweden
COMSOL AB
Tegnrgatan 23
SE-111 40 Stockholm
+46 8 412 95 00
+46 8 412 95 10
info@comsol.se
www.comsol.se
Switzerland
COMSOL Multiphysics GmbH
Technoparkstrasse 1
CH-8005 Zrich
+41 (0)44 445 2140
+41 (0)44 445 2141
info@ch.comsol.com
www.ch.comsol.com
COMSOL, Inc.
1 New England Executive Park
Suite 350
Burlington, MA 01803
+1-781-273-3322
+1-781-273-6603
COMSOL, Inc.
10850 Wilshire Boulevard
Suite 800
Los Angeles, CA 90024
+1-310-441-4800
+1-310-441-0868
COMSOL, Inc.
744 Cowper Street
Palo Alto, CA 94301
+1-650-324-9935
+1-650-324-9936
info@comsol.com
www.comsol.com
For a complete list of
international representatives,
visit
www.comsol.com/contact
Home Page
www.comsol.com
www.comsol.com/
community/forums
May 2011
COMSOL 4.2
C o n t e n t s
Contents 2
Chapter 1: Introduction
About Using this Guide
11
Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . 11
The Client/Server Connection . . . . . . . . . . . . . . . . . . 12
Basics on Working with a Model Object . . . . . . . . . . . . . . 13
Loading and Saving a Model . . . . . . . . . . . . . . . . . . . 14
Importing and Exporting a Model . . . . . . . . . . . . . . . . . 15
COMSOL 3.5a Model Conversion. . . . . . . . . . . . . . . . . 17
Calling External MATLAB Functions in the COMSOL Desktop . . . . . . 19
User-Defined GUIs . . . . . . . . . . . . . . . . . . . . . . 19
Startup of COMSOL with MATLAB . . . . . . . . . . . . . . . . 20
Running COMSOL with MATLAB in Batch Mode . . . . . . . . . . . 20
Getting More Information . . . . . . . . . . . . . . . . . . . . 20
23
35
41
57
. . . . . . . . . . . . . . . . . . . . 58
. . . . . . . . . . . . . . . . . . . . 60
63
87
3 |
CHAPTER :
103
119
139
140
5 |
CHAPTER :
Introduction
This guide introduces you to LiveLink for MATLAB, which extends your
COMSOL modeling environment with an interface between COMSOL
Multiphysics and MATLAB. The COMSOL Java API Reference Guide provides
additional documentation of the API.
In this chapter:
About Using this Guide
Getting Started
Note: If you are working directly from a PDF on your computer, the blue links do
not work to open a model or documentation referenced in a different user guide.
However, if you are using the online help desk in COMSOL Multiphysics, these links
work to other modules, model examples, and documentation sets.
THE DOCUMENTATION
) or Help>Dynamic Help (
and then either enter a search term or look under a specific module in the
documentation tree.
THE MODEL LIBRARY
7 |
CHAPTER 1: INTRODUCTION
open for further investigation. Use both the step-by-step instructions and the actual
models as a template for your own modeling and applications. SI units are used to
describe the relevant properties, parameters, and dimensions in most examples, but
other unit systems are available.
To open the Model Library, select View>Model Library (
) from the main menu, and
then search by model name or browse under a Module folder name. If you also want
to review the documentation explaining how to build a model, select the model and
) to reach the PDF or HTML version,
click Model PDF or the Dynamic Help button (
respectively. Alternatively, select Help>Documentation in COMSOL and search by name
or browse by Module.
If you have feedback or suggestions for additional models for the library (including
those developed by you), feel free to contact us at info@comsol.com.
COMSOL WEB SITES
Typographical Conventions
All COMSOL user guides use a set of consistent typographical conventions that should
make it easy for you to follow the discussion, realize what you can expect to see on the
screen, and know which data you must enter into various data-entry fields.
In particular, you should be aware of these conventions:
Click text highlighted in blue to go to other information in the PDF. When you are
using the online help desk in COMSOL Multiphysics, these links also work to other
Modules, model examples, and documentation sets.
A boldface font of the shown size and style indicates that the given word(s) appear
exactly that way on the COMSOL Desktop (or, for toolbar buttons, in the
) is often
corresponding tooltip). For example, the Model Builder window (
referred to and this is the window that contains the model tree. As another example,
), and this boldface
the instructions might say to click the Zoom Extents button (
font means that you can expect to see a button with that label (when you hover over
the button with your mouse) on the COMSOL Desktop.
The names of other items on the COMSOL Desktop that do not have direct labels
contain a leading uppercase letter. For instance, we often refer to the Main toolbar
the horizontal bar containing several icons that are displayed on top of the user
interface. However, nowhere on the COMSOL Desktop, nor the toolbar itself,
includes the word Main.
The forward arrow symbol > indicates selecting a series of menu items in a specific
order. For example, Options>Results is equivalent to: From the Options menu, select
Results.
A Code (monospace) font indicates you are to make a keyboard entry in the user
interface. You might see an instruction such as Enter (or type) 1.25 in the Current
density edit field. The monospace font also is an indication of programming code.
or a variable name. An italic Code (monospace) font indicates user inputs and parts
of names that can vary or be defined by the user.
An italic font indicates the introduction of important terminology. Expect to find
an explanation in the same paragraph or in the Glossary. The names of other user
guides in the COMSOL documentation set also have an italic font.
9 |
CHAPTER 1: INTRODUCTION
Button: Click a button to perform an action. Usually located on a toolbar (the Main
toolbar or the Graphics window toolbar, for example), or in the upper right corner
of a Settings window.
Icon: An icon is an image that displays on a window (for example, the Model Wizard
or Model Library) or displays in a Context Menu when a node is right-clicked.
Sometimes selecting an icon from a nodes Context Menu adds a node with the
same image and name, sometimes it simply performs the action indicated (for
example, Delete, Enable, or Disable).
10
Getting Started
In this section:
Quick Start
The Client/Server Connection
Basics on Working with a Model Object
Loading and Saving a Model
Importing and Exporting a Model
COMSOL 3.5a Model Conversion
Calling External MATLAB Functions in the COMSOL Desktop
User-Defined GUIs
Startup of COMSOL with MATLAB
Running COMSOL with MATLAB in Batch Mode
Getting More Information
Quick Start
The easiest way to get started with LiveLink for MATLAB is to make a model in
COMSOL Multiphysics, save it as a Model M-file, and load it in MATLAB.
1 From the File menu, select Open Model Library.
2 Navigate to COMSOL Multiphysics>Equation-based Models and double-click
shell_diffusion to open it.
3 From the File menu, select Save As Model M-file and save it as shell_diffusion in
11 |
CHAPTER 1: INTRODUCTION
For example, change the parameter definitions in the model object. They are available
under model.param (see lines 2528 in the M-file) in the model object. Then run the
file again.
stored.
2 Connect MATLAB to the COMSOL server. Enter the command:
mphstart(portnumber)
GETTING STARTED
12
Where portnumber is the number of the port to use the COMSOL server. If the
COMSOL server is listening on the default port number (2036) you dont need to
specify the port number in mphstart.
3 Import the COMSOL class and start implementing a model:
import com.comsol.model.*
import com.comsol.model.util.*
model = ModelUtil.create('Model');
D I S C O N N E C T M AT L A B F RO M T H E C O M S O L S E R VE R
Once MATLAB is connected to the COMSOL server, disconnect from the server by
entering:
ModelUtil.disconnect;
The above command create a model object in the COMSOL server and a MATLAB
link that can access the function of the COMSOL model object. The COMSOL model
object is defined as Model while the MATLAB link is defined by model.
In addition to creating models, you can list the model object available in the COMSOL
server:
list = ModelUtil.tags;
You can also set a path in the COMSOL server. This is very useful if you need to use
external file in the COMSOL model (for instance geometry, mesh or data file):
13 |
CHAPTER 1: INTRODUCTION
ModelUtil.path(<path>);
By default the progress bar is not displayed during the mesh and solve operation. It is
possible to activate the progress bar with the command:
ModelUtil.showProgress(true);
This create a model object Model in the COMSOL server that is accessible using the
MATLAB object model.
When using the function mphload, the model history is automatically disabled, this is
to prevent large amount of history recording when running the model in loop. If you
want to keep the model history you can use the function mphload, as following:
model = mphload('busbar.mph','-history');
A file on the MPH format can be loaded by the COMSOL Desktop. In addition you
can save your model as a Model M-file by entering
model.save('shell_diffusion2','m');
GETTING STARTED
14
When saving the model as a M-file, the file contains the syntax of the entire sequence
history. If you want only to get the sequence corresponding to the set up of the model
object, you need to reset it first. You can use the reset method as:
model.reset;
Note: The models are not automatically saved between MATLAB sessions.
In the COMSOL Desktop you can use the option Export to Server from the File menu
in order to send the model object to the COMSOL server that is connected with
MATLAB. Once you have the model object in the COMSOL server you need to create
a link in the MATLAB prompt.
1 From the File menu, select Open Model Library.
2 Navigate to COMSOL Multiphysics>Equation-based Models and double-click
shell_diffusion to open it.
3 From the File menu, select Client server > Export Model to Server.
4 The Server and the Port to use have to be specified (default values are localhost
and 2036). In order to connect to the server you need to enter the Username and a
Password; these are defined the first time you connect to the COMSOL server.
15 |
CHAPTER 1: INTRODUCTION
Finally you can define the name of the model object to export (default name is
Model).
5 Click OK.
6 In MATLAB, create a link to the model object in the COMSOL server by entering
the command:
model = ModelUtil.model('Model');
Note: If the model object is exported to the COMSOL server with a different name,
replace Model with the name of the model exported to the COMSOL server. It is
possible to obtain the list of the model object available in the COMSOL server with
the command: ModelName = ModelUtil.tags
I M P O R T I N G A M O D E L I N T H E C O M S O L D E S K T O P F RO M M AT L A B
To import a model defined in a COMSOL server to the COMSOL Desktop, use the
Import Model from Server from the File menu. This window is similar to the Client
server>Export Model to Server window.
GETTING STARTED
16
Note: You can have several model objects on a server, which is why the name of the
model to import is mandatory for the import procedure.
To support the conversion from COMSOL 3.5a there is a separate launcher available,
which lets you run models represented in 3.5a syntax along with version 4 models
using the LiveLink interface. To start MATLAB in compatibility mode, use the
following:
Windows: Select COMSOL with MATLAB (COMSOL 3.5a Compatibility) under COMSOL 4.2
from the Windows Start menu.
Linux and Mac OS X: Start COMSOL with MATLAB with the command
comsol matlab -compat -c35aroot <COMSOL 3.5a root directory>
After starting MATLAB in this way, you have access to all documented functionality in
COMSOL 3.5a from MATLAB as well as the functionality in the LiveLink interface.
If you are using a recent version of MATLAB, make sure that all necessary updates of
COMSOL 3.5a are applied. Go to the COMSOL web site http://www.comsol.com/
support/updates to check for updates.
You find more information regarding the conversion process in the section M-File
Conversion.
CONVERTING MODELS
There are two ways you can migrate your models. This can be done with the command
mphv4 when running COMSOL with MATLAB (3.5a compatibility).
The mphv4 command converts the COMSOL 3.5a FEM structure to a COMSOL 4.2
model object. External operations done with the FEM structure are not converted.
17 |
CHAPTER 1: INTRODUCTION
Modify the 3.5a M-file to create a @femgui object instead of a FEM structure. Run
the M-file. Use the mphv4 utility to convert the model. This restores all fields from
the FEM structure as well as meshing, solving, and postprocessing settings.
fem=femgui;
% Run rest of old model
fem=...
% Convert model
model=mphv4(fem);
After converting your model to a model object, save it both as an MPH file and as an
M-file.
CORRESPONDING WRAPPER FUNCTIONS IN 3.5A
Some wrapper functions are available to work directly with the COMSOL 4.2 model
object. The table below shows the correspondence between equivalent 3.5a and 4.2
functions:
TABLE 1-1: CORRESPONDING WRAPPER FUNCTIONS IN 3.5A AND 4.2
COMSOL 3.5A
COMSOL 4.2
posteval
mpheval
geomplot
mphgeom
postglobal
mphglobal
postint
mphint
postinterp
mphinterp
assemble
mphmatrix
meshplot
mphmesh
femstate
mphstate
GETTING STARTED
18
User-Defined GUIs
You can use the MATLAB GUIDE functionality to generate a user-defined GUI
combined with a COMSOL model, such as in the following figure:
A MATLAB M-file can be used to set up the GUI components and update the model
object. See the GUIDE help in MATLAB for more information.
19 |
CHAPTER 1: INTRODUCTION
A few files are used to set things up properly. In the directory <COMSOLINSTALLDIR>/
mli/startup you can find two files.
java.opts is used to control the amount of memory that is reserved for Java inside
of MATLAB. This amount has to be increased from its default values in order to
accommodate large models and large amounts of that sometimes is transferred
between MATLAB and COMSOL. You can increase the number even further if you
often run out of memory (Java heap space). Notice that increasing the values too
much leaves less memory to perform calculations in MATLAB.
startup.m is a file that is run by MATLAB once every time it starts. By default, this
file does only writes some welcome text on the screen, or add your own commands
at the end. However, the preferred way to add commands to the startup procedure
is to create a file called comsolstartup.m in your home directory or in a directory
on the MATLAB path.
GETTING STARTED
20
The COMSOL Java API Reference Guide contains reference documentation that
describes the methods in the Model object.
The section Command Reference describes additional utilities available for use with
LiveLink for MATLAB.
21 |
CHAPTER 1: INTRODUCTION
Building Models
This chapter gives an overview of the model object and provides an introduction
to building models using the LiveLink interface.
In this chapter:
The Model Object
Running the Model in a Loop
22
23 |
adding data to the model object, performing computations, or returning data. The
following list outlines the use of the model objects top-level methods:
TABLE 2-1: TOP-LEVEL METHODS IN THE MODEL OBJECT
FUNCTION
PURPOSE
model.batch
model.coeff
model.constr
Manipulate constraints
model.coordSystem
model.cpl
model.elem
Manipulate elements
model.field
Manipulate fields
model.frame
Manipulate frames
model.func
Manipulate functions
model.geom
Manipulate geometry
model.intRule
model.init
model.material
Manipulate materials
model.mesh
Manipulate meshes
model.modelNode
model.ode
model.opt
Manipulate optimization
model.pair
Manipulate pairs
model.param
model.physics
model.probe
Manipulate probes
model.result
model.selection
model.shape
model.sol
Manipulate solutions
model.study
Manipulate studies
model.unitSystem
Manipulate units
model.variable
Manipulate variables
model.weak
24
You find detailed documentation of model object methods in the COMSOL Java API
Reference Guide.
To display information about the root node of the model, return a reference to the
model, for example, by entering a variable name without ending the command with a
semicolon:
>> model
COMSOL Model Object
Name: Untitled.mph
Tag: Model
Identifier: root
The name of the root node is the file name associated with the model. The tag of the
root node is the same name when the model object is created. The node identifier is
used to refer to the root scope in multiphysics expressions. Determine the geometries
of your model by entering:
>> model.geom
Type: List
Child tags: geom1
The printout lists the tags of the geometry nodes. The single geometry node is the
geometry that was just created. To display more information about the geometry,
enter:
>> model.geom('geom1')
25 |
Type: Geometry
Tag: geom1
Dimension: 2
Current child: sq1
Child nodes: sq1, fin
The geometry node is of type Geometry. You specified its tag when you create the
geometry. It does not have an identifier because you cannot use the node in
expressions. The printout also contains the dimension of the geometry, the geometrys
current node, and the child nodes. You can also obtain its child nodes by entering:
>> model.geom('geom1').feature
Type: List
Child tags: sq1, fin
The printout lists the tags of the feature nodes in the geometry sequence. Its child
nodes are the square that we just created and the default finalize node. List information
about the square by entering:
>> model.geom('geom1').feature('sq1')
Type: Square
Tag: sq1
Identifier: sq1
Operation: Square
Status: built
The Square feature is built. You can also determine the tag of the node and its
identifier.
Note that you can also define the tag as a JAVA string object:
tags=model.geom('geom1').feature.tags;
model.geom('geom1').feature(tags(1));
26
Enter the following commands to create a 2D geometry node with a square node.
% Create the geometry
model.geom.create('geom1', 2);
model.geom('geom1').feature.create('sq1', 'Square');
model.geom('geom1').run;
You can also display the mesh in a MATLAB figure with the mphmesh command.
mphmesh(model,'mesh1')
Now set up the physics. First manually set the relative permittivity r in the default
Charge conservation node (defined with the tag ccn1). Then ground the lower
boundary and add a charge distribution on the right boundary. You can use a
temporary variable es to make the lines shorter.
% Setup physics
model.physics.create('es', 'Electrostatics', 'geom1');
model.physics('es').feature('ccn1').set('epsilonr_mat', 1,
'userdef');
model.physics('es').feature.create('gnd1', 'Ground', 1);
model.physics('es').feature('gnd1').selection.set([2]);
model.physics('es').feature.create('sfcd1',
'SurfaceChargeDensity', 1);
model.physics('es').feature('sfcd1').selection.set([4]);
model.physics('es').feature('sfcd1').set('rhoqs', 1, '1e-10');
27 |
The study helps you set up solver defaults. Just run the study to set up the defaults and
solve the model.
% Create the study
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.study('std1').run;
28
If the feature already exists in the model object you can also assign a shortcut variable
name:
std1 = model.study('std1');
std1.feature.create('stat1', 'Stationary');
In this user guide the reduced syntax is used. When saving a model as an M-file the full
syntax is always provided.
Utility Functions
In addition to the methods in the model object, LiveLink for MATLAB includes the
following M-file utility functions.
TABLE 2-2: M-FILE UTILITY FUNCTIONS
NAME
PURPOSE
mphdoc
mpheval
mphgeom
mphgetadj
mphgetcoords
mphgetp
mphgetu
mphglobal
mphint
mphinterp
mphload
mphmatrix
mphmesh
mphselectbox
mphselectcoords
mphplot
mphstart
mphstate
mphv4
You find more information about these functions in the Command Reference.
29 |
model;
model.geom;
model.geom('geom1');
model.geom('geom1').feature;
model.geom('geom1').feature('sq1');
and
mphdoc
mphdoc
mphdoc
mphdoc
model.physics;
model.physics('es');
model.physics('es').feature;
model.physics('es').feature('glm1');
You can also access subfeature documentation with the following syntax
mphdoc model Rectangle
mphdoc model Sphere
mphdoc model FreeTri
All these commands provide useful information about the different parts of the model
object in the MATLAB help browser.
To get help with the M-file utility functions in the product, use the MATLAB help
command, for example,
help mphplot
30
Note: To call a MATLAB function from within the model object you do not need to
start COMSOL with MATLAB, starting the COMSOL Desktop is sufficient. The
MATLAB process starts automatically to evaluate the function.
D E F I N E A N EX T E R N A L M AT L A B F U N C T I O N I N T H E C O M S O L M O D E L
To evaluate a MATLAB M-function from within the COMSOL model you need to
add a MATLAB node in the model object where you define the function name, the list
of the arguments and, if required, the function derivatives.
The Settings window of the MATLAB node consists of a table where the function
name and the list of the arguments are entered.
If necessary you can expand the Derivatives section to define the derivatives of the
function with respect to the function arguments.
For example, to define assume that you want to use MATLABs Bessel function of the
third kind (Hankel function) in COMSOL Multiphysics define the following settings:
FUNCTION NAME
ARGUMENTS
EXPRESSION
DERIVATIVES
besselh
nu,x
besselh(nu,x)
0,(besselh(nu-1,x)
-besselh(nu+1,x))/2
bessel
besselh(1,x)
(besselh(0,x)
-besselh(2,x))/2
1 Under the Functions section, enter besselh in the Function column and nu, x in
column,
4 Define the partial derivative value: enter 0 in the Partial derivative column.
5 Proceed the same way with second partial derivative. Enter besselh in the Function
31 |
With this definition, COMSOL can evaluate the functions. When the function value is
requested, a MATLAB process automatically starts and evaluates the function, the
values are then returned to the COMSOL model.
Note that the function path needs to be known by MATLAB. In you are calling a user
defined M-function, you can either set the path in MATLAB before running the
COMSOL model, or save the M-functions at the same location where the COMSOL
model mph-file is saved. An alternative is to define the system environment variable
COMSOL_MATLAB_PATH with the path of the user defined function.
USING THE COMMAND LINE
When running COMSOL with MATLAB, you can directly define a parameter with an
M-function by declaring the parameters with the function. Do NOT include it within
quotes '', for example, assume that the parameter E0 is defined with the M-function
my_fun.m, and then define it with the command line:
model.param.set('E0',my_fun(a,b));
32
If you want to call the M-function with variables defined from within the COMSOL
model object, then add a MATLAB node in the model, for example:
model.func.create('extm1', 'MATLAB');
model.func('extm1').setIndex('funcs', 'my_fun', 0, 0);
model.func('extm1').setIndex('funcs', 'x, y', 0, 1);
model.param.set('E0', 'my_fun(x,y)');
With these commands, the parameter E0 is defined with the function my_fun using
COMSOL variables x and y as arguments.
FUNCTION INPUT/OUTPUT CONSIDERATIONS
The functions called from COMSOL must support vector arguments of any length.
COMSOL calls your MATLAB function using vector arguments because the number
of expensive calls from COMSOL to MATLAB can be reduced this way. All common
MATLAB functions such as sin, abs, and other mathematical functions support
vector arguments.
When you write your own functions for specifying inhomogeneous materials, logical
expressions, time-dependent sources, or other model properties, remember that the
input arguments are vectors. The output must have the same size as the input. All
arguments and results must be double precision vectors. Values can be real or complex.
Consider the following example function where the coefficient c depends on the x
coordinate:
function c = func1(x)
if x > 0.6
c = x/1.6;
else
c = x^2+0.3;
end
This function looks good at first but it does not work in COMSOL Multiphysics
because the input x is a matrix.
You must use element-by-element multiplication, division, and power, that is, the
operators .*, ./, and .^. Replace expressions such as x/1.6 and x^2+0.3 with x./
1.6 and x.^2+0.3, respectively.
The comparison x 0.6 returns a matrix with ones (true) for the entries where the
expression holds true and zeros (false) where it is false. The function evaluates the
conditional statement if and only if all the entries are true (1).
33 |
You can replace the if statement with a single assignment to the indices retrieved from
the x 0.6 operation and another assignment to the indices where x 0,6 . All in all,
the function could look like this:
function c = func2(x)
c = (x./1.6).*(x>0.6) + (x.^2+0.3).*(x<=0.6);
34
Define the parameter to update in the Parametric feature and set the value to solve for:
model.sol(<solname>).feature(<fname>).feature('p1').set('pname',
<pname>);
model.sol(<solname>).feature(<fname>).feature('p1').set('plist',
<plist>);
Define the parameter to update in the Parametric feature and set the value to solve for:
model.batch('p1').set('pname', {<pname>});
model.batch('p1').set('plist', <plist>);
Link the batch node to the study and set the solution to store:
model.batch('p1').study('std1');
35 |
model.batch('p1').feature.create('so1', 'Solutionseq');
model.batch('p1').feature('so1').set('seq', <solname>);
model.batch('p1').feature('so1').set('store', 'on');
Create a second solution which includes the solution for each batch parameter value:
model.sol.create('sol2');
model.sol('sol2').study(<stdname>);
model.batch('p1').feature('so1').set('psol', 'sol2');
This example illustrates how to set up a continuation feature to an existing solver study
step and compute for solution for several parameter values.
% Load the busbar model from the Model library:
model = mphload('busbar');
% Create a link to the stationary study step 's1':
s1 = model.sol('sol1').feature('s1');
% Add a Parametric feature to the study step 's1':
p1 = s1.feature.create('p1', 'Parametric');
% Set the parameter name to use in the study step 's1':
p1.set('pname', {'Vtot'});
% Set the parameter value:
p1.set('plist', '20[mV] 40[mV]');
% Run the solver node 'sol1':
model.sol('sol1').run
Add a parametric sweep to the study node and define the width variable of the busbar
wbb as parameter to update and set two values in the parameter list.
% Add a batch node to the model:
p1 = model.batch.create('p1', 'Parametric');
% Set the parameter name to use:
p1.set('pname', {'wbb'});
% Set the parameter values:
p1.set('plist', '5[cm] 10[cm]');
36
The model contains a parametric study: one for the electric potential and one for the
geometry. For each geometry the solution is available as an outer solution.
To evaluate the temperature at (0.1,-2.5e-2, 5.1e-2) for the first geometry case (wbb
is set to 5 cm), enter the command:
Temp = mphinterp(model,'T','coord',[0.1;-2.5e-2;5.1e-2],...
'dataset','dset2','outersolnum',1);
To evaluate the temperature at (0.1,-2.5e-2, 5.1e-2) for the second geometry case
(wbb is set to 10 cm), enter the command:
Temp = mphinterp(model,'T','coord',[0.1;-2.5e-2;5.1e-2],...
'dataset','dset2','outersolnum',2);
37 |
Note: You do not need to run the entire M-file in the loop that sets up the model
object. It is sufficient to load the model object and only modify the parameter that
needs to be changed.
EXAMPLE
In this example use the busbar model from the Model Library and change some
parameters in a loop. The modified parameters are the geometry width and the electric
potential. Then evaluate the temperature at (0.1,-2.5e-2, 5.1e-2) for each cases.
% Load the model:
model = mphload('busbar');
Temp = {};
% Start the loop for the geometry parameter:
for width = [5e-2 10e-2]
% Start the loop for the electric potential:
for V = [20e-3 40e-3]
% Update the parameter values:
model.param.set('wbb',width);
model.param.set('Vtot',V);
% Compute the solution:
model.sol('sol1').run;
% Evaluate the temperature:
Temp = [Temp
mphinterp(model,'T','coord',[0.1;-2.5e-2;5.1e-2])];
end
end
[426.7054]
[309.3729]
[358.0418]
38
39 |
Creating Geometries
This section introduces you to Geometry Sequences and how to build them using
the LiveLink interface.
40
Geometry Sequences
This section describes how to set up and run a geometry sequence. For additional
information on geometry modeling, see the section Geometry Modeling and CAD
Tools in the COMSOL Multiphysics Users Guide.
You find reference information on geometry operations in Geometry API in the
COMSOL Java API Reference Guide.
In this section:
The Geometry Sequence Syntax
Working with Geometry Sequences
Exchanging Geometries with the COMSOL Desktop
Importing and Exporting Geometries and CAD Models from File
Retrieving Geometry Information
Modeling with a Parameterized Geometry
Images and Interpolation Data
where <tag> is a string that you use to refer to the geometry. The integer <sdim>
specifies the space dimension of the geometry.
To add an operation to a geometry sequence, use the syntax
model.geom(<tag>).feature.create(<ftag>,operation);
where <tag> is the string you defined when creating the geometry. The string <ftag>
is a string that you use to refer to the operation. To set a property to a value in an
operation, enter
model.geom(<tag>).feature(<ftag>).set(property,<value>);
where <ftag> is the string you defined when creating the operation.
Finally to build the geometry sequence, enter
model.geom(<tag>).run;
41 |
You find further details on available operations and properties in the geometry
sequence in Geometry API in the COMSOL Java API Reference Guide.
You can plot the geometry in MATLAB using the function mphgeom:
mphgeom(model,<tag>);
GEOMETRY SEQUENCES
42
mphgeom(model,'geom1','vertexmode','on')
Continue by creating a rectangle object with side length of 2 and centered at the
origin:
sq1 = geom2.feature.create('sq1','Square');
sq1.set('size',2);
sq1.set('base','center');
The property size describes the side lengths of the rectangle, and the property pos
describes the positioning. The default is to position the rectangle about its lower left
corner. Use the property base to control the positioning.
Create a circular hole with a radius of 0.5 centered at (0, 0):
c1 = geom2.feature.create('c1','Circle');
c1.set('r',0.5);
c1.set('pos',[0 0]);
43 |
The property r describes the radius of the circle, and the property pos describes the
positioning. The property pos could have been left out because the default position is
the origin. The default is to position the circle about its center.
Drill a hole in the rectangle by subtracting the circle from it:
co1 = geom2.feature.create('co1','Compose');
co1.selection('input').object('geom2');
co1.selection('input').set({'c1' 'sq1'});
co1.set('formula','sq1-c1');
A selection object is used to refer to the input object. The operators +, *, and correspond to the set operations union, intersection, and difference, respectively.
This example shows how to use the Compose operation and a set formula. Alternatively,
you can use the Difference operation instead of Compose.
If you have already added the above compose operation, you need to disable it first
before adding the Difference operation.
co1.active(false)
dif1 = geom2.feature.create('dif1','Difference');
dif1.selection('input').object('geom2');
dif1.selection('input').set({'sq1'});
dif1.selection('input2').set({'c1'});
Run the geometry sequence to create the geometry, and plot the result
geom2.run;
mphgeom(model,'geom2');
GEOMETRY SEQUENCES
44
Trimming Solids
To remove the corners and replace with rounded corners, add a fillet operation to the
sequence:
fil1 = geom2.feature.create('fil1','Fillet');
fil1.selection('point').object('geom2',0);
fil1.selection('point').set('dif1', [1 2 7 8]);
fil1.set('radius','0.5');
The geometry sequence is updated with rounded corners. To view the result, enter
mphgeom(model,'geom2');
Use the following commands to create six open curve segments that together form a
closed curve.
model = ModelUtil.create('Model');
g1 = model.geom.create('g1',2);
w=1/sqrt(2);
c1 = g1.feature.create('c1','BezierPolygon');
c1.set('type','open');
c1.set('degree',2);
c1.set('p',[-0.5 -1 -1;-0.5 -0.5 0]);
c1.set('w',[1 w 1]);
c2 = g1.feature.create('c2','BezierPolygon');
c2.set('type','open');
c2.set('degree',2);
c2.set('p',[-1 -1 -0.5;0 0.5 0.5]);
45 |
c2.set('w',[1 w 1]);
c3 = g1.feature.create('c3','BezierPolygon');
c3.set('type','open');
c3.set('degree',1);
c3.set('p',[-0.5 0.5; 0.5 0.5]);
c4 = g1.feature.create('c4','BezierPolygon');
c4.set('type','open');
c4.set('degree',2);
c4.set('p',[0.5 1 1; 0.5 0.5 0]);
c4.set('w',[1 w 1]);
c5 = g1.feature.create('c5','BezierPolygon');
c5.set('type','open');
c5.set('degree',2);
c5.set('p',[1 1 0.5; 0 -0.5 -0.5]);
c5.set('w',[1 w 1]);
c6 = g1.feature.create('c6','BezierPolygon');
c6.set('type','open');
c6.set('degree',1);
c6.set('p',[0.5 -0.5; -0.5 -0.5]);
GEOMETRY SEQUENCES
46
The objects c1, c2, c3, c4, c5, and c6 are all curve2 objects. The vector [1 w 1]
specifies the weights for a rational Bzier curve that is equivalent to a quarter-circle arc.
The weights are adjusted to create elliptical or circular arcs.
CREATING 3D GEOMETRIES USING SOLID MODELING
Add a rectangle to the work plane, then add fillets to all its corners:
r1 = wp1.geom.feature.create('r1', 'Rectangle');
r1.set('size',[1 2]);
geom1.run
fil1 = wp1.geom.feature.create('fil1', 'Fillet');
fil1.selection('point').set('r1', [1 2 3 4]);
fil1.set('radius', '0.125');
geom1.runCurrent;
ext1 = geom1.feature.create('ext1', 'Extrude');
ext1.set('distance', '0.1');
47 |
GEOMETRY SEQUENCES
48
geom1.run;
Create a model with the geometry sequence. Save the model from the COMSOL
Desktop. Create a model object from MATLAB and load the file into it.
A natural choice for storing geometries in 1D, 2D, and 3D is the native file format of
COMSOLs geometry kernel (.mphtxt, .mphbin).
Note: This file format is only used for geometry and mesh objects. It is not the same
as a Model MPH-file (.mph).
2D CAD FORMATS
COMSOL Multiphysics supports import and export for the DXF file format, a data
interchange format of the CAD system AutoCAD . You can also import files in the
neutral GDS format.
3D CAD FORMATS
It is possible to import surface meshes in the STL and VRML formats. COMSOL also
provides a CAD Import Module, which supports import of most 3D CAD file formats:
Parasolid, ACIS (SAT), STEP, IGES, Pro/ENGINEER, Autodesk Inventor ,
and SolidWorks . The CAD Import Module Users Guide discusses these file formats
in detail.
49 |
geom1.feature.create('con1','Cone');
geom1.run;
There are general geometry information methods. For example, to determine the
space dimension of the geometry, enter:
geom1.getSDim
There are also methods for determining the number of geometrical entities; for
example, inquire about the number of domains, and the number of boundaries:
geom1.getNDomains
geom1.getNBoundaries
There are also methods for evaluating properties, like coordinate values and curvatures
on faces and edges. This example evaluates coordinates and derivatives on face 1 for
parameter values (0.5, 0.5)
geom1.faceX(1,[[0.5,0.5]])
geom1.faceDX(1,[[0.5;0.5]])
To get the parameter length of edge number N you can use the edgeParamRange(N)
function, for instance to get the length of edge number 3 you just need to enter:
GEOMETRY SEQUENCES
50
geom1.edgeParamRange(3)
To get the coordinate and the curvature data along a specified edge:
geom1.edgeX(2,0.5)
geom1.edgeCurvature(2,0.5)
There are also methods for getting information about the geometry internal
representation, for example, the coordinates of the geometry vertices:
geom1.getVertex
In addition, you can fetch geometry information from elements in the geometry
sequence. To do this, you can, for example, enter
geom1.object('blk1').getNBoundaries
51 |
mphgeom(model,'geom1');
Change the position of the circle by setting parameter a to another MATLAB value,
and re-run the geometry sequence:
model.param.set('a','0.5');
geom1.run;
mphgeom(model,'geom1');
Create a mesh:
GEOMETRY SEQUENCES
52
model.mesh.create('mesh1', 'geom1');
Alternatively, you can run the parametric sweep using a MATLAB control statement:
for a=0.2:0.1:0.8
model.param.set('a',a);
std1.run;
end
The following illustrates how to use COMSOL 3.5a function to create a geometry for
a COMSOL 4.2 model object:
1 Start COMSOL 4.2 with MATLAB (3.5a Compatibility). On Windows go to the start
menu All programs > COMSOL 4.2 > COMSOL 4.2 with MATLAB (3.5a Compatibility). On
Linux/Mac enter at a terminal window the command
comsol server matlab -compat -c35aroot=<dir>/COMSOL35a
53 |
Where <dir> is the home directory where COMSOL Multiphysics 3.5a is installed.
2 Create a circle data, sorted by the angle, and remove some of the points:
phi = 0:0.2:2*pi;
phi([1 3 6 7 10 20 21 25 28 32]) = [];
p = [cos(phi);sin(phi)];
5 Create a square geometry object and create a composite geometry with the two
6 Create a FEM structure with the geometry and convert it to a model object with
GEOMETRY SEQUENCES
54
To create geometry with image files and MRI data you can follow the procedure
provided in the COMSOL 3.5a MATLAB Interface Guides section Geometry
Objects and Images under Images, Interpolation, and MRI Data. Once the
geometry is created with the COMSOL 3.5a commands you can convert it with this
procedure.
55 |
Modeling Physics
This chapter contains an introduction to modeling Physics Interfaces using
LiveLink for MATLAB.
56
Physics Interfaces
This section describes how to set up a physics interface. The physics interface defines
the equations that COMSOL solves. You find additional information on the physics
interfaces in Overview of the Physics Interfaces and the following sections in the
COMSOL Multiphysics Users Guide.
In this section:
The Physics Interface Syntax
Using Physics Interfaces
The Material Syntax
Using Materials
Modifying the Equations
Adding Global Equation
where <tag> is a string that you use to refer to the physics interface. The string
<physint> is the constructor name of the physics interface. The string <gtag> is the
geometry where you want to specify the interface.
To add a feature to a physics interface, use the syntax
model.physics(<tag>).feature.create(<ftag>,<operation>);
where <tag> is the string you defined when creating the physics interface. The string
<ftag> is a string that you use to refer to the operation. To set a property to a value
in a operation, enter
model.physics(<tag>).feature(<ftag>).set(property,<value>);
where <ftag> is the string you defined when creating the operation.
There are alternate syntaxes available. Consult the reference documentation for details.
You find further details on available physics interface constructors and physics interface
feature constructors in model.physics() in the COMSOL Java API Reference
Guide.
57 |
The tag of the interface is es. The physics interface constructor is Electrostatics.
The physics is set up on geometry geom1.
The physics interface creates a number of default features immediately. Examine these
by entering:
>> model.physics('es').feature
Type: List
Child tags: ccn1, zc1, init1
The first feature, ccn1, is the charge conservation equation. Establish this by entering:
>> model.physics('es').feature('ccn1')
Type: Charge Conservation
Tag: ccn1
Operation: ChargeConservation
PHYSICS INTERFACES
58
model.material.create(<tag>);
where <tag> is a string that you use to refer to the physics interface.
To add a material model, use the syntax
mm=model.material(<tag>).materialmodel.create(<mtag>,<descr>);
where <tag> is the string you defined when creating the material. The string <mtag>
is a string that you use to refer to the material model. The string <descr> is a
description of the material model. To set a property to a value in a operation, enter
mm.set(property,<value>);
You find further details on available physics interface constructors and physics interface
feature constructors in model.material() in the COMSOL Java API Reference
Guide.
The following sections contain examples of working with physics interfaces and
materials.
Using Materials
As an addition to the introductory model the section Using Physics Interfaces,
consider using a material to define the air in the model.
mat1=model.material.create('mat1');
The material automatically creates a material model, def, which you can use to set up
basic properties. Use it to define the relative permittivity:
mat1.materialmodel('def').set('relpermittivity', {'1'});
To use the defined material in your model, you must modify the Electrostastics
in Charge conservation feature with tag ccn1 to use the material.
es.feature('ccn1').set('epsilonr_mat', 1, 'from_mat');
You can then resolve the model using the material instead of the user-defined property:
model.study.create('std1');
model.study('std1').run;
59 |
The getInfoTable(<type>) method returns the list of the table defined for the weak
type ('Weak'), the constraint type ('Constraint'), or the expression type
('Expression').
To get the equations corresponding to the physics node <phys>:
Weak = Info.getinfoTable('Weak');
This returns a java.lang.string variable that contains both the name of the weak
equation variable and the equation of the physics implemented in the weak form. In
this example the following results:
list = weak(:)
list=
java.lang.String[]:
'(-es.Dx*test(Vx)-es.Dy*test(Vy))*es.d'
'root.mod1.es.weak$1'
Where root.mod1.es.weak$1 is the name of the field to modify if you want to modify
the governing equation. This can be done with the lock method, for instance:
Info.lock('root.mod1.es.weak$1',
{'(-es.Dx*test(Vx)-es.Dy*test(Vy))*1e-3'});
The above command changes the thickness of the material from the variable name
es.d to a constant value 1e-3.
To define the name of the variable to be solved by the global equation, enter
ge1.set('name', 1, 'u');
PHYSICS INTERFACES
60
61 |
Creating Meshes
This section introduces you to Meshing Sequences and how to build them using
the LiveLink interface.
62
Meshing Sequences
This section describes how to set up and run meshing sequences to create your meshes.
For additional information on meshing, see Creating Meshes in the COMSOL
Multiphysics Users Guide.
You find reference information in Meshing API in the COMSOL Java API Reference
Guide.
where <tag> is a string that you use to refer to the sequence. The tag <gtag> specifies
the geometry.
To add an operation to a sequence, use the syntax
model.mesh(<tag>).feature.create(<ftag>,<operation>);
where <tag> is the string you defined when creating the sequence. The string <ftag>
is a string that you use to refer to the operation. To set a property to a value in a
operation, enter
model.mesh(<tag>).feature(<ftag>).set(property,<value>);
where <ftag> is the string you defined when creating the operation.
Finally to build the sequence, enter
model.mesh(<tag>).run;
See Meshing API in the COMSOL Java API Reference Guide for more details on
available operations and properties in the sequence.
To plot the mesh in MATLAB with Handle Graphics, use the command
mphmesh(model,<tag>);
63 |
The Size attribute provides a number of input properties that you can use to control,
for example:
The maximum mesh size and curvature mesh size
The growth rate for the mesh size (away from small details)
The resolution of narrow regions
These properties are available both globally and locally.
There are nine predefined settings you can use to set a suitable combination of values
for many properties. To select one of these settings, use the property hauto and pass
an integer from 1 to 9 as its value to describe the mesh resolution:
Extremely fine (1)
Extra fine (2)
Finer (3)
Fine (4)
Normal (5)
Coarse (6)
Coarser (7)
Extra coarse (8)
Extremely coarse (9)
The default value is 5, that is, the Normal mesh settings. See the COMSOL
Multiphysics Reference Guide entry on Size for details about the mesh size values
for the predefined settings and all other properties.
MESHING SEQUENCES
64
mphmesh(model,'mesh1');
You can override this behavior by setting hauto to another integer. You can also
override by setting specific size properties, for example, making the mesh finer than
the default by specifying a maximum element size of 0.02:
mesh1.feature('size').set('hmax','0.02');
mesh1.run;
mphmesh(model,'mesh1');
65 |
This value corresponds to 1/50 of the largest axis-parallel distance, whereas the default
value is 1/15.
MESHING SEQUENCES
66
mphmesh(model,'mesh1');
67 |
mphmesh(model,'mesh1')
MESHING SEQUENCES
68
To create a structured quadrilateral mesh in 2D, use the Map operation. This operation
uses a mapping technique to create the quadrilateral mesh. For each domain, the
algorithm generates a logical mesh on a block geometry and then maps it onto the real
geometry by transfinite interpolation. The input geometry object must meet the
following criteria for the mapping technique to work:
Each domain must be bounded by one connected boundary component only.
Each domain must be bounded by at least four boundary segments.
The geometry must not contain isolated vertices or boundary segments.
The shape of each domain must not differ too much from a rectangular shape.
Use the EdgeGroup attribute to group the edges (boundaries) into four edge groups,
one for each edge of the logical mesh. Using the Distribution attribute you can also
control the edge element distribution, which determines the overall mesh density.
69 |
mesh1.run;
mphmesh(model,'mesh1');
Figure 5-6: Structured quadrilateral mesh (right) and its underlying geometry.
The EdgeGroup attributes specify that the four edges enclosing domain 1 are
boundaries 1 and 3; boundary 2; boundary 8; and boundary 4. For domain 2 the four
edges are boundary 4; boundary 5; boundary 7; and boundaries 9, 10, and 6.
BUILDING A MESH INCREMENTALLY
You can create meshes in a step-by-step fashion by creating selections for the parts of
the geometry that you want to mesh in each step. The following example illustrates the
procedure:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1',2);
geom1.feature.create('r1','Rectangle');
geom1.feature.create('c1','Circle');
uni1 = geom1.feature.create('uni1', 'Union');
uni1.selection('input').object('geom1');
uni1.selection('input').set({'c1' 'r1'});
geom1.runCurrent;
del1 = geom1.feature.create('del1', 'Delete');
del1.selection('input').object('geom1', 1);
del1.selection('input').set('uni1', 8);
geom1.run('del1');
mesh1 = model.mesh.create('mesh1','geom1');
dis1 = mesh1.feature.create('dis1', 'Distribution');
dis1.selection.set([2 4]);
dis1.set('type', 'predefined');
dis1.set('method', 'geometric');
dis1.set('elemcount', '20');
dis1.set('reverse', 'on');
dis1.set('elemratio', '20');
dis2 = mesh1.feature.create('dis2', 'Distribution');
MESHING SEQUENCES
70
dis2.selection.set([1 3]);
dis2.set('type', 'predefined');
dis2.set('method', 'geometric');
dis2.set('elemcount', '20');
dis2.set('elemratio', '20');
map1 = mesh1.feature.create('map1','Map');
map1.selection.geom('geom1', 2);
map1.selection.set(2);
mesh1.feature.create('frt1','FreeTri');
mesh1.run;
mphmesh(model,'mesh1');
The final mesh appears in Figure 5-7. Also note the effect of the Distribution
feature, with which you can control the distribution of vertex elements along geometry
edges.
Note that to get the FreeQuad feature before the FreeTri feature you need to
position the current point to point on the dis1 feature, and then insert the FreeQuad
feature.
Alternatively, you can selectively remove parts of a mesh by using the Delete feature.
For example, to remove the structured mesh from domain 2 along with the adjacent
edge mesh on edges 3 and 4, and replace it with an unstructured quad mesh, enter
these commands:
71 |
del1 = mesh1.feature.create('del1','Delete');
del1.selection.geom('geom1', 2).set(2);
del1.set('deladj','on');
frq1 = mesh1.feature.create('frq1','FreeQuad');
frq1.selection.geom('geom1', 2).set(2);
mesh1.run;
As usual, for further details on the various commands and their properties consult the
COMSOL Java API Reference Guide.
REVOLVING A MESH BY SWEEPING
Using the Sweep feature you can create 3D volume meshes by extruding and revolving
face meshes. Depending on the 2D mesh type, the 3D meshes can be hexahedral
(brick) meshes or prism meshes.
ExampleRevolving Mesh
Create and visualize a revolved prism mesh as follows:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('planetype', 'quick');
wp1.set('quickplane', 'xy');
c1 = wp1.geom.feature.create('c1', 'Circle');
c1.set('pos', [2, 0]);
rev1 = geom1.feature.create('rev1', 'Revolve');
rev1.set('angle2', '60').set('angle1', '-60');
rev1.selection('input').set({'wp1'});
geom1.run('rev1');
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.feature('ftri1').selection.geom(2);
mesh1.feature('ftri1').selection.set(2);
mesh1.runCurrent;
swe1 = mesh1.feature.create('swe1', 'Sweep');
swe1.selection.geom(3);
swe1.selection.add(1);
mesh1.run;
mphmesh(model,'mesh1')
MESHING SEQUENCES
72
To obtain a torus, leave the angles property unspecified; the default value gives a
complete revolution.
To generate a 3D prism mesh from the same 2D mesh by extrusion and then plot it,
enter the following commands:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('planetype', 'quick');
wp1.set('quickplane', 'xy');
c1 = wp1.geom.feature.create('c1', 'Circle');
c1.set('pos', [2, 0]);
ext1 = geom1.feature.create('ext1', 'Extrude');
ext1.selection('input').set({'wp1'});
geom1.runAll;
mesh1 = model.mesh.create('mesh1', 'geom1');
ftri1 = mesh1.feature.create('ftri1', 'FreeTri');
ftri1.selection.geom('geom1', 2);
ftri1.selection.set(3);
dis1 = mesh1.feature.create('dis1', 'Distribution');
dis1.selection.set(1);
dis1.set('type', 'predefined');
dis1.set('elemcount', '20');
dis1.set('elemratio', '100');
swe1 = mesh1.feature.create('swe1', 'Sweep');
swe1.selection('sourceface').geom('geom1', 2);
swe1.selection('targetface').geom('geom1', 2);
mesh1.run;
mphmesh(model,'mesh1');
73 |
The result appears in Figure 5-9. With the properties elemcount and elemratio you
control the number and distribution of mesh element layers in the extruded direction.
See Distribution in the COMSOL Java API Reference Guide.
You can combine swept meshing with free meshing. Just specify selections for the
meshing. In this case, start by free meshing domain 2, then sweep the resulting surface
mesh through domain 1.
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
cone1 = geom1.feature.create('cone1', 'Cone');
cone1.set('r', '0.3');
cone1.set('h', '1');
cone1.set('ang', '9');
cone1.set('pos', [ 0 0.5 0.5]);
cone1.set('axis', [-1 0 0]);
geom1.feature.create('blk1', 'Block');
mesh1 = model.mesh.create('mesh1', 'geom1');
ftet1 = mesh1.feature.create('ftet1', 'FreeTet');
ftet1.selection.geom('geom1', 3);
ftet1.selection.set(2);
swe1 = mesh1.feature.create('swe1', 'Sweep');
swe1.selection('sourceface').geom('geom1', 2);
swe1.selection('targetface').geom('geom1', 2);
mesh1.run;
MESHING SEQUENCES
74
mphmesh(model,'mesh1');
For 2D and 3D geometries it is also possible to create boundary layer meshes using the
BndLayer feature. A boundary layer mesh is a mesh with dense element distribution
in the normal direction along specific boundaries. This type of mesh is typically used
for fluid flow problems to resolve the thin boundary layers along the no-slip
boundaries. In 2D, a layered quadrilateral mesh is used along the specified no-slip
boundaries. In 3D, a layered prism mesh or hexahedral mesh is used depending on if
the corresponding boundary layer boundaries contain a triangular or a quadrilateral
mesh.
If you start with an empty mesh, the boundary-layer mesh uses free meshing to create
the initial mesh before inserting boundary layers into the mesh. This generates a mesh
with triangular and quadrilateral elements in 2D and tetrahedral and prism elements in
3D. The following example illustrates the procedure in 2D:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 2);
r1 = geom1.feature.create('r1', 'Rectangle');
r1.set('size', [10, 5]);
c1 = geom1.feature.create('c1', 'Circle');
c1.set('pos', [3.5 2.5]);
dif1 = geom1.feature.create('dif1', 'Difference');
dif1.selection('input2').object('geom1');
dif1.selection('input').object('geom1');
dif1.selection('input').set({'r1'});
dif1.selection('input2').set({'c1'});
75 |
geom1.runAll;
mesh1 = model.mesh.create('mesh1', 'geom1');
bl1 = mesh1.feature.create('bl1', 'BndLayer');
bl1.feature.create('blp1', 'BndLayerProp');
bl1.feature('blp1').selection.set([2 3 5 6 7 8]);
mesh1.run;
mphmesh(model,'mesh1');
Initial unstructured quad mesh (left) and resulting boundary layer mesh (right).
MESHING SEQUENCES
76
Use the stat method on the meshing sequence to get information on the mesh
quality. The quality measure is a scalar quantity, defined for each mesh element, where
0 represents the lowest quality and 1 represents the highest quality.
The following commands illustrate how to visualize the mesh quality for a mesh on the
unit circle:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('c1', 'Circle');
geom1.runAll;
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.run;
meshdset1 = model.result.dataset.create('mesh1', 'Mesh');
meshdset1.set('mesh', 'mesh1');
pg1 = model.result.create('pg1', 2);
meshplot1 = pg1.feature.create('mesh1', 'Mesh');
meshplot1.set('data', 'mesh1');
meshplot1.set('filteractive', 'on');
meshplot1.set('elemfilter', 'quality');
meshplot1.set('tetkeep', '0.25');
mphplot(model,'pg1');
meshplot1.set('elemfilter','qualityrev');
meshplot1.run;
mphplot(model,'pg1');
These commands display the worst 25% and the best 25% elements in terms of mesh
element quality. Notice in Figure 5-11 how the triangular mesh elements in the plot
to the right are more regular than those in the left plot; this reflects the fact that a
quality measure of 1 corresponds to a uniform triangle, while 0 means that the triangle
has degenerated into a line.
Figure 5-11: Visualizations of the mesh quality: worst 25% (left) and best 25% (right).
77 |
REFINING MESHES
Given a mesh consisting only of simplex elements (lines, triangles, and tetrahedra) you
can create a finer mesh using the feature Refine. Thus
mesh1.feature.create('ref1', 'Refine');
Use the CopyEdge feature in 2D and the CopyFace feature in 3D to copy a mesh
between boundaries. It is only possible to copy meshes between boundaries that have
the same shape. However, a scaling factor between the boundaries is allowed. The
following example demonstrates how to copy a mesh between two boundaries in 3D
and then create a swept mesh on the domain.
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('planetype', 'quick');
wp1.set('quickplane', 'xy');
c1 = wp1.geom.feature.create('c1', 'Circle');
c1.set('r', 0.5);
c1.set('pos', [1, 0]);
rev1 = geom1.feature.create('rev1', 'Revolve');
rev1.set('angle1', '0').set('angle2', '180');
rev1.selection('input').set({'wp1'});
MESHING SEQUENCES
78
geom1.run('wp1');
mesh1 = model.mesh.create('mesh1', 'geom1');
size1 = mesh1.feature.create('size1', 'Size');
size1.selection.geom('geom1', 1);
size1.selection.set(18);
size1.set('hmax', '0.06');
ftri1 = mesh1.feature.create('ftri1', 'FreeTri');
ftri1.selection.geom('geom1', 2);
ftri1.selection.set(10);
cpf1 = mesh1.feature.create('cpf1', 'CopyFace');
cpf1.selection('source').geom('geom1', 2);
cpf1.selection('destination').geom('geom1', 2);
cpf1.selection('source').set(10);
cpf1.selection('destination').set(1);
sw1 = mesh1.feature.create('sw1', 'Sweep');
sw1.selection('sourceface').geom('geom1', 2);
sw1.selection('targetface').geom('geom1', 2);
mesh1.run;
mphmesh(model,'mesh1');
The algorithm automatically determines how to orient the source mesh on the target
boundary, and the result looks like this:
You can explicitly control the orientation of the copied mesh by using the EdgeMap
attribute. The command sequence
em1 = cpf1.feature.create('em1', 'EdgeMap');
em1.selection('srcedge').set(18);
em1.selection('dstedge').set(2);
mesh1.feature.remove('sw1');
mesh1.feature.create('ftet1', 'FreeTet');
mesh1.run;
mphmesh(model,'mesh1');
copies the mesh between the same boundaries as in the previous example, but now the
orientation of the source mesh on the target boundary is different. The domain is then
79 |
meshed by the free mesh, resulting in the mesh shown in the next figure. Note that in
this case it is not possible to create a swept mesh on the domain because the boundary
meshes do not match in the sweeping direction.
MESHING SEQUENCES
80
To import a mesh stored in a supported format use the Import feature. The following
commands import and plot a NASTRAN mesh for a crankshaft:
model = ModelUtil.create('Model');
model.geom.create('geom1', 3);
mesh1 = model.mesh.create('mesh1', 'geom1');
imp1 = mesh1.feature.create('imp1', 'Import');
imp1.set('filename','<dir>\\COMSOL42\\models\\
COMSOL_Multiphysics\\Structural_Mechanics\\crankshaft.nas');
mesh1.feature('imp1').importData;
mesh1.run;
mphmesh(model,'mesh1');
81 |
Where <dir> is the path of root directory where COMSOL Multiphysics 4.2 is
installed
You can access the model mesh statistics with the mphmeshstats function:
stats = mphmeshstats(model,'mesh1');
MESHING SEQUENCES
82
To get the coordinates of the mesh vertices as a matrix data where each column
corresponds to a vertex mesh, you can use
Vertex = mesh1.getVertex;
To get the number of triangle elements ('tri') and the elements, you can use
NumElemTri = mesh1.getNumElem('tri');
Elem = mesh1.getElem('tri');
It is also possible to set mesh data via the data method. Using this method you access
a temporary object (MeshData) storing mesh data. When you use the data method the
first time, the MeshData object is empty. You can fill it with mesh data either by using
various set method or by transferring mesh data from the mesh of the meshing
sequence. Call the data.createMesh method to construct a complete mesh from the
MeshData object and store it in the meshing sequence. If the geometry is not empty,
the new mesh is checked to ensure that it matches the geometry. Thus, to create an
83 |
arbitrary mesh you need to create an empty geometry sequence and a corresponding
empty meshing sequence and construct the mesh on the empty meshing sequence.
The following example creates a triangular mesh on a square, extracts the vertices and
the triangle. Then the vertices are transformed (the coordinates values are divided by
2) and inserted into a new meshing sequence:
model = ModelUtil.create('Model');
model.modelNode.create('mod1');
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('sq1', 'Square');
geom1.run;
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.run('ftri1');
mphmesh(model,'mesh1');
vtx = mesh1.getVertex;
tri = mesh1.getElem('tri');
for k = 1:length(vtx)
vtx(:,k)=vtx(:,k)*0.5;
end
geom2 = model.geom.create('geom2', 2);
mesh2 = model.mesh.create('mesh2', 'geom2');
mesh2.data.setElem('tri',tri);
mesh2.data.setVertex(vtx);
mesh2.data.createMesh;
MESHING SEQUENCES
84
mphmesh(model,'mesh2');
85 |
Creating Studies
This section introduces you to setting up and running studies for solving models
using the LiveLink interface.
86
The Study
This section describes how to set up and run a study. The study contains basic solver
settings. COMSOL uses the physics interfaces and the study to automatically
determine solver settings. You find additional information on the study in Solvers and
Study Types in the COMSOL Multiphysics Users Guide. Reference information is
described in Solver API in the COMSOL Java API Reference Guide.
where <tag> is a string that you use to refer to the study sequence.
To add a study step to a study, use the syntax
model.study(<tag>).feature.create(<ftag>,<operation>);
where <tag> is the string you defined when creating the study. The string <ftag> is a
string that you use to refer to the study step. To set a property to a value in a study
step, enter
model.study(<tag>).feature(<ftag>).set(property,<value>);
where <ftag> is the string you defined when creating the operation.
To run the study, enter
model.study(<tag>).run
The study is initially empty. The study needs to know the type of analysis that you want
to perform. For example, create a Stationary study step to specify a stationary analysis.
std1.feature.create('stat1', 'Stationary');
87 |
std1.run;
This automatically generates a solver sequence and runs it. The solver sequence can be
set up automatically from the study or be created manually.
Alternatively, create a time-dependent study running from 0 to 10 with a step of 1 by
entering
time1 = std1.feature.create('time1', 'Transient');
time1.set('tlist', 'range(0,1,10)');
std1.run;
where <tag> is a string that you use to refer to the solver configuration.
To add a solver operation, use the syntax
model.sol(<tag>).feature.create(<ftag>,<operation>);
where <tag> is the string you defined when creating the operation. The string <ftag>
is a string that you use to refer to the study step. To set a property to a value in a study
step, enter
model.sol(<tag>).feature(<ftag>).set(<property>,<value>);
where <ftag> is the string you defined when creating the operation.
To run the solver configuration, enter
model.sol(<tag>).run
See also Solver API in the COMSOL Java API Reference Guide.
THE STUDY
88
sol1.feature.create('v1', 'Variables');
sol1.feature.create('s1', 'Stationary');
The study determines what equation form (stationary, time-dependent, and so on) to
use for generating the equations that you solve.
The variables step automatically determines the available variables. You might want to
specify the variables solved for in the variables step.
The solution steps can be of different types, for example, stationary to indicate that you
solve for a stationary solution.
The solver configuration needs to be attached to its study.
sol1.attach(true);
89 |
L
D = -------
U
L
E = ------
U
M
N = -------U
where:
K is the stiffness matrix
D is the damping matrix
E is the mass matrix
Nis the constraint Jacobian matrix
All these matrices can depend on the solution vector U. The matrices K, D, and E can
also depend on the time derivatives of U.
G E T T I N G T H E S Y S T E M M A T R I C E S I N M AT L A B
The matrices system can be extracted in MATLAB with the command mphmatrix. You
only need to define the solver node Solname to use and the list Out of the system
matrices to extract (defined as a cell array):
dat = mphmatrix(model,Solname,'Out',Out);
See the following list of the matrices that you can extract with the mphmatrix
command:
EXPRESSION
DESCRIPTION
Stiffness matrix
Load vector
Constraint vector
Constraint Jacobian
Damping matrix
Mass matrix
NF
NP
MP
MLB
MUB
Kc
Lc
Dc
Ec
Null
Nullf
THE STUDY
90
EXPRESSION
DESCRIPTION
ud
Particular solution ud
uscale
Scale vector
For instance, in the introductory example in section A Simple Model Example extract
the stiffness matrix and the eliminated stiffness matrix with the following commands:
MA = mphmatrix(model,'sol1','as1','Out',{'K','L'});
The stiffness matrix and the residual are available using MA.K and MA.L. If the solution
has been computed you can verify that the residual is close to zero.
Note that the assembly of the eliminated matrices uses the current solution vector as
scaling. If you have a solver step in your solver configuration
You can get the unscaled matrices by removing setting the scaling method to none in
the variables step of the solver configuration, for instance:
model.sol('sol1').feature('v1').set('scalemethod','none');
MA = mphmatrix(model,'sol1','as1','Out',{'Kc'});
If you want to extract the system matrices and the load vector you need to make sure
that no solver step node is added to the solver configuration node. If you have one you
can disable it with the command:
model.sol('sol1').feature('s1').active(false);
MA = mphmatrix(model,'sol1','as1','Out',{'Kc' 'Lc'});
SOLVING A SIMPLE PROBLEM IN THE MATRIX LEVEL
The following example illustrate how to use the mphmatrix command to extract the
eliminated system matrices and solve the stationary problem at the MATLAB prompt.
The problem studied here is a linear heat transfer problem solved on a unit square with
a surface heat source and temperature constraint.
% Create a new model object
model = ModelUtil.create('Model');
% Create a square geometry
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('sq1', 'Square');
geom1.run;
% Setup material properties
mat1 = model.material.create('mat1');
def = mat1.materialModel('def');
def.set('thermalconductivity',{'4e2'});
def.set('density',{'8e3'});
91 |
def.set('heatcapacity',{'2e3'});
% Define the physics settings
ht = model.physics.create('ht', 'HeatTransfer', 'geom1');
hs1 = ht.feature.create('hs1','HeatSource',2);
hs1.selection.set(1);
hs1.set('Q',1,'1e5');
temp1 = ht.feature.create('temp1','TemperatureBoundary',1);
temp1.selection.set([1 2]);
% Create a mapped mesh
mesh1 = model.mesh.create('mesh1','geom1');
dis1 = mesh1.feature.create('dis1','Distribution');
dis1.selection.set([1 2]);
dis1.set('numelem','2');
mesh1.feature.create('map1','Map');
mesh1.run;
% Solve the problem
std1 = model.study.create('std1');
std1.feature.create('stat','Stationary');
std1.run;
You can extract the solution vector with the mphgetu function:
U = mphgetu(model);
In order to extract the residual without using the final solution as linearization point
we need to deactivate the solver step node. Not doing this operation results in an
almost null residual:
model.sol('sol1').feature('s1').active(false);
Extract the eliminated system include the Null space-basis, the scale vector and the
particular solution:
MA =
mphmatrix(model,'sol1','Out',{'Kc','Lc','Null','ud','uscale'});
Solve for the eliminated solution vector using the extracted system:
Uc = MA.Null*(MA.Kc\MA.Lc);
Now compare both solution vector U and U1 computed by COMSOL and by the
matrix operation respectively.
THE STUDY
92
The vector x is called the state vector. The state-space form of the model is
dx
------- = Ax + Bu
dt
y = Cx + Du
dx
M C ------- = M A x + M B u
dt
y = Cx + Du
This form is more suitable for large systems because the matrices MC and MA usually
become much more sparse than A.
If the mass matrix MC is small, it is possible to approximate the dynamic state-space
model with a static model, where M = 0:
0 = McAx + McBu
y = Cx + Du
93 |
To get the state-space matrices of a given model, use the mphstate function with the
following syntax:
dat = mphstate(model,Solname, 'Out',Out,'input',...
input_param,'output',output_expr);
Where Solname is the tag of the solver sequence to use for the matrices evaluation.
input_param is the list of the input variables defined as parameters in the model.
output_expr is the list of expressions to use as output in the state-space system. Out
is the list of the matrices you wish assemble, see below the list of the matrices that can
be extracted with the mphstate command:'
EXPRESSION
DESCRIPTION
MA
McA matrix
MB
McB matrix
C matrix
D matrix
Mc
Mc matrix
Null
Null matrix
ud
ud vector
x0
x0 vector
Two optional properties are also available with the mphstate function:
keepfeature, mphstate leave the state-space feature node in the solver sequence
when keepfeature property is set to on. The default value is off.
sparse, mphstate assemble sparse matrices when the sparse property is set to on.
The default value is off.
EXAMPLE
To illustrate how to use the mphstate function to extract the state-space matrices of
the model described in A Simple Model Example. The surface charge density defines
the input of the state-space system, the electric potential at point (0.8;0.9) defines the
output of the system.
1 To create the model, the geometry and the mesh enter the following command at
THE STUDY
94
geom1.run;
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('fre1', 'FreeTri');
The default expression of the probe being the electric potential V, you dont need to
redefine it.
5 Create the study and define the solver sequence:
std1 = model.study.create('std1');
stat1 = std1.feature.create('stat1', 'Stationary');
sol1 = model.sol.create('sol1');
sol1.study('std1');
sol1.feature.create('st1', 'StudyStep');
sol1.feature.create('v1', 'Variables');
sol1.feature.create('s1', 'Stationary');
6 To extract the state space matrices use the mphstate function as described below:
M = mphstate(model,'sol1','Out',{'MA','MB','C','D'},...
'input','rhos','output','mod1.ppb1');
The mphstate function runs the entire solver sequence sol1 and returns a structure
M containing the state-space matrices available at the following fields: M.MA, M.MB, M.C,
and M.D.
The matrices are assembled using the current solution vector as linearization point. If
you do not want to run the problem again when evaluating the state space matrices or
if you want to use a specific solution as linearization point you can create a new solver
sequence.
95 |
The example below shows how to create a new solver sequence in order to extract the
state space system using the previous model already solved.
7 Enter the command below to create an new solver:
sol2 = model.sol.create('sol2');
You need then to attach the solver sequence to the existing study and a Variables
feature, this is done by entering the following commands:
sol2.feature.create('st1','StudyStep');
sol2.study('std1');
v1 = sol2.feature.create('v1','Variables');
Set the linearization point using the solution computed by the solver sequence sol1:
v1.set('initmethod','sol');
v1.set('initsol','sol1');
Extract the state space matrices using the mphstate function as the following:
M = mphstate(model,'sol2','Out',{'A','B','C','D'},...
'input','rhos','output','mod1.ppb1');
Note: In the case where the solver sequence solution sol1 is stored for several
parameter value, as for a time-dependent problem. You can set the linearization point
for a specific parameter value. This is possible with the command:
model.sol(<solname>).feature(<VarTag>).set(solnum,<sol_num>)
THE STUDY
96
Creating Solution
You can use the createSolution method available for the solver feature in order to
create a new solution vector.
To create a proper solution vector, include both parameter values and the solution
vector, to proceed use the method setPVals and setU respectively:
model.sol(<solname>).setPVals(PVals);
model.sol(<solname>).setU(U);
Where <solname> is the solver tag, PVals the list of parameter values and U the
solution vector to use.
Finally create the solution vector with the createSolution method:
model.sol(<solname>).createSolution;
EXAMPLE: COMBINE SOLUTION VECTORS
This example illustrate how you can combine two transient solution vectors into one.
Each solution vector contains the solutions of a transient heat transfer problem for a
different set of time. The command illustrates how to combine the two solution
vectors in order to access the solution at all time steps directly from within the same
solution vector. Set up a basic 2D transient heat transfer problem, solve it for 200
seconds and save the model as a MPH file. Then solve for the next 200 seconds and
97 |
save the second solution in a different file. The heat transfer problem consist of a
quarter of piece of copper with a an internal heat source of 5e5[w/m^3].
1 Run the command below at the MATLAB prompt in order to obtained the two
THE STUDY
98
model.sol('sol1').feature('v1').set('initsol', 'sol1');
std1.run;
% Save the first model as filename2
model.save('filename2')
2 Now that both solution vectors are created, load the models saved in filename1 and
3 Compare the solutions by plotting the plot group pg1 for each model object:
mphplot(model1,'pg1')
mphplot(model2,'pg1')
4 Create a new model object 'Model' that contains the new combined solution
model = mphload(fullfile(tempdir,'Model_step1'),'Model');
6 Create a new list of time step. Note in this example PVals1(end) and PVals2(1) are
the same.
PVals = [PVals1;PVals2(2:end)];
7 Set the first solution vector (available in model1) to the new model object model.
The getU method extract the value of the solution vector, while the setU method
set a vector in a solution vector.
for i = 1:length(PVals1);
U = model1.sol('sol1').getU(i);
model.sol('sol1').setU(i,U);
end
8 Set the second solution vector (available in model2) to the new model object model,
99 |
Note: The first time step of the second solution is disregarded as it is the same as the
last time step of the first solution vector.
THE STUDY
100
101 |
Analyzing Results
This section introduces you to analyzing results using the LiveLink interface.
102
Results
This chapter describes how to do results analysis and visualization. You find additional
information on meshing in Results Evaluation and Visualization in the COMSOL
Multiphysics Users Guide.
Reference information on the meshing operations in the COMSOL Java API are
described in Results API in the COMSOL Java API Reference Guide 4.2.
where <tag> is a string that you use to refer to the plot group, and dim is the space
dimension of the plot group.
To add a plot feature to a plot group, use the syntax
model.result(<tag>).feature.create(<ftag>,<operation>);
where <tag> is the string you defined when creating the plot group. The string <ftag>
is a string that you use to refer to the plot feature. To set a property to a value in a plot
feature, enter
model.result(<tag>).feature(<ftag>).set(property,<value>);
where <ftag> is the string you defined when creating the feature.
Use the mphplot function to render the plot in a figure:
mphplot(model,<tag>)
This renders the plot group in a MATLAB plot using Handle Graphics. See the
reference entry for mphplot for more information.
Alternatively, to plot using a COMSOL plot window, enter
model.result(<tag>).run
This only works if you started COMSOL with the -graphics option.
103 |
You find further details under model.result() in the COMSOL Java API Reference
Guide.
The following sections contain examples of working with plot groups.
A plot group needs a data set to plot. By default, a solution data set tagged 'dset1'
is created. You need to point the plot group to a data set:
model.result('pg2').set('data', 'dset1');
Finally, to render the plot group in MATLAB, use the mphplot function:
mphplot(model,'pg2');
This renders the graphics in a MATLAB figure window. To plot the plot group in a
COMSOL graphics window, make sure you have started COMSOL with MATLAB
using the -graphics option and enter
RESULTS
104
mphplot(model,'pg2','server','on');
To get a height plot (for 2D plots only) you can add a Height feature. For instance:
htgh1 =
model.result('pg1').feature('surf1').feature.create('htgh1','Heig
ht');
htgh1.set('heightdata','expr');
htgh1.set('expr','es.normE');
105 |
mphplot(model,'pg1');
You can also define a color expression feature with a Color feature:
col1 = cont1.feature.create('col1','Color');
col1.set('col1','Color');
col1.set('expr','es.normE');
mphplot(model,'pg2');
To filter the color data (for example, to plot data only where x<0.5) you can create a
Filter feature:
filt1 = cont1.feature.create('filt1','Filter');
filt1.set('expr','x<0.5');
RESULTS
106
mphplot(model,'pg2');
To get a deformed plot you can create a Deform feature on the plot feature.
PLOT TYPE LISTINGS
The 1D plot group can be defined with the feature listed in the following table:
TABLE 7-1: FEATURES AVAILABLE FOR 1D PLOT GROUP
FEATURE NAME
DESCRIPTION
LineGraph
1D Line Plot
Global
PointGraph
Point plot
Table
Table plot
The 2D plot group can be defined with the feature listed in the following table:
TABLE 7-2: FEATURES AVAILABLE FOR 1D PLOT GROUP
107 |
FEATURE NAME
DESCRIPTION
ArrrowLine
ArrowSurface
Contour
Contour plot
CoordSysSurface
Line
2D Line plot
MaxMinLine
MaxMinSurface
DESCRIPTION
Mesh
Mesh plot
Particle
ParticleMass
PrincipalSurface
ScatterSurface
Scatter plot
Streamline
Streamline plot
Surface
Surface plot
The 3D plot group can be defined with the feature listed in the following table:
TABLE 7-3: FEATURE AVAILABLE FOR 3D PLOT GROUP
FEATURE NAME
DESCRIPTION
ArrowLine
ArrowSurface
ArrowVolume
Contour
Contour plot
CoordSysLine
CoordSysSurface
CoordSysVolume
Isosurface
Isosurface plot
Line
Line plot
MaxMinLine
MaxMinSurface
MaxMinVolume
Mesh
Mesh plot
Particle
ParticleMass
PrincipalSurface
PrincipalVolume
ScatterVolume
Slice
Slice plot
Streamline
Streamline plot
RESULTS
108
DESCRIPTION
Surface
Surface plot
Volume
Volume plot
Not all plot feature can have subfeatures (attributes). Below is the a list of subfeatures
for each plot type:
TABLE 7-4: SUBFEATURE LIST FOR PLOT TYPES
SUBFEATURE
PLOT TYPES
Color
Deform
Height
Filter
POLAR PLOT
You can generate a polar plot by adding a polar plot group to the results node:
model.result.dataset.create(<pgname>, 'PolarGroup');
In a polar plot group you can set a Line, Point, Global, or Table plot. And then
define the radial and the angular spacing with the method .set(rspacing,<value>)
and .set(tsapcing,<value>), respectively.
where <tag> is a string that you use to refer to the data set and dtype is a data set type.
To set a property to a value in a data set, type
model.result.dataset(<tag>).set(property,<value>);
where <tag> is the string you defined when creating the data set feature.
109 |
Using the simple example in A Simple Model Example, extend the results by showing
a cross-section line plot from the coordinates (0, 0.5) to (1, 0.5). To do this, you can
create a 2D cross section data set and an 1D plot group. Start by creating the data set:
model.result.dataset.create('cln1', 'CutLine2D');
model.result.dataset('cln1').setIndex('genpoints','0.5',0,1);
model.result.dataset('cln1').setIndex('genpoints','0.5',1,1);
Then create the 1D plot group with a line graph feature that uses the data set:
model.result.create('pg3', 1);
model.result('pg3').feature.create('lngr1', 'LineGraph');
model.result('pg3').set('data', 'cln1');
DIMENSION
DESCRIPTION
Solution
All
Mesh
All
CutPlane
CutLine3D
CutPoint3D
Edge3D
Isosurface
RESULTS
110
DIMENSION
DESCRIPTION
ParCurve3D
ParSurface
Surface
Contour
CutLine2D
CutPoint2D
Edge2D
Mirror2D
Parametric2D
ParCurve2D
Revolved2D
CutPoint1D
Parametric1D
Revolved1D
Evaluating Data
The function mpheval lets you evaluate the result on domains at the MATLAB
prompt.
For example, using the simple example in section A Simple Model Example, to evaluate
the electrical potential V in the node points of the model, enter
pd = mpheval(model,'V')
This returns a structure pd that contains the evaluated expressions and various other
information:
pd.p contains the node point coordinates information.
pd.t contains the indices to columns in pd.p of a simplex mesh; each column in
pd.t represents a simplex.
pd.ve contains the indices to mesh elements for each node points.
pd.expr contains the value of the expression V at each node points.
pd.unit contains the list of the unit of the expressions.
You can evaluate the expression on different element dimension level using the Edim
property. For instance, evaluate the electric potential on boundary 3:
111 |
pd = mpheval(model,'V','Edim',1,'Selection',3);
It is possible to evaluate the expression on both the outer solution (the one generated
by a parametric sweep) or the inner solution (the one that result of the parametric, time
dependent, or eigenvalue solver). These solution can be accessed with the
Outersolnum and the Solnum property, respectively.
In the above example you can add a parametric step in the solver sequence node in
order to vary the surface charge density. First add a parameter in the model:
model.set.param.set('rhos','1e-10');
Set the surface charge density boundary condition with the new parameter:
sfcd1.set('rhoqs',1,'rhos');
Finally add activate the parametric analysis and set the parameter range to solve for:
std1.feature('stat').set('useparam','on');
std1.feature('stat').set('pname',{'rhos'});
std1.feature('stat').set('plist','range(1e-10,1e-10,10e-10)');
To access the electric potential for the third parameter value use:
pd = mpheval(model,'V','solnum',3)
Now you can add a parametric sweep in order to vary the relative permittivity of the
material. First of all define a new parameter for the relative permittivity:
model.set.param.set('mu','1');
You can now evaluate the electric potential for mur=2 and rhos=5e-10 with the
following command:
RESULTS
112
pd = mpheval(model,'V','solnum',5,'outersolnum',2)
Integrating Expressions
The function mphint lets you to evaluate the integral value of any expression at the
MATLAB prompt.
For instance, integrate the electric potential V over the domain and evaluate the surface
area of the geometry to manually compute the average electric potential:
Int_V = mphint(model,'V');
Surface = mphint(model,'1');
average = Int_V/Surface
Interpolating Data
The function mphinterp lets you interpolate results on domains.
For example, to interpolate the electric potential V at a specified set of coordinates,
enter
V = mphinterp(model,'V','coord',[0 0.1;0.1 0.1])
113 |
plot(y,V)
Generating Reports
The export method allows the user to generate an animation or to export data to an
external file (ASCII format).
ANIMATION EXPORT
You can define an animation as two different types: a movie or an image sequence. The
movie generates file formats such as GIF (.gif), AVI (.avi), or flash (.swf); the image
sequence generates a sequence of images.
To generate an animation, add an Animation node to the export method:
anim1 = model.result.export.create('anim1', 'Animation');
To change the animation type you can use either the imageseq or movie option as in
the following command:
anim1.set('type', 'imageseq');
To set the filename and run the animation use the following commands:
anim1.set(typefilename,<filenname>);
anim1.run;
RESULTS
114
For a movie type it is possible to change the number of frames per second with the
command:
anim1.set('fps','fps_number');
where width_px and height_px are the width and height size (in pixels) respectively
to use for the animation.
DATA EXPOR T
In order to extract data value to an ASCII file, create a Data node to the export
method:
data1 = model.result.export.create('data1', 'Data');
Set the expression and the filename, and run the export:
data1.setIndex('expr', 'T', 0);
data1.set('filename', <filenname>);
data1.run;
The default data structure is spreadsheet, and the format is the following:
% Model:
% Version:
% Date:
% Dimension:
% Nodes:
% Expressions:
% Description:
% x
y
x1
y1
x2
y2
filename.mph
COMSOL 4.0.0.974
Jun 8 2010, 11:17
2
1272
20
data
data1
data2
In case of multiple solution fields (as for a parametric, transient, or eigenvalue analysis)
extra columns are added corresponding to solution data at each parameter, time step,
or eigenvalue.
The sectionwise data structure generates the file in the format below:
% Model:
% Version:
115 |
filename.mph
COMSOL 4.0.0.974
% Date:
% Dimension:
% Nodes:
% Elements:
% Expressions:
% Description:
% Coordinates
x1
y1
x2
y2
...
% Elements (triangles)
node11
node12
node21
node22
...
% Data
data1
data2
...
node13
node23
RESULTS
116
117 |
118
Converting M-Files
In this section:
M-File Conversion
M-File Conversion, Including a For Loop
Converting Postprocessing Sequences
Unsupported Functions in COMSOL Multiphysics 4.2
M-File Conversion
LAUNCHING THE LIVELINK INTERFACE IN COMPATIBILITY MODE
To support the conversion from COMSOL 3.5a there is a separate launcher available,
which lets you run models represented in 3.5a syntax along with version 4 models. To
start MATLAB in compatibility mode, use the following:
Windows: Select COMSOL with MATLAB (COMSOL 3.5a Compatibility) under COMSOL 4.2
from the Windows Start menu.
Linux and Mac: Start COMSOL with MATLAB with the command
comsol server matlab -compat -c35aroot <COMSOL 3.5a root directory>
Having started MATLAB in this way you should have access to all documented
functionality in COMSOL 3.5a from MATLAB as well as the version 4 functionality
in LiveLink for MATLAB.
The conversion of an M-file from 3.5a to version 4 is based on running your M-file in
the compatibility mode and then using the mphv4 command to create a version 4
model object.
CONVERTING USING THE FEM STRUCTURE
The mphv4 command accepts a COMSOL 3.5a FEM structure as input. However, the
FEM structure does not contain any of the meshing settings, solver settings, nor the
postprocessing settings.
To convert any M-file using a FEM structure.
1 Run the M-file in compatibility mode to create a FEM structure.
119 |
4 Edit the M-file, including settings for meshing, solving, results evaluation, and
visualization.
CONVER TING USING THE FEMGUI OBJECT
The mphv4 command accepts a COMSOL 3.5a FEM structure as input. The FEMGUI
object includes meshing settings, solver settings, and the postprocessing settings.
To convert any M-file using a FEMGUI object.
1 Make sure you have FEMGUI object available instead of a FEM structure:
fem=femgui
5 Edit the M-file, including settings for meshing, solving, results evaluation, and
visualization.
EXAMPLES
This first example illustrates how to convert a Model M-file in 3.5a format to a 4.2
Model M-file. The following M-file is used for the conversion:
fem.geom=rect2(1.6,1,'base','corner','pos',[-0.8,0]);
fem.const={'Q0','1e5'};
fem.mesh=meshinit(fem,'hauto',3);
fem.appl.mode.class = 'HeatTransfer';
fem.appl.sshape = 2;
fem.appl.assignsuffix = '_ht';
fem.appl.bnd.type = {'q0','T'};
fem.appl.bnd.ind = [2,2,1,1];
fem.appl.equ.Q = 'Q0';
fem.appl.equ.ind = [1];
fem=multiphysics(fem);
fem.xmesh=meshextend(fem);
CONVERTING M-FILES
120
fem.sol=femstatic(fem,'solcomp',{'T'},'outcomp',{'T'});
postplot(fem,'tridata',{'T'}, ...
'trimap','Rainbow','axis',[-0.9,0.9,-0.6,1.6]);
1 Start COMSOL 4.2 with MATLAB (3.5a Compatibility) using the shortcut icon from the
Windows start menu, or enter the following command at the terminal prompt:
comsol matlab -compat -c35aroot <COMSOL 3.5a root directory>
If you want to save the mesh, solver, and postprocessing settings it is important to
define the variable fem as a FEMGUI object.
2 Edit the M-files and add the following line at the beginning of the script:
fem = femgui;
3 Save and run the model M-file at the MATLAB prompt. You can see the structure
[1x1 struct]
{'shlag(2,'T')'}
1
[1x1 struct]
[1x1 struct]
[1x1 struct]
{'Q0' '1e5'}
[1x1 rect2]
[1x1 femmesh]
'on'
'on'
[1x1 com.femlab.xmesh.Xmesh]
[1x1 femsol]
The resulting model object contains both the COMSOL 3.5a mesh object and
solution vector. Because fem is a FEMGUI object, the model also contains the mesh
and solver sequences defined in the M-file. To convert a FEM structure you can
follow the exact same procedure (just skip the second step in the above procedure).
You can get the mesh group information with the following command:
model.mesh.getList
ans =
121 |
[Type: Mesh
Tag: mesh1
Current child node: obj
Number of child nodes: 2, Type: Mesh
Tag: mesh2
Current child node: ftri1
Number of child nodes: 2]
The above information indicates that the mesh group mesh1 is a mesh object (the
3.5a mesh object), and the mesh group mesh2 corresponds to the sequence defined
with the FEMGUI object.
To get the solution list:
model.sol.getList
ans =
[Type: Solver
Tag: sol1, Type: Solver
Tag: sol2]
sol1 contains the solver sequence, and sol2 is the 3.5a solution.
The reason of having both the 3.5a mesh and solution object and the corresponding
sequence is to allow you to use the exact same model and solution as in version 3.5a
or to run a sequence set up in version 3.5a.
5 You can work with the model object at the MATLAB prompt or save the model
Saving the model as an M-file saves the geometry and the mesh object in the binary
files Converted_geom1.mphbin and Converted_mesh1_obj.mphbin. The model
M-file can be run directly.
To run the M-file using the mesh and the solver sequences, the following
modifications are required.
6 Edit the file ConvertedFEM.m, the file should be as the following:
function out = model
%
% Converted.m
%
% Model exported on May 28 2010, 11:05 by COMSOL 4.0.0.967.
import com.comsol.model.*
import com.comsol.model.util.*
CONVERTING M-FILES
122
model = ModelUtil.create('Model');
model.modelPath('Path');
model.param.set('Q0','1e5');
model.modelNode.create('mod1');
model.geom.create('geom1', 2);
model.geom('geom1').feature.create('CO1', 'Rectangle');
model.geom('geom1').feature('CO1').set('pos', '-0.8,0.0');
model.geom('geom1').feature('CO1').set('size', {'1.6' '1'});
model.geom('geom1').setGeom('Converted_geom1.mphbin');
model.physics.create('ht', 'HeatTransfer', 'geom1');
model.physics('ht').feature.create('hs1', 'HeatSource', 2);
model.physics('ht').feature('hs1').selection.set([1]);
model.physics('ht').feature.create('temp1', 'TemperatureBoundary', 1);
model.physics('ht').feature('temp1').selection.set([1 2]);
model.mesh.create('mesh1', 'geom1');
model.mesh('mesh1').feature.create('obj', 'MeshObject');
model.mesh.create('mesh2', 'geom1');
model.mesh('mesh2').feature.create('ftri1', 'FreeTri');
model.physics('ht').feature('solid1').set('k_mat', 'userdef');
model.physics('ht').feature('solid1').set('k', {'400'; '0'; '0'; '0'; '400';
'0'; '0'; '0'; '400'});
model.physics('ht').feature('solid1').set('rho_mat', 'userdef');
model.physics('ht').feature('solid1').set('rho', '8700');
model.physics('ht').feature('solid1').set('Cp_mat', 'userdef');
model.physics('ht').feature('solid1').set('Cp', '385');
model.physics('ht').feature('init1').set('T', '273.15');
model.physics('ht').feature('hs1').set('Q', 'Q0');
model.physics('ht').feature('temp1').set('T0', '273.15');
model.mesh('mesh1').feature('obj').set('filename',
'Converted_mesh1_obj.mphbin');
model.mesh('mesh1').run;
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').feature('size').set('hmin', '2.0E-4');
model.mesh('mesh2').feature('size').set('hcurve', '0.25');
model.mesh('mesh2').feature('size').set('hgrad', '1.25');
model.mesh('mesh2').feature('size').set('hauto', '3');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').run;
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.sol.create('sol1');
model.sol.create('sol2');
model.sol('sol1').feature.create('st1', 'StudyStep');
model.sol('sol1').feature.create('v1', 'Variables');
model.sol('sol1').feature.create('s1', 'Stationary');
123 |
model.sol('sol1').feature('s1').feature.create('fc1', 'FullyCoupled');
model.sol('sol1').feature('s1').feature.create('d1', 'Direct');
model.result.dataset('dset1').set('geom', 'geom1');
model.result.dataset('dset2').set('geom', 'geom1');
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.study('std1').feature('stat1').set('mesh', {'geom1' 'mesh1'});
model.sol('sol1').feature('st1').name('Compile Equations: Stationary 1');
model.sol('sol1').feature('st1').set('studystep', 'stat1');
model.sol('sol1').feature('v1').set('initsol', 'sol2');
model.sol('sol1').feature('v1').set('notsol', 'sol2');
model.sol('sol1').feature('s1').set('stol', '1e-006');
model.sol('sol1').feature('s1').feature('fc1').set('minstep', '0.0001');
model.sol('sol1').feature('s1').feature('d1').set('errorchk', 'off');
model.sol('sol2').name('COMSOL 3.5a Solution');
model.result('pg1').set('data', 'dset2');
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'none');
out = model;
7 The lines that correspond to the first mesh case (mesh1) must be removed. The first
mesh case corresponds to the imported mesh object. In the original M-file (see
above) the lines numbers are 30, 31, 45, and 46:
model.mesh.create('mesh1','geom1');
model.mesh('mesh1').feature.create('obj', 'MeshObject');
model.mesh('mesh1').feature('obj').set('filename',
'Converted_mesh1_obj.mphbin');
model.mesh('mesh1').run;
8 Delete the lines that use the 3.5a solution solver sequence. This is the second solver
sol2. In the original M-file (see above) the line numbers are 59, 75, 76, and 80:
model.sol.create('sol2');
model.result.dataset('dset2').set('geom','geom1');
model.sol('sol1').feature('v1').set('initsol','sol2');
model.sol('sol1').feature('v1').set('notsol','sol2');
model.sol('sol2').name('COMSOL 3.5a Solution');
9 Delete the line that creates the data set using the COMSOL 3.5a Solution (Line 67
10 Add the command to run the solver sequence after the definition of the solver
CONVERTING M-FILES
124
11 The first mesh case mesh1 has been removed from the model object definition. The
study node needs to be updated accordingly. Change from mesh1 to mesh2 on line
71(in the original M-file) as follows:
model.study('std1').feature('stat1').set('mesh',{'geom1'
'mesh2'});
12 The COMSOL 3.5a Solution data set has been removed from the model object
definition. The plot group needs to updated accordingly. Change dset2 to dset1
on line 82 (in the original M-file):
model.result('pg1').set('data','dset1');
125 |
model.physics('ht').feature('hs1').set('Q', 'Q0');
model.physics('ht').feature('temp1').set('T0', '273.15');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').feature('size').set('hmin', '2.0E-4');
model.mesh('mesh2').feature('size').set('hcurve', '0.25');
model.mesh('mesh2').feature('size').set('hgrad', '1.25');
model.mesh('mesh2').feature('size').set('hauto', '3');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').run;
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.sol.create('sol1');
model.sol('sol1').feature.create('st1', 'StudyStep');
model.sol('sol1').feature.create('v1', 'Variables');
model.sol('sol1').feature.create('s1', 'Stationary');
model.sol('sol1').feature('s1').feature.create('fc1', 'FullyCoupled');
model.sol('sol1').feature('s1').feature.create('d1', 'Direct');
model.result.dataset('dset1').set('geom', 'geom1');
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.study('std1').feature('stat1').set('mesh', {'geom1' 'mesh1'});
model.sol('sol1').feature('st1').name('Compile Equations: Stationary 1');
model.sol('sol1').feature('st1').set('studystep', 'stat1');
model.sol('sol1').feature('s1').set('stol', '1e-006');
model.sol('sol1').feature('s1').feature('fc1').set('minstep', '0.0001');
model.sol('sol1').feature('s1').feature('d1').set('errorchk', 'off');
model.sol('sol1').runAll;
model.result('pg1').set('data', 'dset1');
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'none');
out = model;
The new M-file is ready to run. This regenerates a new mesh case in COMSOL 4.2.
Note that the mesh can differ slightly from the one obtained in version 3.5a. This does
not affect the results as long as the solution is not mesh dependent.
CONVERTING M-FILES
126
COMSOL model. In this case it is recommended to convert the FEM structure to the
model object at each iteration.
The following example illustrates a multiple parameterization procedure. Both
geometry parameters and the inlet velocity boundary condition are parameterized.
% The line below is added for the 4.2 conversion procedure
fem=femgui;
j = 1;
for L = [1 2]
for Q0 = [1e5 1e6]
fem.geom=rect2(L,1,'base','corner','pos',[-0.8,0]);
fem.const={'Q0',Q0,'L',L};
fem.mesh=meshinit(fem,'hauto',3);
fem.appl.mode.class = 'HeatTransfer';
fem.appl.sshape = 2;
fem.appl.assignsuffix = '_ht';
fem.appl.bnd.type = {'q0','T'};
fem.appl.bnd.ind = [2,2,1,1];
fem.appl.equ.Q = 'Q0';
fem.appl.equ.ind = [1];
fem=multiphysics(fem);
fem.xmesh=meshextend(fem);
fem.sol=femstatic(fem,'solcomp',{'T'},'outcomp',{'T'});
postplot(fem, 'tridata',{'T'},...
'trimap','Rainbow','axis',[-0.9,0.9,-0.6,1.6]);
% The two lines below are added for the 4.2 conversion procedure
model = mphv4(fem);
model.save(['Y:\v4_models\ConvertedFEM_',num2str(j),'.mph']);
j=j+1;
end
end
127 |
4 Edit Converted_param.m and modify the file according to the procedure details in
directly. Modify the geometry node settings such that they include the parameter L
as the definition of the length of the rectangle:
model.geom('geom1').feature('CO1').set('size', {'L' '1'});
CONVERTING M-FILES
128
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.sol.create('sol1');
model.sol('sol1').feature.create('st1', 'StudyStep');
model.sol('sol1').feature.create('v1', 'Variables');
model.sol('sol1').feature.create('s1', 'Stationary');
model.sol('sol1').feature('s1').feature.create('fc1', 'FullyCoupled');
model.sol('sol1').feature('s1').feature.create('d1', 'Direct');
model.result.dataset('dset1').set('geom', 'geom1');
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.study('std1').feature('stat1').set('mesh', {'geom1' 'mesh2'});
model.sol('sol1').feature('st1').name('Compile Equations: Stationary 1');
model.sol('sol1').feature('st1').set('studystep', 'stat1');
model.sol('sol1').feature('s1').set('stol', '1e-006');
model.sol('sol1').feature('s1').feature('fc1').set('minstep', '0.0001');
model.sol('sol1').feature('s1').feature('d1').set('errorchk', 'off');
model.result('pg1').set('data', 'dset1');
model.result('pg1').set('title', 'Surface: Temperature [K]');
model.result('pg1').set('titleactive', true);
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'everywhere');
% Start of the FOR loops
j=1;
for L = [1 2]
for Q0 = [1e5 1e6]
model.param.set('Q0', 1e5);
model.param.set('L',1);
model.sol('sol1').runAll;
model.save(['PATH\Converted_param_',num2str(j),'.mph']);
j=j+1;
end
end
129 |
fem.const={'Q0','1e5'};
fem.mesh=meshinit(fem,'hauto',3);
fem.appl.mode.class = 'HeatTransfer';
fem.appl.sshape = 2;
fem.appl.assignsuffix = '_ht';
fem.appl.bnd.type = {'q0','T'};
fem.appl.bnd.ind = [2,2,1,1];
fem.appl.equ.Q = 'Q0';
fem.appl.equ.ind = [1];
fem=multiphysics(fem);
fem.xmesh=meshextend(fem);
fem.sol=femstatic(fem,'solcomp',{'T'},'outcomp',{'T'});
postplot(fem,'tridata',{'T'}, ...
'trimap','Rainbow','axis',[-0.9,0.9,-0.6,1.6]);
postplot(fem,'tridata','T','triz','T','trimap','Rainbow', ...
'contdata','flux_ht','contlevels',20,'contmap','Thermal');
postplot(fem,'arrowdata',{'fluxx_ht','fluxy_ht'}, ...
'arrowxspacing',15,'arrowyspacing',15, ...
'arrowtype','arrow', 'arrowcolor',[1.0,0.0,0.0]);
1 The first step consists of adding the command to overload the FEM structure during
M-file reading in order to get the FEMGUI object. Also add the command to
convert the FEMGUI object to a COMSOL 4.2 model object after each
postprocessing function and save each of the model objects on M-file format. The
M-file should be similar to the following:
fem=femgui;
fem.geom=rect2(1.6,1,'base','corner','pos',[-0.8,0]);
fem.const={'Q0','1e5'};
fem.mesh=meshinit(fem,'hauto',3);
fem.appl.mode.class = 'HeatTransfer';
fem.appl.sshape = 2;
fem.appl.assignsuffix = '_ht';
fem.appl.bnd.type = {'q0','T'};
fem.appl.bnd.ind = [2,2,1,1];
fem.appl.equ.Q = 'Q0';
fem.appl.equ.ind = [1];
fem=multiphysics(fem);
fem.xmesh=meshextend(fem);
fem.sol=femstatic(fem,'solcomp',{'T'},'outcomp',{'T'});
CONVERTING M-FILES
130
postplot(fem,'tridata',{'T'}, ...
'trimap','Rainbow','axis',[-0.9,0.9,-0.6,1.6]);
model=mphv4(fem);
model.save('PATH\plot_1','m')
postplot(fem,'tridata','T','triz','T','trimap','Rainbow', ...
'contdata','flux_ht','contlevels',20,'contmap','Thermal');
model=mphv4(fem);
model.save('PATH\plot_2','m')
postplot(fem,'arrowdata',{'fluxx_ht','fluxy_ht'}, ...
'arrowxspacing',15,'arrowyspacing',15, ...
'arrowtype','arrow', 'arrowcolor',[1.0,0.0,0.0]);
model=mphv4(fem);
model.save('PATH\plot_3','m')
2 You can now open plot_1.m and modify it according to the first example model.
131 |
model.physics('ht').feature('solid1').set('k_mat', 'userdef');
model.physics('ht').feature('solid1').set('k', {'400'; '0'; '0'; '0'; '400';
'0'; '0'; '0'; '400'});
model.physics('ht').feature('solid1').set('rho_mat', 'userdef');
model.physics('ht').feature('solid1').set('rho', '8700');
model.physics('ht').feature('solid1').set('Cp_mat', 'userdef');
model.physics('ht').feature('solid1').set('Cp', '385');
model.physics('ht').feature('init1').set('T', '273.15');
model.physics('ht').feature('hs1').set('Q', 'Q0');
model.physics('ht').feature('temp1').set('T0', '273.15');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').feature('size').set('hmin', '2.0E-4');
model.mesh('mesh2').feature('size').set('hcurve', '0.25');
model.mesh('mesh2').feature('size').set('hgrad', '1.25');
model.mesh('mesh2').feature('size').set('hauto', '3');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').run;
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.sol.create('sol1');
model.sol('sol1').feature.create('st1', 'StudyStep');
model.sol('sol1').feature.create('v1', 'Variables');
model.sol('sol1').feature.create('s1', 'Stationary');
model.sol('sol1').feature('s1').feature.create('fc1', 'FullyCoupled');
model.sol('sol1').feature('s1').feature.create('d1', 'Direct');
model.result.dataset('dset1').set('geom', 'geom1');
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.study('std1').feature('stat1').set('mesh', {'geom1' 'mesh1'});
model.sol('sol1').feature('st1').name('Compile Equations: Stationary 1');
model.sol('sol1').feature('st1').set('studystep', 'stat1');
model.sol('sol1').feature('s1').set('stol', '1e-006');
model.sol('sol1').feature('s1').feature('fc1').set('minstep', '0.0001');
model.sol('sol1').feature('s1').feature('d1').set('errorchk', 'off');
model.sol('sol1').runAll;
model.result('pg1').set('data', 'dset1');
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'none');
out = model;
group, open Plot_2.m and search for and copy the following lines:
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.result('pg1').feature('surf1').feature.create('hght1', 'Height');
CONVERTING M-FILES
132
model.result('pg1').feature.create('con1', 'Contour');
4 Paste the above lines in the file Plot_1.m before the line out = model;
5 In the added line replace the plot group name pg1 to pg2.
6 Do the same for the plot group defined in Plot_3.m with the following lines:
model.result.create('pg1', 2);
model.result('pg1').feature.create('arws1', 'ArrowSurfac');
133 |
model.physics('ht').feature('hs1').selection.set([1]);
model.physics('ht').feature.create('temp1', 'TemperatureBoundary', 1);
model.physics('ht').feature('temp1').selection.set([1 2]);
model.mesh.create('mesh2', 'geom1');
model.mesh('mesh2').feature.create('ftri1', 'FreeTri');
model.physics('ht').feature('solid1').set('k_mat', 'userdef');
model.physics('ht').feature('solid1').set('k', {'400'; '0'; '0'; '0'; '400';
'0'; '0'; '0'; '400'});
model.physics('ht').feature('solid1').set('rho_mat', 'userdef');
model.physics('ht').feature('solid1').set('rho', '8700');
model.physics('ht').feature('solid1').set('Cp_mat', 'userdef');
model.physics('ht').feature('solid1').set('Cp', '385');
model.physics('ht').feature('init1').set('T', '273.15');
model.physics('ht').feature('hs1').set('Q', 'Q0');
model.physics('ht').feature('temp1').set('T0', '273.15');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').feature('size').set('hmin', '2.0E-4');
model.mesh('mesh2').feature('size').set('hcurve', '0.25');
model.mesh('mesh2').feature('size').set('hgrad', '1.25');
model.mesh('mesh2').feature('size').set('hauto', '3');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').run;
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.sol.create('sol1');
model.sol('sol1').feature.create('st1', 'StudyStep');
model.sol('sol1').feature.create('v1', 'Variables');
model.sol('sol1').feature.create('s1', 'Stationary');
model.sol('sol1').feature('s1').feature.create('fc1', 'FullyCoupled');
model.sol('sol1').feature('s1').feature.create('d1', 'Direct');
model.result.dataset('dset1').set('geom', 'geom1');
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.study('std1').feature('stat1').set('mesh', {'geom1' 'mesh1'});
model.sol('sol1').feature('st1').name('Compile Equations: Stationary 1');
model.sol('sol1').feature('st1').set('studystep', 'stat1');
model.sol('sol1').feature('s1').set('stol', '1e-006');
model.sol('sol1').feature('s1').feature('fc1').set('minstep', '0.0001');
model.sol('sol1').feature('s1').feature('d1').set('errorchk', 'off');
model.sol('sol1').runAll;
model.result('pg1').set('data', 'dset1');
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'none');
model.result.create('pg2', 2);
model.result('pg2').feature.create('surf1', 'Surface');
CONVERTING M-FILES
134
model.result('pg2').feature('surf1').feature.create('hght1', 'Height');
model.result('pg2').feature.create('con1', 'Contour');
model.result('pg2').set('data', 'dset2');
model.result('pg2').feature('surf1').set('descr', 'T');
model.result('pg2').feature('surf1').set('smooth', 'none');
model.result('pg2').feature('con1').set('expr', 'flux_ht');
model.result('pg2').feature('con1').set('unit', '');
model.result('pg2').feature('con1').set('descr', 'flux_ht');
model.result('pg2').feature('con1').set('colortable', 'Thermal');
model.result('pg2').feature('con1').set('smooth', 'none');
model.result.create('pg3', 2);
model.result('pg3').feature.create('arws1', 'ArrowSurfac');
model.result('pg3').set('data', 'dset2');
model.result('pg3').feature('arws1').set('expr', {'fluxx_ht' 'fluxy_ht'});
model.result('pg3').feature('arws1').set('color', 'custom');
model.result('pg3').feature('arws1').set('customcolor', {'0.99 '0' '0'});
out = model;
The resulting model object does not include the proper parameter value list for
continuation parameter. To set the parameter list value enter
model.study('std1').feature('stat1').set('plist',
'range(0,0.01,1)');
and
135 |
model.sol('sol1').feature('s1').feature('p1').set('plist',
'range(0,0.01,1)');
COMSOL 4.2
posteval
mpheval
geomplot
mphgeom
postglobal
mphglobal
postint
mphint
postinterp
mphinterp
assemble
mphmatrix
meshplot
mphmesh
femstate
mphstate
CONVERTING M-FILES
136
137 |
Command Reference
The main reference for the syntax of the commands available with LiveLink for
MATLAB is the COMSOL Java API Reference Guide. This section documents
additional interface functions that come with the product.
138
Summary of Commands
mphcd
mphdoc
mpheval
mphgeom
mphgetadj
mphgetcoords
mphgetp
mphgetproperties
mphgetu
mphglobal
mphint
mphinterp
mphload
mphmatrix
mphmesh
mphmeshstats
mphmodel
mphnavigator
mphplot
mphsave
mphselectbox
mphselectcoords
mphstart
mphstate
mphversion
mphviewselection
mphv4
mphxmeshinfo
139 |
C o m m a nds G r ou p ed b y Fu n c t i on
Interface Functions
FUNCTION
PURPOSE
mphdoc
mphload
mphsave
mphcd
mphstart
mphversion
Geometry Functions
FUNCTION
PURPOSE
mphgeom
mphviewselection
Mesh Functions
FUNCTION
PURPOSE
mphmesh
mphmeshstats
Utility Functions
FUNCTION
PURPOSE
mphgetadj
mphgetcoords
mphgetp
mphgetu
mphxmeshinfo
mphmatrix
mphstate
140
FUNCTION
PURPOSE
mphselectbox
mphselectcoords
Postprocessing Functions
FUNCTION
PURPOSE
mpheval
mphglobal
mphint
mphinterp
mphplot
PURPOSE
mphnavigator
mphmodel
Return tags for the nodes and subnodes in the COMSOL model
object.
mphmodel
141 |
FUNCTION
PURPOSE
mphv4
mphcd
Change directory to the directory of the model
Purpose
mphcd
Syntax
mphcd(model)
Description
mphload, mphsave
142
mphdoc
Return HTML help of a specified function.
Purpose
mphdoc
Syntax
mphdoc arg1
mpdoc arg1 arg2
Description
mphdoc arg1 returns the HTML documentation associated to the function arg1.
mphdoc arg1 arg2 returns the HTML documentation associated to the function
arg1.('arg2').
mphdoc arg1 arg2 -web returns the HTML documentation associated to the
function arg1.('arg2') in the default web browser.
Example
143 |
mpheval
Evaluate expressions on node points.
Purpose
mpheval
Syntax
pd = mpheval(model,{e1,e2,...,en},...)
Description
expressions e1,e2,...,en.
The value pd is post data, a structure with fields p, t, ve, and fields for data values.
The field p contains node point coordinate information. The number of rows in p
is the number of space dimensions. The field t contains the indices to columns in p
of a simplex mesh, each column in t representing a simplex. The field ve contains
indices to mesh elements for each node point. For each expression e1,e2,...,en
a field with the name d1,d2,... dn is added with the numerical values. The
columns in the data value fields correspond to node point coordinates in columns
in p. The field expr contains the expression name evaluated. The field unit contains
the list of the unit for each expression. The data contains the real part of
complex-valued expressions.
The function mpheval accepts the following property/value pairs:
TABLE 9-1: PROPERTY/VALUE PAIRS FOR THE MPHEVAL COMMAND.
PROPERTY
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Complexfun
off | on
on
Complexout
off | on
off
Dataset
String
Edim
0 | 1 | 2 |
3
Geometry
space
dimension
Matherr
off | on
off
Outersolnum
Positive
integer
Pattern
lagrange |
gauss
lagrange
Phase
Scalar
Recover
off | ppr |
pprint
off
Refine
Integer
144
mpheval
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Selection
Integer
vector
All
domains
Smooth
internal |
none |
everywhere
internal
Smoothing setting
Solnum
Integer
vector |
all | end
all
Double
array
The property Dataset controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets.
The property Edim decides which elements to evaluate on. Evaluation takes place
only on elements with space dimension Edim. If not specified, Edim=sdim is used,
where sdim is the space dimension of the geometry. For example, in a 3D model, if
evaluation is done on edges (1D elements), Edim is 1. Similarly, for boundary
evaluation (2D elements), Edim is 2, and for domain evaluation (3D elements),
Edim is 3 (default in 3D).
Use Recover to recover fields using polynomial-preserving recovery. This
techniques recover fields with derivatives such as stresses or fluxes with a higher
theoretical convergence than smoothing. Recovery is expensive so it is turned off by
default. The value pprint means that recovery is performed inside domains. The
value ppr means that recovery is also applied on all domain boundaries.
The property Refine constructs evaluation points by making a regular refinements
of each element. Each mesh edge is divided into Refine equal parts.
The property Smooth controls if the post data is forced to be continuous on element
edges. When Smooth is set to internal, only elements not on interior boundaries are
made continuous.
The property Solnum is used to select the solution to plot when a parametric,
eigenvalue or time dependent solver has been used to solve the problem.
The property Outersolnum is used to select the solution to plot when a parametric
sweep has been used in the study.
145 |
mpheval
When the property Phase is used, the solution vector is multiplied with
exp(i*phase) before evaluating the expression.
The expressions e1,e2,...,en are evaluated for one or several solutions. Each
solution generates an additional row in the data fields of the post data output
structure. The property Solnum and t control which solutions are used for the
evaluations. The Solnum property is available when the data set has multiple
solutions, for example in the case of parametric, eigenfrequency, or time-dependent
solutions. The t property is available only for time-dependent problems. If Solnum
is provided, the solutions indicated by the indices provided with the Solnum
property are used. If t is provided solutions are interpolated. If neither Solnum nor
t is provided, all solutions are evaluated.
For time-dependent problems, the variable t can be used in the expressions ei. The
value of t is the interpolation time when the property t is provided, and the time
for the solution, when Solnum is used. Similarly, lambda and the parameter are
available as eigenvalues for eigenvalue problems and as parameter values for
parametric problems, respectively.
Example
146
mphgeom
Plot a geometry in a MATLAB figure.
Purpose
mphgeom
Syntax
mphgeom(model,geomname)
mphgeom(model,geomname,...)
Description
Example
PROPERTY
VALUE
Parent
Double
DEFAULT
Parent axes
Selection
Double
Selection
Entity
point |
edge |
boundary |
domain
Geometric entity to
select
Build
on | off |
current
on
Edgecolor
Char
Edge color
Edgelabels
on | off
off
Edgelabelscolor
Char
Edgemode
on | off
on
Show edges
Facealpha
Double
Use transparency
Facelabels
on | off
off
Facelabelscolor
Char
Facemode
on | off
on
Show faces
Vertexlabels
on | off
off
Vertexlabelscolor
Char
Vertexmode
on | off
off
Show vertices
147 |
DESCRIPTION
mphgeom
mphgeom(model,'geom1')
148
mphgetadj
Return geometry entity indices that are adjacent to other.
Purpose
mphgetadj
Syntax
n = mphgetadj(model,geomname,returntype,adjtype,adjnumber)
Description
n = mphgetadj(model,geomname,returntype,adjtype,adjnumber) returns
Example
'point': 0
149 |
mphgetcoords
Return point coordinates of geometry entities.
Purpose
mphgetcoords
Syntax
c = mphgetcoords(model,geomane,entitytype,entitynumbers)
Description
coordinates of the points that belong to the entity object with the type entitytype
and the index entitynumber.
The entitytype property can be one of 'point', 'edge', 'boundary' or
'domain' following the entity space dimension defined below:
150
mphgetp
Obtain information about a solution.
Purpose
mphgetp
Syntax
[sz,ndofs,data,name,type] = mphgetp(model)
[sz,ndofs,data,name,type] = mphgetp(model,'solname',sol)
Description
contains the number of degrees of freedom. data contains the values of the
parameters, for a parametric solution, the output times for a transient solution or
eigenvalues for an eigenvalue solution. name contains the name of the parameters,
time or eigenvalue variable. type contains a string with the type of the solver, which
can be either Stationary, Time, or Eigenvalue.
TABLE 9-3: PROPERTY/VALUE PAIRS FOR THE MPHGETP COMMAND
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Solname
String
Studysteptag
String
st1
The study step tag must be the tag of a node of type StudyStep (Compile
Equations) or Variables.
The Solname property set the solution data set to use associated with the defined
solver node.
Example
Get the size and degrees of freedom for the variables for sol1:
[sz,ndofs]=mphgetp(model,'solname','sol1','studysteptag','v1')
Get the solution information for the second solution data set:
[sz,ndofs,list,name,type]=mphgetp(model,'solname','sol2')
See also
151 |
mphgetu
mphgetproperties
Extract properties from a model node
Purpose
mphgetproperties
Syntax
mphproperties(node)
Description
mphproperties(node) returns properties that are defined for the node node.
Example
mphnavigator
152
mphgetu
Return solution vector.
Purpose
mphgetu
Syntax
U = mphgetu(model,...)
[U,Udot] = mphgetu(model,...)
Description
U = mphgetu(model) returns the solution vector U for the default solution data set.
[U,Udot] = mphgetu(model,...) returns in addition Udot, which is the time
VALUE
DEFAULT
DESCRIPTION
Solname
String
Auto
Solnum
Positive integer
vector
Auto
The Solname property set the solution data set to use associated with the defined
solver node.
Example
Get the solution vector for the last time step (default solution number):
u = mphgetu(model);
Get the solution vector and its derivative for solution number 4:
[u,ut] = mphgetu(model,'solnum',4);
See also
153 |
mphgetp
mphglobal
Evaluate global quantities.
Purpose
mphglobal
Syntax
[d1,d2,...,dn] = mphglobal(model,{e1,e2,...,en},...)
Description
evaluating the global quantities specified in the string expression e1, e2,..., en.
[d1,d2,...,dn,unit] = mphglobal(model,{e1,e2,...,en},...) returns the
results from evaluating the global quantities specified in the string expression e1,
e2, ..., en. unit is a nx1 cell array that contains the unit of the different
expressions evaluated.
Valid property/value pairs include:
TABLE 9-5: PROPERTY/VALUE PAIRS FOR THE MPHGLOBAL COMMAND.
PROPERTY
PROPERTY VALUE
DEFAULT
DESCRIPTION
Complexfun
off | on
on
Use complex-valued
functions with real input
Complexout
off | on
off
Dataset
String
Active solution
data set
Matherr
off | on
off
Outersolnum
Positive
integer
Phase
Scalar
Solnum
Integer vector
| all | end
all
Double array
Unit
String | cell
array
The property Data controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on solution data sets.
When the property Phase is used, the solution vector is multiplied with
exp(i*phase) before evaluating the expression.
The expressions ei are evaluated for one or several solutions. Each solution
generates an additional row in the output data array di. The property Solnum and
t control which solutions are used for the evaluations. The Solnum property is
154
mphglobal
available when the data set has multiple solutions, for example in the case of
parametric, eigenfrequency, or time-dependent solutions. The t property is
available only for time-dependent problems. If Solnum is provided, the solutions
indicated by the indices provided with the Solnum property are used. If t is provided
solutions are interpolated. If neither Solnum nor t is provided, all solutions are
evaluated.
For time-dependent problems, the variable t can be used in the expressions ei. The
value of t is the interpolation time when the property t is provided, and the time
for the solution, when Solnum is used. Similarly, lambda and the parameter are
available as eigenvalues for eigenvalue problems and as parameter values for
parametric problems, respectively.
In case of multiple expression if the unit property is defined with a string, the same
unit is used for both expressions. To use different units, set the property with a cell
array. In case of inconsistent unit definition, the default unit is used instead.
Solnum is used to select the solution number when a parametric, eigenvalue or
time-dependent solver has been used.
Outersolnum is used to select the outer solution number when a parametric sweep
Evaluate the expressions u_up and u_down at the last solution number:
[u_up,u_down] =
mphglobal(model,{'u_up','u_down'},'solnum','end')
155 |
mphint
Perform integration of expressions.
Purpose
mphint
Syntax
val = mphint(model,{e1,e2,...,en},...)
Description
expressions e1,e2,...,en and returns the result in the matrix val with N rows and
M columns. M is the length of the vector Solnum.
[val,unit] = mphint(model,{e1,e2,...,en},...) in addition return the
PROPERTY VALUE
DEFAULT
DESCRIPTION
Dataset
String
active
solution
data set
Edim
1 | 2 | 3
geometry
space
dimension
Element dimension
Intorder
Positive integer
Integration order
Intsurface
on | off
off
Intvolume
on | off
off
Matherr
off | on
off
Method
auto |
integration |
summation
auto
Integration method
Outersolnum
Positive integer
Selection
Integer vector |
all
all
Domain list
Solnum
Integer vector |
end | all
all
Double array
unit
String | cell
array
The property Dataset controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets.
156
mphint
The property Edim decides which elements to evaluate on. Evaluation takes place
only on elements with space dimension Edim. If not specified, Edim=sdim is used,
where sdim is the space dimension of the geometry. For example, in a 3D model, if
evaluation is done on edges (1D elements), Edim is 1. Similarly, for boundary
evaluation (2D elements), Edim is 2, and for domain evaluation (3D elements),
Edim is 3 (default in 3D).
The expressions e1,e2,...,en are integrated for one or several solutions. Each
solution generates an additional column in the returned matrix. The property
Solnum and t control which solutions are used for the integrations. The Solnum
property is available when the data set has multiple solutions, for example in the case
of parametric, eigenfrequency, or time-dependent solutions. The t property is
available only for time-dependent problems. If Solnum is provided, the solutions
indicated by the indices provided with the Solnum property are used. If t is provided
solutions are interpolated. If neither Solnum nor t is provided, all solutions are
evaluated.
For time-dependent problems, the variable t can be used in the expressions ei. The
value of t is the interpolation time when the property t is provided, and the time
for the solution, when Solnum is used. Similarly, lambda and the parameter are
available as eigenvalues for eigenvalue problems and as parameter values for
parametric problems, respectively.
The unit property defines the unit of the integral, if a inconsistent unit is entered,
the default unit is used. In case of multiple expression, if the unit property is
defined with a string, the same unit is used for both expressions. To use different
units, set the property with a cell array. In case of inconsistent unit definition, the
default unit is used instead.
Solnum is used to select the solution number when a parametric, eigenvalue or
time-dependent solver has been used.
Outersolnum is used to select the outer solution number when a parametric sweep
Integrate the x-velocity u at the outlet boundary and get its unit:
[flow unit]= mphint(model,'u','edim',2,'selection',136)
157 |
mphint
flow =
mphint(model,'u','edim',2,'selection',136,'unit','mm^3/s')
Integrate the normal heat flux along the external boundaries using surface
integration:
Q = mphint(model,'ht.ndflux','intsurface','on','edim',1,...
'selection',[2,3,4]);
Integrate both normal heat flux and the temperature and set the unit to use ([MW]
and [m^2*degC] respectively):
[Int unit]=
mphint(model,{'ht.ndflux','T'},'intsurface','on','edim',1,...
'selection',[2,3,4],'unit',{'MW','m^2*degC'});
158
mphinterp
Evaluate expressions in arbitrary points or data sets.
Purpose
mphinterp
Syntax
[v1,v2,...,vn] = mphinterp(model,{e1,e2,...,en},'coord',coord,...)
[v1,v2,...,vn] =
mphinterp(model,{e1,e2,...,en},'dataset',dset,...)
Description
[v1,v2,...,vn] = mphinterp(model,{e1,e2,...,en},coord,coord,...)
evaluates expressions e1,e2,...en on the specified data set. In this case the data
set needs to be of a type that defines an interpolation in itself, such as cut planes,
revolve, and so forth.
[v1,v2,...,vn,unit] = mphinterp(model,{e1,e2,...,en},...) returns in
159 |
mphinterp
The following property/value pairs are available:
TABLE 9-7: PROPERTY/VALUE PAIRS FOR THE MPHEVAL COMMAND.
PROPERTY
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Complexfun
off | on
on
Complexout
off | on
off
Coord
Double
array
Dataset
String
Auto
Edim
0 | 1 | 2 |
3
geometry
space
dimension
Element dimension
Matherr
off | on
off
Outersolnum
Positive
integer
Phase
Scalar
Recover
off | ppr |
pprint
off
Selection
Integer
vector |
all
all
Domain number
Solnum
Integer
vector |
all | end
all
Double
array
Unit
String |
Cell array
The property Data controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets. The active solution data set is used by default.
The property Edim decides which elements to evaluate on. Evaluation takes place
only on elements with space dimension Edim. If not specified, Edim=sdim is used,
where sdim is the space dimension of the geometry. For example, in a 3D model, if
evaluation is done on edges (1D elements), Edim is 1. Similarly, for boundary
evaluation (2D elements), Edim is 2, and for domain evaluation (3D elements),
Edim is 3 (default in 3D).
160
mphinterp
Use Recover to recover fields using polynomial-preserving recovery. This
techniques recover fields with derivatives such as stresses or fluxes with a higher
theoretical convergence than smoothing. Recovery is expensive so it is turned off by
default. The value pprint means that recovery is performed inside domains. The
value ppr means that recovery is also applied on all domain boundaries.
The property Refine constructs evaluation points by making a regular refinements
of each element. Each mesh edge is divided into Refine equal parts.
The property Smooth controls if the post data is forced to be continuous on element
edges. When Smooth is set to internal, only elements not on interior boundaries are
made continuous.
When the property Phase is used, the solution vector is multiplied with
exp(i*phase) before evaluating the expression.
The expressions e1,e2,...,en are evaluated for one or several solutions. Each
solution generates an additional row in the data fields of the post data output
structure. The property Solnum and t control which solutions are used for the
evaluations. The Solnum property is available when the data set has multiple
solutions, for example, in the case of parametric, eigenfrequency, or time-dependent
solutions. The t property is available only for time-dependent problems. If Solnum
is provided, the solutions indicated by the indices provided with the Solnum
property are used. If t is provided solutions are interpolated. If neither Solnum nor
t is provided, all solutions are evaluated.
For time-dependent problems, the variable t can be used in the expressions ei. The
value of t is the interpolation time when the property t is provided, and the time
for the solution, when Solnum is used. Similarly, lambda and the parameter are
available as eigenvalues for eigenvalue problems and as parameter values for
parametric problems, respectively.
In case of multiple expression, if the unit property is defined with a string, the same
unit is used for both expressions. To use different units, set the property with a cell
array. In case of inconsistent unit definition, the default unit is used instead.
Solnum is used to select the solution number when a parametric, eigenvalue or
time-dependent solver has been used.
Outersolnum is used to select the outer solution number when a parametric sweep
161 |
mphinterp
model = mphload('heat_convection_2d.mph');
Evaluate the variation of the pressure at different times and get the unit:
[p,t, unit]= mphinterp(model,{'p','t'},'coord',[2; 0.2],...
't',[0:0.01:0.5 0.3:0.1:1]);
Evaluate the pressure and the time with the unit [mPa] and [min] respectively:
[p,t] = mphinterp(model,{'p','t'},'coord',[2; 0.2],...
't',1,'unit',{'mPa','min'});
Evaluate the von Mises effective stress at the cut point data set cpt1:
[mises,n]= mphinterp(model,{'solid.mises','n'},...
'datset','cpt1');
See also
162
mphload
Load a COMSOL model MPH-file.
Purpose
mphload
Syntax
model =
model =
model =
[model,
Description
model = mphload(File) loads a COMSOL model object and assigns the default
mphload(File)
mphload(File, ModelObjectName)
mphload(File, ModelObjectName, '-history')
filename] = mphload(File, ModelObjectName)
recording.
[model, filename] = mphload(File, ModelObjectName) also returns the full
Load the model in the file effective_diffusivity.mph from the Model Library
and return the file name:
[model, filename] = mphload('effective_diffusivity.mph');
163 |
mphmatrix
Get model matrices.
Purpose
mphmatrix
Syntax
str = mphmatrix(model,solname,'Out',...)
Description
EXPRESSION
DEFAULT
DESCRIPTION
out
Cell array of
strings
Initmethod
| init | sol
Initsol
solname | zero
solname
Solnum
Number | auto
auto
Solution number
EXPRESSION
DESCRIPTION
out
Stiffness matrix
Load vector
Constraint vector
Constraint Jacobian
Damping matrix
Mass matrix
NF
NP
MP
MLB
MUB
Kc
164
mphmatrix
EXPRESSION
DESCRIPTION
Lc
Dc
Ec
Null
Nullf
ud
Particular solution ud
uscale
Scale vector
Compare the sparsity of both system matrices (non-eliminated (b) and eliminated
one (r)):
hold on
165 |
mphmatrix
spy(str.Kc,'r')
Extract the stiffness matrix and the load vector evaluated for the initial solution:
str = mphmatrix(model,'sol1','out',{'Kc' 'Lc'},...
'initmethod','init');
166
mphmesh
Plot a mesh in a MATLAB figure window.
Purpose
mphmesh
Syntax
mphmesh(model,meshname)
mphmesh(model,meshname,...)
Description
window.
mphmesh(model,meshname,...) plots the mesh meshname in a MATLAB figure
window with the specified properties.
Example
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Parent
Double
Edgecolor
Char
Edge color
Edgelabels
on | off
off
Edgelabelscolor
Char
Edgemode
on | off
on
Show edges
Facealpha
Double
Use transparency
Facelabels
on | off
off
Facelabelscolor
Char
Facemode
on | off
on
Show faces
Meshcolor
Char
flat
Vertexlabels
on | off
off
Vertexlabelscolor
Char
Vertexmode
on | off
off
Show vertices
Parent axis
Plot the mesh with a colored element and transparency set to 0.5:
mphmesh(model, 'mesh1', ...
'edgecolor', 'b', ...
'facealpha',0.5,...
'meshcolor','r');
167 |
mphmeshstats
Return mesh statistics and mesh information
Purpose
mphmeshstats
Syntax
Description
DESCRIPTION
isactive
hasproblems
iscomplete
sdim
Space dimension
types
numelem
minquality
Minimum quality
meanquality
Mean quality
qualitydistr
minvolume
maxvolume
volume
Example
FIELD
DESCRIPTOIN
vertex
elem
elementity
Load the busbar model and show the mesh distribution in a figure:
model = mphload('busbar');
stats = mphmeshstats(model);
168
mphmeshstats
bar(linspace(0,1,20), stats.qualitydistr)
Note that the edge type is the first type in the list
numedgeelem = stats.numelem(1)
See also
169 |
mphmesh
mphmodel
Return tags for the nodes and subnodes in the COMSOL model object
Purpose
mphmodel
Syntax
mphmodel(model)
Description
mphmodel(model) returns the tags for the nodes and subnodes of the object model.
str = mphmodel(model,-struct) returns the tags for the nodes and subnodes
of the object model as a MATLAB structure str.
The mphmodel function can be used when navigating the model object and
learning about its structure. The mphmodel function is mainly designed for usage
when working on the command line and one needs to learn what nodes are placed
under a particular node.
Example
Load the transport and adsorption model from the model library:
model = mphload('transport_and_adsorption')
mphnavigator
170
mphnavigator
Graphical User Interface for viewing the COMSOL model object
Purpose
mphnavigator
Syntax
mphnavigator
Description
The mphnavigator command open a graphical user interface that can be used to
navigate the model object and to view the properties and methods of the nodes in
the model tree.
The GUI requires that the COMSOL objest is stored in a variable in the base
workspace (at the MATLAB command prompt) with the name model. No other
variable name is supported at this time.
See also
171 |
mphmodel, mphgetproperties
mphplot
Purpose
mphplot
Render a plot group in a figure window.
Syntax
mphplot(model,pg)
mphplot(model,pg,'server',on)
mphplot(model,pg,'rangenum',num)
Description
mphplot(model,pg) renders the plot group tagged pg from the model object
model in a figure window in MATLAB.
mphplot(model,pg,'server','on') renders the plot group tagged pg from
model in a figure window using the COMSOL server.
mphplot(model,pg,'rangenum',num) renders the plot group tagged pg from
model in a figure window in MATLAB with the color range bar (or legend bar) that
corresponds to the feature number num in the list of the plot group.
Note that only one color range bar and one legend bar is supported in a MATLAB
figure. When the option plot on server is active, all color range bars are displayed.
The following options are available:
TABLE 9-12: PROPERTY/VALUE PAIRS FOR THE MPHPLOT COMMAND
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Rangenum
Positive
Integer
none
Server
on | off
off
Plot on server
Parent
Double
Note: The plot on server option requires that you start COMSOL with MATLAB
in graphics mode.
Example
Plot the first plot group with the color range bar:
mphplot(model,'pg1','rangenum',1)
172
mphplot
Load rock_fracture_flow.mph from the Model Library:
model = mphload('rock_fracture_flow.mph');
Plot the second plot group with the color range bar:
mphplot(model,'pg2','rangenum',1)
Load fluid_valve.mph and plot on server (requires that you start COMSOL with
MATLAB in graphics mode):
model = mphload('fluid_valve.mph');
173 |
mphsave
Save a COMSOL model
Purpose
mphsave
Syntax
mphsave(model)
mphsave(model, filename)
Description
mphload
174
mphselectbox
Select geometric entity using a rubberband/box.
Purpose
mphselectbox
Syntax
n = mphselectbox(model,geomname,boxcoord,entity,...)
Description
indices of the geometry entities that are inside a selection domain (rectangle or box).
This method looks only on the vertex coordinates and does not observe all points
on curves and surfaces.
boxcoord set the coordinates of the selection domain, specified as a Nx2 array,
VALUE
DEFAULT
DESCRIPTION
Adjnumber
Scalar
none
When a model uses form an assembly more than one vertex may have the same
coordinate if the coordinate is shared by separate geometric objects. In that case one
can use the adjnumber property in order to identify the domain that the vertices
should be adjacent to.
Example
Find boundaries inside the selection box that are adjacent to domain number 1:
n = mphselectbox(model,'geom1',...
[0,0.05;0,-0.05;-0.05,0.05],'boundary','adjnumber',1);
175 |
mphselectbox
Load effective_diffusivity.mph from the Model Library:
model = mphload('effective_diffusivity.mph');
Find the boundaries that are inside the selection rectangle defined by
[3e-4,4e-4;4.5e-4,5.5e-4]:
n = mphselectbox(model,'geom1',...
[3e-4,4e-4;4.5e-4,5.5e-4],'boundary');
Find the boundaries that are inside the same selection rectangle:
n = mphselectbox(model,'geom1',...
[3e-4,4e-4;4.5e-4,5.5e-4],'point');
See also
176
mphselectcoords
Select geometric entity using point coordinates
Purpose
mphselectcoords
Syntax
n = mphselectcoords(model,geomname,coord,entity,...)
Description
VALUE
DEFAULT
DESCRIPTION
Adjnumber
Scalar
none
Radius
Scalar
auto
Search radius
Include
All | any
all
When a model uses form an assembly more than one vertex may have the same
coordinate if the coordinate is shared by separate geometric objects. In that case one
can use the adjnumber property in order to identify the domain that the vertices
should be adjacent to.
The radius property is used to specify the radius of the sphere/circle that the
search should be within. A small positive radius (based on the geometry size) is used
by default in order to compensate for rounding errors.
If the include property is 'all' then all vertices must belong to the entity in to be
considered a match. If the Include property is 'any' then an entity is considered
a match as long as any of the vertices are adjacent to the entity.
Examplee
177 |
mphselectcoords
model = mphload('busbar.mph');
Select boundaries that are adjacent to the points [0.09,0,0.1] and [0.09,0,0.015]
with a search radius of 0.01:
n = mphselectcoords(model,'geom1',...
[0.09,0,0.1;0.09,0,0]','boundary',... 'radius',0.01);
See also
178
mphstart
Connect MATLAB to a COMSOL server.
Purpose
mphstart
Syntax
mphstart
mphstart(port)
mphstart(ipaddress, port)
mphstart(ipaddress, port, comsolpath)
Description
mphstart creates a connection with a COMSOL server using the default port
started without using the COMSOL with MATLAB option. mphstart then sets up
the necessary environment and connect to COMSOL.
Prior to calling mphstart it is necessary to set the path of mphstart.m in the
MATLAB path or to change the current directory in MATLAB (e.g. using the cd
command) to the location of the mphstart.m file.
A COMSOL server must be started prior to running mphstart.
179 |
mphstate
Get state-space matrices for dynamic system.
Purpose
mphstate
Syntax
str = mphstate(model,solname,'Out',{'SP'})
str = mphstate(model,solname,'Out',{'SP1','SP2',...})
Description
VALUE
Out
Mc | MA | MB| C
| D | Null | ud
| x0
DEFAULT
DESCRIPTION
Keepfeature
off | on
Input
String
Output
String
Sparse
off | on
Initmethod
init | sol
Initsol
solname | zero
solname
Solnmum
auto
auto
Solution number
Output variables
off
off
Sparse matrices
Use linearization point
The property Sparse controls whether the matrices A, B, C, D, M, MA, MB, and Null
are stored in the sparse format. See femsim for a description of the other properties.
The equations correspond to the system below:
Mcx = McAx + McBu
y = Cx + Du
where x are the state variables, u are the input variables, and y are the output
variables.
180
mphstate
A static linearized model of the system can be described by:
y = D C McA 1 McB u
181 |
mphstate
str = mphstate(model,'sol1','out',...
{'MA','MB','C','D'},'input','T0',... 'output','mod1.ppb1');
182
mphversion
Return the version number of COMSOL Multiphysics
Purpose
mphversion
Syntax
v = mphversion
[v,vm] = mphversion(model)
Description
See also
183 |
mphload, mphsave
mphviewselection
Display a geometric entity selection in a MATLAB figure.
Purpose
mphviewselection
Syntax
mphviewselection(model,geomname,number,'entity',entity,...)
mphviewselection(model,selection,...)
Description
mphviewselection(model,geomname,number,'entity',entity,...) displays
the geometric entity number of type entity in MATLAB figure including the
representation of the geometry geom.
mphviewselection(model,selection,...) displays the geometric entity
selection selection in a MATLAB figure including the representation of the
geometry.
VALUE
Parent
Double
Edgecolor
Edgelabels
on | off
off
Edgelabelscolor
Edgemode
on | off
on
Show edges
Facealpha
Double
Facelabels
on | off
off
Facelabelscolor
Facemode
on | off
on
Show faces
Facecolor
RGB array
[0.6,0.6,0.6]
Vertexlabels
on | off
off
Vertexlabelscolor
Vertexmode
on | off
off
Show vertices
Vertex marker
Marker
DEFAULT
DESCRIPTION
Parent axis
Markercolor
Markersize
Int
12
Geommode
on | off
on
Facecolorselected
RGB array
[1,0,0]
184
mphviewselection
Example
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Edgecolorselected
RGB array
[1,0,0]
Markercolorselected
Showselector
on | off
on
Show Selector
Selectorcolor
RGB array
[0,0,1]
Selectoralpha
Double
0.25
Set selector
transparency value
Entity
Domain |
boundary | edge |
point
Selection
Char | Int
Plot edge 1 to 9
hold on
mphviewselection(model, 'geom1',1:8,'geommode','off',...
'entity','edge', 'edgecolorselected', [0 1 0.5])
185 |
mphv4
Convert a FEM structure or FEMGUI object to a model object.
Purpose
mphv4
Syntax
model = mphv4(obj)
Description
Note: The mphv4 function requires that you run COMSOL with MATLAB in
compatibility mode.
Example
186
mphxmeshinfo
Extract information about the Xmesh
Purpose
mphxmeshinfo
Syntax
Description
Example
FIELD
DESCRIPTION
ndofs
Number of DOFs
fieldnames
fieldndofs
meshtypes
dofs
nodes
elements
187 |
I n d e x
A
CAD formats 49
circle 43
Compose operation 44
COMSOL 3.5a, converting from 119
COMSOL Desktop 23
exchanging geometries with 48
COMSOL Java API 23
COMSOL Multiphysics binary files 81
COMSOL Multiphysics text files 81
constraint Jacobian matrix 90
constraint residual vector 89
constraints 89
constructor name 57
contacting COMSOL 8
converting meshes 80
copying boundary meshes 78
damping matrix 89
data filtering 106
data sets 104, 110
syntax for 109
Delaunay method 67
Difference operation 44
documentation 30
documentation, location 7
DXF files 49
emailing COMSOL 8
equations
global 60
188
modifying 59
evaluating data 111
exporting data for file 114
extruding, meshes by sweeping 73
F
GDS format 49
geometries
1D 42
2D 43
3D 47
exchanging with the COMSOL Desktop 48
parameterized 51
geometry sequences 41
getType() methods 172
importing meshes 81
integrating expressions 113
Internet resources 7
interpolating data 113
Java 23
mass matrix 89
materials 58
MATLAB functions, using in COMSOL 30
MATLAB help browser 30
mesh
189 |
CHAPTER :
advancing front 67
converting 80
copying 78
creating a quad mesh 68
creating boundary layers 75
Delaunay 67
getting information about 82
importing 81
refining 78
setting data for 83
mesh quality measures 77
mesh resolution 64
meshing sequences 63
M-files
from COMSOL 3.5a 119
Model Builder 23
Model Library, accessing in COMSOL 7
model object 23
modifying equations 59
MPH-files 7
N
NASTRAN files 81
NASTRAN mesh 81
native file formats 49
node point coordinates 111
null-space matrix 93
parameterized geometries 51
physics interfaces 57
plot groups
syntax for 103
using 104
plot types 107
rectangle 43
refining meshes 78
reports 114
residual vector 89
190
sequences of operations 23
set operations 44
simplex elements 78
solution vector 89
solver configuration, syntax for 88
sparsity, of matrix 165
state vector 93
state-space matrices
evaluating from models 94
state-space models 93
stiffness matrix 89
structured meshes 69
study, syntax for 87
summary of commands 139
sweeping, to revolve meshes 72
syntax
for materials 58
for physics interfaces 57
system matrices 89
as MATLAB data 90
visualization 103
191 |
CHAPTER :
www.comsol.com