Connecting UQLab to COMSOL

Dear all, I have a corrosion model in COMSOL, that basically is a diffusion-reaction based model. I need to perform Kriging over the parameter estimation. As a first step I managed to operate COMSOL within matlab through “LiveLink”, which in principle will bring both UQLab and Comsol within the same matlab environment, but still have a problem in the navigation ! How I can exchange files between both of them so that I can perform my calculations through UQLab ?
Highly appreciate your help!
Thanks in advanced

3 Likes

Hi @TamadurAB,

I mentioned previously about the possibility of using UQLink to wrap COMSOL so you can use your model as a UQLab MODEL object. But indeed now knowing about LiveLink for MATLAB feature of COMSOL, UQLink may not be necessary.

I assume that LiveLink provide you with abilities—via MATLAB commands—to change the parameters in your model you’re interested in, run the COMSOL simulation, and post-process or get the results that you’re interested in (i.e., quantities of interest). Can you confirm this?

If so, you might not need to think about exchanging files and can simply create a MATLAB wrapper function around relevant LiveLink functionalities. You can find the details of creating a wrapper function in the Model Module User Manual Section 2.3 but below is the basic idea.

You need to create a MATLAB function with the following template:

function Y = myCOMSOLWrapper(X,P)
% LiveLink/MATLAB code that:
%   1. loads the COMSOL model (if necessary)
%   2. takes X as input variables and P as parameters to the model
%   3. runs the COMSOL simulation
%   4. post-processes the simulation results to get Y (the quantity of interest).
end

A note on terminology so as to not confuse them later on: UQLab makes a distinction between the terms input variables (X) and parameters (P). The former is used for inputs that are modeled probabilistically in the context of UQ (the ones that you create an INPUT object for). The latter is optional and used for static inputs; these inputs are kept constant during model evaluation, but you might still want to access them manually between simulation campaign, say, to change how the model is evaluated (e.g., time step size, setting for the numerical solver).

Once you successfully create this wrapper, you can proceed to create a UQLab MODEL object by assigning the wrapper function filename to the configuration option: ModelOpts.mFile = 'myCOMSOLWrapper'; and call uq_createModel on the option (for an example, see Basic Modeling: Computational Model Definition).

I cannot be more concrete because I don’t know anything about LiveLink for MATLAB other than an assumption that such an API should be able to give you a control over the required steps I mentioned inside the wrapper.

Hope this helps.

