Best Practice for Working with Model M-Files

May 14, 2014

When developing models in COMSOL Multiphysics® software, it is common to come across tasks that have to be carried out repeatedly. This three-part blog series will show you how repetitive tasks can be efficiently achieved using model M-files and LiveLink™ for MATLAB®.

Introducing Variations into Models

You can introduce many variations into your models through the COMSOL Multiphysics user interface (UI). Functionality, such as parametric sweeps and optimization, allow you to vary a set of parameters in tailor-made edit fields for this purpose.

Yet, some types of variations are not catered to by the UI. In these cases, LiveLink™ for MATLAB® comes in handy as it can access all the model settings, using the COMSOL® API for use with Java® (COMSOL API).

With LiveLink™ for MATLAB®, it is possible to:

  • Start simulations automatically from a MATLAB® program
  • Introduce changes to model settings through the use of scripting
  • Create models from scratch
    • Creating the geometry, meshing, defining physics, calling a solver, and postprocessing the results
  • Read CAD files and files containing meshes
  • Connect to other data sources and read data from files, databases, etc.
  • Create a simplified UI for novices to run models

Many of these features are important if you wish to avoid repeating your work in the COMSOL Multiphysics UI.

Building a Model from Scratch Using LiveLink™ for MATLAB®

If you are new to LiveLink™ for MATLAB®, then the Introduction to LiveLink™ for MATLAB® manual provides sufficient information to get you started. In particular, the LiveLink™ for MATLAB® User’s Guide provides further resources about the commands within the COMSOL Multiphysics API and the equivalent MATLAB® functions they access. You can actually create your first model M-file, which controls a COMSOL Multiphysics model, without having to read this documentation. This is because such scripts can be auto-generated from the COMSOL Multiphysics UI.

Let’s look at a simple heat transfer example that only requires the COMSOL Multiphysics base package to build and solve. The geometry can be seen in the following figure, where a heat flux is introduced at the bottom boundaries and dissipates into the surrounding air at the top boundaries.

A geometry where heat flux originates at the bottom boundary and then dissipates into the air

Plot created with COMSOL Multiphysics that shows the surface temperature of a model

The geometry consists of a few rectangles that are either combined with or subtracted from each other. The M-file code for making this geometry can be seen below:

Example M-file code needed to make a geometry

Here, the code is commanding COMSOL Multiphysics to create rectangle nodes in the model tree, as well as the node that takes the difference between rectangles. You see that the size and position (pos) of the entities are defined. These definitions can be used to define the geometry as you’d like it to be. It is evident that even small geometries may lead to a lot of defining code. The next section shows how to create lines automatically.

Automatic Generation of Model M-files

All functionality within COMSOL Multiphysics can be represented by a line of code, and a full model would correspond to many lines of code. Instead of creating a model from scratch using a script, you can create it in the COMSOL software UI and then save it as an M-file. This is done by choosing File > Save as and then selecting “Model File for MATLAB (*.m)”.

Such an M-file contains all the steps that have been followed when building the model. By running the file using LiveLink™ for MATLAB®, you will notice that all the commands that were performed are recorded. If the model was solved several times, there will be several calls to the solvers, which you typically don’t want. If you were to run the model from the MATLAB® command line, it will solve the model several times. In order to obtain an M-file that is compact, you can choose File > Compact History before saving the file.

Diagram showing the steps necessary to obtain a compact M-file

Now that we have the entire model as an M-file, we are free to investigate — or change — any of the settings in the model. We can add new features to the model, as well.

Have a look at your M-file and see if you can identify the various sections of the model and how things are set up. Some things will be easy to understand in a model, such as how parameters and the geometry are defined. Other things, such as solver or plots settings, can be more obscure. However, if you have MATLAB® coding experience, you should easily be able to see where things are defined.

In the following example snippet:

Example code showing how mesh settings are defined

you can see how the mesh settings are defined. When an M-file contains the definition of the geometry, physics, mesh, solvers, etc., a call is made to a “run()” method. This takes all the commands in the M-file and executes them in COMSOL Multiphysics. Calls to “run()” may take a long time if your model is big, so if you wish to follow the solution progress, you can switch on the Progress window by using this code (before calling run):

