Thursday, August 18, 2016

Comsol Multiphysics (from livelink)

Reference Manuals:

Comsol Reference Manual:
COMSOL_Reference_Manual.pdf

Comsol with Livelink Reference Manual:
LiveLink_For_MATLAB_Users_Guide.pdf

A good way to start:

Do you need it? Comsol offers a method to perform a parameter shift which could avoid going into these troubles.

Otherwise, open the GUI and create your model. The following ideas are rule of thumb that makes everything simpler afterwards:
  • use as many parameters as you can
  • refer to domains with implicit selections (explicit selections might get undefined when the geometry get modified
  • perform every basic task you want to be able to modify later (geometry, meshing, material properties, physics definition, solver and run the simulation).
From there, two scenarios are possible, the clean one and the messy one. The clean one is simpler but gives less control. The messy one gives access to all the parameter of the model.
The clean method: 
Save the Comsol model as a standard "simulation.mph" file and later open Comsol with the following command line (from the console):
comsol server matlab 
Start a new script and add the following line:

mphload('simulation.mph');
It is then possible to access all the information from the model with the command
 mphnavigator
All the parameter can be accessed and modified with the command described bellow.

The messy method:
Perform every task and compact the history (file > Compact History), then save the file as a model file for Matlab (.*m).

Every task performed before will be translated in command lines. The Matlab file is self-contained.

Few useful commands for display:

plot the geometry:
mphgeom(model);

plot the mesh:

model.mesh.run()
mphmesh(model);

plot a result:
mphplot(model, 'pg1');

Extracting information:
[d1, ..., dn] = mphinterp(model,{'e1', ..., 'en'},'coord',<coord>);

More examples to access data:
data = mpheval(model,'mf.normB');                              %give 'mf.normB' for each points
databoundaries = mpheval(model,'mf.normB', 'selection', 43);             %give 'mf.normB' for each points on the boundary 43
dataPoint = mphinterp(model,'mf.normB','coord',[5e-2;-2e-2;1e-3]);  %give 'mf.normB' at a particular point
data_point.amplitude = mphinterp(out,'log(mf.normB)','coord',[ones(size(-2.5:0.01:2.5))*0.27;-2.5:0.01:2.5]);  %line measurement

%rename file
filename = ['/home/user/plot' num2str(index) '.txt'];
model.result.export('plot1').set('filename', filename);

%remove the header
model.result.export('plot1').set('header', false);

%change the size of something:
model.param.set('L','18[cm]');

%run the solver
model.sol('sol1').run;

%check the time of a comand
tic;
time = toc;
fprint('blabla %gt\n', time);

Debugging:

The feedbacks provided by Livelink are not very informative. A good way to  debug the model is to save the model as an "mph" file and check what is happening from the GUI. To do so (the full path is needed as Comsol is run from a weird place):
model.save('/home/user/test.mph');

or
 
mphsave(model,'filename')

Friday, May 22, 2015

3-D bar graph with Matlab (and why you should not use it)

Matlab has an important set of display function to perform data visualization. Among them, a few ones allow performing 3D visualization of 2D data.

I am going to talk about the bar3 and hist3 function which are the nicer ones according to me


Hist3

The data sample used for this plots are generated  using the randn function:
figure;
hist3(randn(1000,2));
This return a 2D matrix with the histogram of the two arrays (globally a random Gaussian mixture).

The hist3 function  allows to plot the data straight in a figure (if the ";" is not present) and give the following results:

Samples of plot using the hist3 function
The following attribute can be changed:
% change the transparency
alpha(0.5);
% define the color of the face according to the height (left and right)
set(get(gca,'child'),'FaceColor','interp','CDataMode','auto');
% define the color of the face according to the height (center)
set(get(gca,'child'),'FaceColor','flat','CDataMode','auto');
% change the colormap
colormap('cool');
% accelerate the display using OpenGL for the rendering
set(gcf,'renderer','opengl');


Bar3

The function bar3 offer more flexibility than hist3 and is just intended to be used for a display purpose.

In order to get the similar data as for the previous example we get the bivariate histogram of two random vectors:
dataSample = hist3(randn(1000,2));
figure;
bar3(dataSample);
This function allows to plot a similar kind of shape but offer more flexibility.
Samples of plot using the bar3 function
It is possible to access each bar of the plot one by one and to change the width, the color, the visibility and the transparency (among others) of them.

change the width:

width = 0.5;
bar3(dataSample, width);

change the color

% first subplot
for n=1:numel(h)
     cdata=get(h(n),'zdata');
     set(h(n),'cdata',cdata,'facecolor','interp')
end

% second and third subplot
for n=1:numel(h)
     cdata=get(h(n),'zdata');
     cdata=repmat(max(cdata,[],2),1,4);
     set(h(n),'cdata',cdata,'facecolor','flat')
end

change the visibility

% second subplot
for iSeries = 1:numel(h)
    zData = get(h(iSeries),'ZData');
    index = logical(kron(zData(2:6:end,2) == 0,ones(6,1)));
    zData(index,:) = nan;
    set(h(iSeries),'ZData',zData);
end

change the color

% classic method
colormap(axis3, 'summer');
cmap = colormap(axis3);
cmap = flipud(cmap);
colormap(axis3, cmap);

How and where to use it

This visualization tool should be used with care since it does not display the information accurately.

It is, however, a very good tool to explain a methodology.

Tuesday, November 25, 2014

Getting started with GUI in Matlab.

This is a short introduction on how use the Graphical User Interface (GUI) with Matlab:


To start a GUI in Matlab just type "guide" in the command window. You can then drag and drop object, and change their properties with a double click.

Load a file using a browser

Get the path of a file and load it:
[FileName,PathName] = uigetfile('*.mat','Select the MATLAB matrix');
str = load([PathName, FileName]);

working with variables

Matlab define a set of function which allow the user to define the possible interaction with the objects. This function can be access with the callback function (to generate it just do a right click on the object and go in the callback section).

One of the important issue with this methods is that all the data have to be loaded and saved each time you change of function.

The natural workflow is:

function pushbutton1_Callback(hObject, eventdata, handles)
% load the data
var = evalin('base', 'varName');
...
% manipulation
...
% save the data
assignin('base', 'varName', var);
or  getappdata and setappdata.

Get and set properties from a callback

To get the value of a property (for example the value of a slider):
get(handles.slider2, 'Value');
 and to set a property (for example to define the text of a edit object):
set(handles.edit1, 'string', 'text');
Sometimes finding the handles of an object can be a bit tricky. There is a special function called findobj which allow to do it. An easy way to use it it to look for the 'Tag'  of the object.
findobj('Tag''edit1'

Display images/graphs

Do display an image you have to add a axis object.
The next step is to select the axes.
axes(handles.axes1);
and finally to plot the image:
imagesc(img);

Ps: to remove the axis it is possible to use axis off


Save a file using a browser

The following function open a browser and allow to save a file
uisave('varName');

Monday, November 24, 2014

Morphological Operations in Matlab

Just a memo about the functions available in Matlab dedicated to image processing.

Filtering:
filter2 : add 'same' as an option to avoid the size transformation.

Create a selection:
im2bw : convert an image to a B&W image according to a threshold.

create a filter:
strel : Create a structural element. means to be used as a mask, see 'diamond', 'disk'.
edge : detect the edges of an image, to apply with a threshold.

Modify the selection:
imdilate
imerode
imclose : Which is basically a combinaison of imdilate and imerode
imopen : Opposite of imclose
imfill : Clean alternative of imclose
bwmorph : Lots of different operation available, included 'skel', 'bridge', ...
imcomplement : Inverse the values of the black and white in a image

Full list of the functions available in Matlab at: http://www.mathworks.com.au/help/images/morphological-filtering.html