Working with CST options from Matlab
- Tutorial

At the beginning of our career path, we are posed with small tasks, the solution of which we immediately run to show to the head. We get advice and comments, then we run to redo it. At the end of the working day, we turn off the computer and with a calm soul go home.
But as your experience and task list grows, there is a shortage of time. At some point, it begins to seem that you can’t leave the office. Then automation will help us to become more productive. Under the cut will be a little experience as a designer of antenna technology.
Introduction
In the last and first post on Habré I told you dear reader how to manage CST MWS CAD systems using Matlab code. Let’s not get a response in the comments, but there are reviews from my colleagues and friends. And the most important question: “Will you show specific application options?” It was impossible to excuse that application options are limited only by your imagination and package functionality. According to this, at the request of workers today we will consider an example of managing CST MWS from outside.
In this case, I wanted to get the machine to complete tasks while I was gone, or I am busy with something more important and useful at the current time. Therefore, it was not only decided to delve into your favorite packages for electrodynamic modeling ( CST Microwave Studio and Ansys HFSS) for control from outside. Ideally, with a tool that I am familiar with, which is Mathworks Matlab .
First of all, I want to note that the article does not claim to be super uniqueness and in some parts it will consist of a translation of the CST help, and the things highlighted below will seem too obvious to some.
Work with options
I love the options. Out of inexperience, I used to develop nonparametric models, but now I parameterize almost everything. Why am I doing this? And I like it so much. Thus, I can rebuild any geometry in seconds without error, if I made a good model. There are no problems with geometry = no problems with the computational grid = no problems with optimization, so you can always quickly transfer a project to other frequencies, to other cases, and much more.
Very often a situation arises when it is necessary to conduct a series of calculations with a change in a parameter and an analysis of the behavior of the structure when it changes. Built-in Parameter Sweep Utilityinvites us to change the parameters according to a linear or logarithmic law, choosing the number of points or the step between them. It is also possible to enter specific parameter values. And if you want to see a different parameter change law?

Strategy
In the general case, our task is quite simple, it boils down to calculating the parameter values and transmitting the CST for the calculation. Whatever is not so boring, fasten the conclusion of some graphs. Below is a simple block diagram of what we will do.

The only thing I want to note is that I called the export of the result in text format as the output of the result, and put the stage of presenting the simulation results in Matlab into the “Post-processing” block.
Let's start
For example, we will use my 5-minute project of a rectangular patch antenna.

The figure above shows the model itself for the calculation and the parameter L, which we will change.
Let the parameter L change according to the quadratic law to the law in the range from 10 to 100, the number of values is 5:
x = sqrt(10):(10-sqrt(10))/5:10;
y = x.^2;Just in case, I’ll give you a chart, although everyone understands how it should look.