Code used to turn on the Progress window prior to calling a run

Working Even Faster Without Model M-Files

If you use MATLAB® to change a model using the COMSOL software API and lose track of changes, it is nice to know that you can always save the model as an MPH-file, load it into the COMSOL Multiphysics UI, and inspect it there. Furthermore, you can load MPH-files into MATLAB® and manipulate them from there, as well.

The following example loads an MPH-file and performs a “for” loop on the parts of the model that has changed (its geometry) before solving it.

Code that loads a MPH file and runs a for loop on model parts that have been changed

Selections

One of the biggest reasons for working with M-files is to be able to manipulate geometries. In order to do this, you need to understand Selections:

Code that sets up physics for heat transfer and boundary conditions for Heat Flux Boundary

The above code sets up some of the heat transfer physics, including two boundary conditions for a “Heat Flux Boundary” on a series of boundaries, identified by numbers. When a geometry is changed in a way that introduces more domains, boundaries, or vertices, these numbers will change too. You will need a way to either track these numbers, or avoid using them.

These will be the topics of the next two blog entries in this series. Stay tuned.

Other Posts in This Series

  1. How to Manually Work with Entity Numbers in Selections
  2. Automatically Handling Selections in COMSOL Multiphysics®

MATLAB is a registered trademark of The MathWorks, Inc.


Comments (13)

Leave a Comment
Log In | Registration
Loading...
Peter Cendula
Peter Cendula
September 16, 2014

Thanks for useful blog! I tried to ‘compact history’ in my rather larger MPH file and I got the error ‘Unknown model parameter’. Is there any way to workaround this?

Thanks
Peter

Lars Gregersen
Lars Gregersen
September 16, 2014 COMSOL Employee

COMSOL analyzes the structure while performing Compact History, but sometimes has to give up. Please send the MPH-file to support@comsol.com so we can have a look.

Mathias Perrin
Mathias Perrin
December 29, 2015

Thank you for this blog,

I use every day Matlab Livelink with comsol, and I think it is very efficient.

It is a fantastic tool when you combine Matlab advantages (graphics, data posttreatment, highlevel mathematical functions such as FFT, matrix operations) with Comsol advantages (multiphysics approach, numerical computation of complex physical problems).

That’s why I am trying to compile matlab programs using Matlab compiler. The idea is to be able to distribute exécutables that would use a Comsol licence and Matlab runtime libraries.

I am trying to compile a simple script that opens some .mph model, using mphload().

Untill now, I always have some bug at runtime. It is probably a matter of setting correctly the path to the .dll and java files that are needed at runtime.

I discussed with Comsol but they don’t support matlab compiler, and of course matlab do not support compilation of comsol exécutables.

So, if someone ever tried, and has a procedure, or at least some experience, I would be very very glad to know it !

Cheers,

Mathias

Lars Gregersen
Lars Gregersen
January 4, 2016 COMSOL Employee

Hi

Although not officially supported applications compiled with the Matlab Compiler should work together with Comsol Multiphysics.

When creating your application then include a call to mphstart at the beginning of your application. Make sure to use one of the variants of mphstart that includes a COMSOLPATH. Make sure you use the correct COMSOLPATH at runtime. Comsol has to be installed on the computer in order for the application to run.

If this doesn’t work then please contact support and we’ll see if we can help you. Please include the version of Matlab and your operating system that you are using in the message to us.

Oscar Diaz
Oscar Diaz
April 7, 2016

Hej Lars,
Nice blog entrances on Matlab livelink. Some of those useful tricks I learned on the way, by creating a model, compacting the history and saving the m-file to check some syntaxis errors and similar.
The program that I did, creates new geometries during the execution process calling different comsol-functions from matlab. Always when the meshing crashed and red text came to the matlab command window, indicating an error and that the execution was cancelled.
Now, after 3h execution, the execution got stocked somewhere, but I cannot find where. While in normal execution, it has been calling the same functions since the early beginning until it just dies…
It might have to do something with memory I guess (not so sure), because the only closing/stopping possible when goes to this problem, is closing the OS command window where the comsol server was started. Then, I go back to Matlab editor, and find out an active breakpoint (green arrow on a code line that stops the execution when the program reaches that code line), even if the comsol server is already closed (not possible to continue in execution). Can it be that the size of the object that is stored in the memory of the Comsol API overflows the memory available (the output files from previous steps is ca. 100MB)
I’ve been stocked here for a long time, do you have any suggestions?