Thanks so much @damarginal … LiveLink provide full control over the comsol model, so in basic you can operate … study … any numerical experiments in comsol using ATLAB commands.
I`ll check the wrapper and will update the answer with any outcomes I can get. Thanks!

Great to hear! I’d be glad to hear more about the outcome!

1 Like

hello,

Did you manage to find a solution? because I have the same problem

Hi … Somehow yes.
It depends on translating the command of COMSOL into Matlab using the field structure within Matlab.
As a start, you can convert the comsol into matlab “.m” file and then get the commands needed directly from the model file in matlab

Greeting all,
I am also running into the same problem. I know how to run comsol from any matlab code.

below is the command line that call the comsol batch from matlab given that your storing the txt input file in paramcomsol.dat.

% C:\Program Files\COMSOL\COMSOL55\Multiphysics\bin\win64\comsolbatch.exe, -job, b2, -alivetime, 15, -inputfile, “C:\Users\sahuqa\Documents\batchmodel.mph”, -batchlog, “C:\Users\sahuqa\Documents\batchmodel.mph.log”, -recover
!“C:\Program Files\COMSOL\COMSOL55\Multiphysics\bin\win64\comsolbatch.exe” -batchlog out.log -inputfile reactive.mph -paramfile paramcomsol.dat -nosave

I still struggling with connecting the UQLAB to the comsol model. is it possible in UQlab to use existing input and output data for the analysis? this is a side question

Thanks

Hi Qasim,

You need to check the output format of the comsol file and the input to comsol. In principle, comsol output is a column matrix but UQLab read it as a raw matrix. Also for the input, you need to convert them into string format as comsol uses them within your wrapper. Hope you understand the general idea if not let me know.

Have a nice evening

Thanks for paramcomsol.dat. will check it too

Just a follow-up to this point:
• I am assuming a reaction system that need to identify the initial time “t_initial” and the reaction rate constant “K_rxn”.
• The COMSOL should be connected via Livelink to MATLAB
https://doc.comsol.com/5.4/doc/com.comsol.help.llmatlab/LiveLinkForMATLABUsersGuide.pdf”

  1. Define the input
    Input module: Create the input using UQLab input module!
  2. The wrapper function: the general form would be:
    function out = MyWrapper(K_rxn, t_ initial )
    Target of this code is to communicate with COMSOL and extract the data from the model.
    Note that the input is defined by the input module of UQLab and then it will be converted into COMSOL format and then the output will be sent to the analysis function and then we read it back to in UQLab format for further analysis
    ========================================================
    Define your output as global
    global Xout
    ========================================================
    Set number of iterations for running the COMSOL model
    Iter = length(K_rxn);
    Load COMSOL model "no need to load it for each iteration” (Time saving)!
    model = mphload (‘COMSOLModel.mph’);
    No need to set up the time function because it is better to use time adapting time scheme!
  • Note that this will lead to have different sizes of the output and required further adjustment before feeding the output to UQLab
    for i = 1:Iter
    Set model parameters: not the name must be as defined in comsol
    reaction rate: model.param.set('K_rxn’, K_rxn(i));
    initial time: model.param.set(‘t_init’, t_init(i));

    Run the study
    model.study(‘std1’).run (in this case it is a time-dependent study!)
    ===========================================================
    Load COMSOL results: depends on how you defined the output in your comsol model you may call the results using mphtable or the solution block, for example:
    bnd_table = mphtable(model,‘tbl1’);
    ** Read the results “Use MATLAB command here”
    result(i).T = bnd_table.data(:,1); time [day] result(i).C = bnd_table.data(:,2); concentration
    ** Calculating the required output
    result(i).M = 0.2.*ones(size(result(i).C)) - result(i).C; (I am just assuming here the calculations)

end
out = X;
!! Hope this is clear now!

A second solution would be:
Create the test matrices in COMSOL (parameteric sweep or any other methods and use the input data into UQLab). For such solution, check the UQLab examples, which work with existing data, like for Kriging: https://www.uqlab.com/kriging-boston-housing-data-set

Hello TamadurAB and others:
Recently, I conducted research on COMSOL and UQLab joint computation. I realized applying the uncertainty quantization algorithm in UQLab to the finite element model created by COMSOL. Here is my method to share with you.I hope my work will be helpful to you and other UQLab enthusiasts.
I used matlab real-time script to create the code.
First, create the model:

uqlab
rng(100,'twister');
global model;
model=mphopen('support_unit.mph')
modelOPts.mFile='support_unit';
myModel=uq_createModel(modelOPts);

Then, define the input:

IOpts.Marginals(1).Name='S1';
IOpts.Marginals(1).Type='Gaussian';
IOpts.Marginals(1).Moments=[0.25e-3,0.25e-5];
IOpts.Marginals(2).Name='r';
IOpts.Marginals(2).Type='Gaussian';
IOpts.Marginals(2).Moments=[0.025e-3,0.025e-5];
myInput=uq_createInput(IOpts);

Create sample points and model responses:

X=uq_getSample(8,'LHS');
% Y = uq_evalModel(X);
Y=support_unit(X);

Finally, Kriging metamodel was obtained according to the algorithm in UQLab:

MetaOpts.Type = 'Metamodel';
MetaOpts.MetaType = 'Kriging';
MetaOpts.ExpDesign.X = X;
MetaOpts.ExpDesign.Y = Y;
myKrigingMat = uq_createModel(MetaOpts);
uq_print(myKrigingMat)
uq_display(myKrigingMat)

The model function I defined is:

function Y=support_unit(X)
    global model;
   [i,~]=size(X)
    Y=zeros(i,1);
    for a=1:i
        S_var=X(i,1);
        r_var=X(i,2);
        model.param.set('S1',S_var);
        model.param.set('r',r_var);
        model.sol('sol1').runAll;
        Y(a,1)=mphmean(model,'v','volume','selection',1)
    end
end
2 Likes

Dear WHOLIDAY,
Thank you for sharing your work!
Hopefully, this will resolve all connection issues between MATLAB and COMSOL

Regards
Tamadur

it’s a,not i in the function code “S_var=X(a,1);r_var=X(a,2)”

1 Like