We start CST and open our project, and also bind to the variables all the necessary CST objects:
cst = actxserver('CSTStudio.Application');
mws = cst.invoke('NewMWS');
mws.invoke('OpenFile','path\to\file.cst');
solv = mws.invoke('Solver');
export = mws.invoke('ASCIIExport');
plot1d = mws.invoke('Plot1D');Briefly about what these 6 lines represent in the order they are written:
- Binding a CST Studio application object to a cst variable
- Binding CST MWS window to mws variable
- Opening a CST MWS file in a window
- Binding a calculator object to a solv variable
- Binding an Export object in ASCII to an export variable
- Binding an object of one-dimensional graphs to the variable plot1d
Next, we introduce an intermediate variable that is useful for generating paths to result files:
f_cell = cell(length(y),1);What can we achieve from CST about the parameters used in the project?
I somehow could not fasten the last function in the list to the matlab. But not the point, in this case we do not need it.
- We can remove the parameter with the command
mws.invoke('DeleteParameter','ParameterName'); - Find out the number of parameters
mws.invoke('GetNumberOfParameters'); - Find out the name of a parameter by its number
mws.invoke('GetParameterName','ParameterNumber'); - Find out the parameter value by its number in double
mws.invoke('GetParameterNValue','ParameterNumber'); - Find out the parameter value by its number in string
mws.invoke('GetParameterNValue','ParameterNumber'); - Find out the value of a parameter by its name in string
mws.invoke('RestoreParameter','ParameterName'); - Find out the value of a parameter by its name in double
mws.invoke('RestoreDoubleParameter','ParameterName'); - Find out the expression by which the parameter is calculated by its name in string
mws.invoke('RestoreParameterExpression','ParameterName'); - Create a new parameter string (or replace an existing one) with its description
mws.invoke('StoreParameterWithDescription','ParameterName', 'ParameterValue','ParameterDescription'); - Create a new parameter string (or replace an existing one) without description
mws.invoke('StoreParameter','ParameterName', 'ParameterValue'); - Create a new double parameter (or replace the existing one) without description
mws.invoke('StoreDoubleParameter','ParameterName', 'ParameterValue'); - Make sure the parameter name is not taken if it is unoccupied to create a new one with the specified values, otherwise do not touch the existing one
mws.invoke('MakeSureParameterExists','ParameterName', 'ParameterValue'); - Add a description to an existing parameter by name
mws.invoke('SetParameterDescription','ParameterName'); - Pull arrays by calculation start number with parameter names and their values
mws.invoke('GetParameterCombination','ResultId','ParameterNames','ParametersValues');
I somehow could not fasten the last function in the list to the matlab. But not the point, in this case we do not need it.
Since I greatly simplified the task, only one function is of interest from the list presented in the spoiler:
mws.invoke('StoreDoubleParameter','ParameterName', 'ParameterValue');In the body of the cycle, we will need to do only 4 operations: pass the parameter, update the model, start the calculation and export the results.
Open a cycle with a length of 1 to the number of y parameter values :
for i=1: length(y)We pass the parameter:
mws.invoke('StoreDoubleParameter','L', y(i));Updating the model:
mws.invoke('Rebuild');We start the calculation:
solv.invoke('Start');Next, we prepare the string variables of the paths to save files (the first line translates the current value of the parameter into a string, the second - create a string of the path to save the file, the third - write the address of the current result file into the array of cells:
str_y = num2str(y(i));
f_name = strcat('C:\Results_patch\patch_z_im_y=', str_y,'.txt');
f_cell(i,1) = {f_name};As the result for export, I chose the graph of the imaginary part of the input resistance, so the following is the choice of the corresponding branch of the result tree, the export procedure in ASCII described in the previous post , and also the end of the cycle.
mws.invoke('SelectTreeItem','1D Results\Z Matrix\Z1,1');
plot1d.invoke('PlotView','imaginary');
export.invoke('Reset');
export.invoke('FileName',f_name);
export.invoke('Mode','FixedNumber');
export.invoke('Step','1001');
export.invoke('Execute')
endAfter the actions done, we have a set of files with the result of calculating the imaginary part of the input resistance. But what else to do with frequency-dependent quantities? Display as a graph.
Since all output results in ASCII from CST have a header, we need to get rid of it, in our case, these are two lines at the beginning of each file:
Frequency / MHz Z1,1/imaginary
----------------------------------------------------------------------To do this, we will use the simple function listed below the spoiler, which I wrote a long time ago. The input parameter for the function is the path to the file to remove the header.
The function reads the file line by line, then overwrites the data in it without a header, and on the output gives you a variable with data from the file.
Delete header
function [f_cell] = h_remove(ishod)
ffile = fopen(ishod,'rt');
f_cell=cell(1003,1);
i=1;
for i=1:length(f_cell)
%while feof(Farfield) ==0
f_cell{i,1} = fgetl(ffile);
%i = i+1;
end
f_cell = f_cell(3: end, 1);
fclose(ffile);
ffile = fopen(ishod, 'w+');
for i = 1: length(f_cell)
fprintf(ffile, '%s\r\n', f_cell{i,1});
end
fclose(ffile);
f_dat = load(ishod);
endUsing the above function, load the calculation results into variables, display the graph and comb it slightly.
y1 = h_remove(f_cell{1,1});
y2 = h_remove(f_cell{2,1});
y3 = h_remove(f_cell{3,1});
y4 = h_remove(f_cell{4,1});
y5 = h_remove(f_cell{5,1});
y6 = h_remove(f_cell{6,1});
plot(y1(:,1),y1(:,2), '-r', y1(:,1),y2(:,2), '--r',y1(:,1),y3(:,2), '-.r',y4(:,1),y1(:,2), '-b',y1(:,1),y5(:,2), '--b',y1(:,1),y6(:,2), '-.b')
grid on
xlabel('Частота, МГц')
ylabel('Сопротивление, Ом')
legend(num2str(y(1)),num2str(y(2)),num2str(y(3)),num2str(y(4)),num2str(y(5)),num2str(y(6)))

conclusions
In such a simple way, in just 39 lines, we forced CST to perform a parametric calculation according to the law we changed for the parameter, output the calculation results for further processing in ASCII, and screw the output in the Matlab environment.
You can say: E “then everything can be done without Matlab!” What have you come up with is the built-in VBA macro editor. ” And I will answer: “Yes, you are right. You can write everything in VBA if you like it. ”
But further processing of the results in Matlab may be useful. You can also use Report Generator. Then it becomes possible to leave the car to carry out the calculation in your absence, and then it remains only to print and put the finished report on the head table.
References
Below I place the test script, parsed here, and the h_remove functions for your experiments, as well as a link to the project file for those who did not notice the link in the text:
→ Antenna project
Script
%% Расчет значений параметра
x = sqrt(10):(10-sqrt(10))/5:10;
y = x.^2;
%% Запуск и привязка объектов CST
%cst = actxserver('CSTStudio.Application');
%mws = cst.invoke('NewMWS');
%mws.invoke('OpenFile','C:\patch.cst');
solv = mws.invoke('Solver');
export = mws.invoke('ASCIIExport');
plot1d = mws.invoke('Plot1D');
f_cell = cell(length(y),1);
%% Цикл для расчета
for i=1: length(y)
mws.invoke('StoreDoubleParameter','L', y(i));
mws.invoke('Rebuild');
solv.invoke('Start');
str_y = num2str(y(i));
f_name = strcat('C:\Results_patch\patch_z_im_y=', str_y,'.txt');
f_cell(i,1) = {f_name};
mws.invoke('SelectTreeItem','1D Results\Z Matrix\Z1,1');
plot1d.invoke('PlotView','imaginary');
export.invoke('Reset');
export.invoke('FileName',f_name);
export.invoke('Mode','FixedNumber');
export.invoke('Step','1001');
export.invoke('Execute')
end
%% Постобработка
y1 = h_remove(f_cell{1,1});
y2 = h_remove(f_cell{2,1});
y3 = h_remove(f_cell{3,1});
y4 = h_remove(f_cell{4,1});
y5 = h_remove(f_cell{5,1});
y6 = h_remove(f_cell{6,1});
plot(y1(:,1),y1(:,2), '-r', y1(:,1),y2(:,2), '--r',y1(:,1),y3(:,2), '-.r',y4(:,1),y1(:,2), '-b',y1(:,1),y5(:,2), '--b',y1(:,1),y6(:,2), '-.b')
grid on
xlabel('Частота, МГц')
ylabel('Сопротивление, Ом')
legend(num2str(y(1)),num2str(y(2)),num2str(y(3)),num2str(y(4)),num2str(y(5)),num2str(y(6)))
h_remove
function [f_dat] = h_remove(ishod)
%Грузим файл который надо править
ffile = fopen(ishod,'rt');
%Создаем временную переменную для хранения строк исходнового текста
f_cell=cell(1003,1);
%Цикл читает построчной исходный файл и записывает во временную переменную
i=1;
for i=1:length(f_cell)
%while feof(Farfield) ==0
f_cell{i,1} = fgetl(ffile);
%i = i+1;
end
f_cell = f_cell(3: end, 1);
fclose(ffile);
ffile = fopen(ishod, 'w+');
for i = 1: length(f_cell)
fprintf(ffile, '%s\r\n', f_cell{i,1});
end
fclose(ffile);
f_dat = load(ishod);
end