Lars Gregersen
Lars Gregersen
April 8, 2016 COMSOL Employee

Hi Oscar

Without seeing your script it is hard to guess what goes wrong. It is quite easy to run out of memory when you are creating a large model using a script since you can easily create thousands of geometric objects, physics and settings, which all take up memory, of course.

The most common memory related mistake when creating models and geometries using a script is that when you create a model using
model = ModelUtil.create(‘Model1’)
each subsequent statement you execute will add some information to the model history. This is done such that you later can export an M-file (or VBA- or Java-file) with all you steps. However, exporting such files are rarely useful (since you already have a script that can do what you want) and you can always use “Compact model history” to get what you want.
The solution is to switch history generation off. We always cover this topic at the tutorials we give at the Comsol Conferences. It is also mentioned in the Introduction to LiveLink for Matlab manual where it says you need to write:
model.hist.disable;

If this doesn’t help your case then please send your script/model to Comsol Support where we will have a look at it.

R Karimi
R Karimi
January 9, 2019

Thanks for your useful blog. I have used COMSOL live link with MATLAB for optimization. My optimization code is written in MATLAB and as the objective function I build a comsol model, run that and use its results. The problem is that when I call the objective function from the optimization code, after 8 to 9 times of calling, the model exits with the error that the solution is not found. However, when I call the objective function separately, with the same inputs from MATLAB, it runs completely. I think the problem is that the previous model is not closed from the last call. How can I close a model in MATLAB Live link?
I would really appreciate if you could help me with it.

Lars Gregersen
Lars Gregersen
January 9, 2019 COMSOL Employee

Hi Karimi

The most common problem we see when a model doesn’t give a solution when performing optimization is that the parameter values that are determined by your optimization code go outside of the area where the model is well defined. Also you must make sure that the initial values for your model are consistent with your new parameter values.

You can use ModelUtil.remove to remove a model from the Comsol Multiphysics Server, but you should rarely use that.
Simply reload the model using mphload whenever you start a simulation. This way you are certain that your simulation starts with a known state.
If you continue to have problems with your model you can send it to support where we will have a look at it.

Cooper Li
Cooper Li
May 2, 2020

Thanks for the wonderful explanation, is it possible that I could use the COMSOL alone to achieve some MATLAB functions, such as for loop and findpeaks(both of them are MATLAB built-in functions)?

Sincerely,
Li

Lars Gregersen
Lars Gregersen
May 4, 2020 COMSOL Employee

We have added model methods and addins to Comsol Multiphysics since I wrote this blog post. These additions makes it possible to create programs using the Java programming language. If your custom programming doesn’t rely heavily on numerics and/or Matlab toolboxes this new approach may be something for you.
I’m not familiar with the findpeaks function (it requries the signal processing toolbox), but from its name it sounds like something you would like to use Matlab for.

Chin Neng Leong
Chin Neng Leong
September 1, 2021

Thanks for sharing this.

I’m trying to export deformed geometry using Deformed Configuration. However, I always get the deformed geometry at the last time step. I managed to modify the time in the Deformed Configuration , but I guess I need to update then only can export the interested time point. Does anyone know what’s the Matlab code to update the Deformed Configuration?

Also, I find that .m file only documents the steps until Study. Is there anyway to save all the steps made to the result sections in .m file?

Thanks
Chin Neng

Lars Gregersen
Lars Gregersen
September 1, 2021 COMSOL Employee

When you save a model as an M-file all steps are included. Including setting up the results. If you are having problems with this I recommend you contact support.
I have a similar advice about exporting deformed geometries. Send your model and the Matlab code you have to support and someone will have a look.

Chin Neng Leong
Chin Neng Leong
September 1, 2021

OK. Thank you.

EXPLORE COMSOL BLOG