How to write a script for Wolfram SystemModeler to run several simulations? - modelica

I want to run around 100 simulations with my model changing two parameters f and TLoadand track the changes on the phase currents currentSensor.i[1] etc.
Now I'm stuck with the documentation on the Wolfram website because there is no definite explanation on how to use scripting with the SystemModeler. I found for example this link on the Wolfram site with some code but no explanation in which commandline I should use it.
I downloaded the WolframScript program and tried to open my model with wolframscript -file SMPM_VoltageSource_Inverter.mo but it says ToExpression::sntx: Invalid syntax in or before ... eventhouh my model simulates totally fine and without any errors in the SimulationCenter.
Can someone explain to me:
Is it possible to write scripts ?
If Yes:
How can I simulate my model?
How can I do a parameter sweep of f and TLoad? Is it as described in the link?
Is it possible to export data of currentSensor.i[1] as a csv-file? And how to?
Thank you for any help!

I don't know about wolfram sorry, but for OpenModelica the following works:
// to load Model from file use
// loadFile("fileName.mo");
loadString("
model M
parameter Real a = 1;
Real x;
equation
x = a * sin(time);
end M;
"); getErrorString();
buildModel(M); getErrorString();
for a in {1,2,3,4} loop
str_a := String(a); getErrorString();
system("./M -override a=" + str_a); getErrorString();
// for windows use
//system("M.exe -override a=" + str_a); getErrorString();
system("mv M_res.mat " + "M_" + str_a + ".mat");
end for;
Put this in a file named for example model.mos and call it from terminal or command line, depending on your os, with omc model.mos if you have OpenModelica installed. this should generate a csv.
EDIT: I realized the original just saves the last value of x, you might want the full output. Therefore i changed the .mos-file. Each different result will be saved in a different file, if you want to change it to csv you just have to change the generated xml.

Related

Matlab script edit - model recognition

I try to alter the properties of a MatlabFunction on Simulink. The recommended commands here are below.
open_system('my_model');
S = sfroot
B = S.find('Name','myBlockName','-isa','Stateflow.EMChart');
The 'BlockName' is a MatlabFunction on the model my_model. The content of B is '0×1 empty handle' and S.Name gives DefaultBlockDiagram. It seems it does not recognize the opened model.
The correct command is "slroot"

linIt function in Octave

I try to convert these matlab scripts to octave. However in getGroundTruthBoxes.m, it has following code:
freq = cell2mat(accumarray(inst(inst>0), segm(inst>0), [], #(x){linIt(histc(x,1:numClass))'}, {zeros(1,numClass)}$
When i try to run with octave, it gives " linIt undefined" error. I googled "linIt" functions , but i can not reach any information about linIt. Can you give information about this "linIt" function?
Thanks.
The user s-gupta whose repository you're using seems to have another repository called utils, where he defines this function https://github.com/s-gupta/utils/blob/master/matlab/linIt.m
Essentially it seems to be a tiny helper function that converts an array to its linearly indexed column-vector, i.e.
function a = linIt(A)
a = A(:);
end

OpenModelica updating CombiTable input in real time

I have a model in which I am using a CombiTable1D to retrieve an external input from a .txt file. The file is generated by a Python script at the moment but in the final phase of the project, it is going to be updated each second. For now, simulation takes place without a problem as the .txt file is static. Just read the file and make simulation according to the data written there.
What I want to do is to simulate a model until a certain time, let's say 100s, and then make it wait until a real time event by which the .txt file is updated for the next external input values between 100-200. The simulation should continue by getting these new values for the next 100 seconds.
As I have already been working with OMPython, it is really practical for me to edit the .txt file using Python, let's say for each 10 seconds in real time. I can now simulate the model until the time instance that I define as the refreshing point of the external input. But I couldn't figure out how to keep the state of the simulation and make it read the file once again.
Actually, this sounds like a co-simulation scenario to me. Anyway, what you could do is to extend from CombiTable1D and have something like
block CombiTable1DWithUpdate
extends Modelica.Blocks.Tables.CombiTable1D(final tableOnFile=true);
algorithm
when sample(0, 10) then
readTableData(tableID, /* force update */ true, verboseRead);
end when;
end CombiTable1DWithUpdate;
In addition the the answer I accepted, I want to give another solution which is not so efficient. For a simple model with a capacitor and resistor, I made successfull tests but with more complex models, it doesn't function properly. In a Modelica script, realTimeSimulation.mos:
outputFile := "stepResult.mat";
simulation_step := 1;
start_time := 0;
stop_time := start_time+simulation_step;
loadFile("WhereverTheFileIs.mo");
buildModel(myTestModel);
system("myTestModel-override=startTime="+String(start_time)+",stopTime="+String(stop_time)+" -r="+outputFile);
will build the model and simulate the first step until the simulation time t=1s. Later on, using Python the text file is updated. The new data for the time between t=1s and t=2s are written to the text file where I am getting the input of the model. Then another step of the simulation is made for the time between t=1s and t=2s. As a loop, it continues like forever like: actualize the data, make new simulation for the new time interval. The trick is, reading the output file created at the end of each step and giving all the variable values as the new initial conditions to the simulation, using following script:
valueList := readSimulationResultVars(outputFile);
start_time := start_time+simulation_step;
stop_time := stop_time+simulation_step;
value := val(OpenModelica.Scripting.stringVariableName(valueList[1]),start_time,outputFile);',
variableString := valueList[1] + "=" + String(value);
for i in 2:size(valueList,1) loop
value := val(OpenModelica.Scripting.stringVariableName(valueList[i]),start_time,outputFile);
variableString := variableString + "," + valueList[i] + "=" + String(value);
end for;
system("myTestModel-override startTime="+String(start_time)+",stopTime="+String(stop_time)+",variableString+" -r="+outputFile);

stuck with my small code in matlab

I have problem with the following code:
.
.
.
a=zeros(1000,ctimes);
a1=zeros(1000,ctimes);
hold all
for i=num1:num2;
colors=Lines(i);
switch phantom
case 1
path=['E:\filename\'];
path1=['E:\filename2\'];
n=['S',num2str(emt),'_',num2str(i),'.m'];
d=load([path,name]);
a(:,i)=complex(d(:,2),d(:,3)));
n1=['S',num2str(emt),'_',num2str(i),'.m'];
d1=load([path1,name1]);
a1(:,i)=complex(d1(:,2),d1(:,3)));
the problem is that a(:,i) can not be defined. while there is no problem or with complex(d1(:,2),d1(:,3))) , can any expert body help me plz?!
thank you ...
Are you sure you are forming your file name correctly? You are doing something to create a variable n, but using a variable name when you form the path. Here are some recommended debugging steps:
1) make sure the file path is formed correctly:
filePath = fullfile(path, name);
disp(filePath);
The fullfile function concatenates elements of a file path & name, and takes care of using the right file path separator (good for portable code, stops you having to remember to add a / or \ to the end of a file path, etc).
2) check that d is loaded correctly:
clear d;
d = load(filePath);
disp(size(d));
3) check the size of the complex quantity you compute before assigning it to a(:,i):
temp = complex(d(:,2), d(:,3));
disp(size(temp));
By the time you have done these things, you should have found your problem (the dimensions of temp should be [1000 1] to match the size of a(:,i), of course).
As an aside, you should avoid using i as a variable name, especially when you are using complex numbers, since its built-in value is sqrt(-1). Thus, c = a + i * b; would create a complex number (a,b) and put it into c - until you change the meaning of i. A simple solution is to use ii. The same is true for j, by the way. It is one of the unfortunate design decisions in Matlab that you can overwrite built in values like that...

Call graph generation from matlab src code

I am trying to create a function call graph for around 500 matlab src files. I am unable to find any tools which could help me do the same for multiple src files.
Is anyone familiar with any tools or plugins?
In case any such tools are not available, any suggestions on reading 6000 lines of matlab code
without documentation is welcome.
Let me suggest M2HTML, a tool to automatically generate HTML documentation of your MATLAB m-files. Among its feature list:
Finds dependencies between functions and generates a dependency graph (using the dot tool of GraphViz)
Automatic cross-referencing of functions and subfunctions with their definition in the source code
Check out this demo page to see an example of the output of this tool.
I recommend looking into using the depfun function to construct a call graph. See http://www.mathworks.com/help/techdoc/ref/depfun.html for more information.
In particular, I've found that calling depfun with the '-toponly' argument, then iterating over the results, is an excellent way to construct a call graph by hand. Unfortunately, I no longer have access to any of the code that I've written using this.
I take it you mean you want to see exactly how your code is running - what functions call what subfunctions, when, and how long those run for?
Take a look at the MATLAB Code Profiler. Execute your code as follows:
>> profile on -history; MyCode; profile viewer
>> p = profile('info');
p contains the function history, From that same help page I linked above:
The history data describes the sequence of functions entered and exited during execution. The profile command returns history data in the FunctionHistory field of the structure it returns. The history data is a 2-by-n array. The first row contains Boolean values, where 0 means entrance into a function and 1 means exit from a function. The second row identifies the function being entered or exited by its index in the FunctionTable field. This example [below] reads the history data and displays it in the MATLAB Command Window.
profile on -history
plot(magic(4));
p = profile('info');
for n = 1:size(p.FunctionHistory,2)
if p.FunctionHistory(1,n)==0
str = 'entering function: ';
else
str = 'exiting function: ';
end
disp([str p.FunctionTable(p.FunctionHistory(2,n)).FunctionName])
end
You don't necessarily need to display the entrance and exit calls like the above example; just looking at p.FunctionTable and p.FunctionHistory will suffice to show when code enters and exits functions.
There are already a lot of answers to this question.
However, because I liked the question, and I love to procrastinate, here is my take at answering this (It is close to the approach presented by Dang Khoa, but different enough to be posted, in my opinion):
The idea is to run the profile function, along with a digraph to represent the data.
profile on
Main % Code to be analized
p = profile('info');
Now p is a structure. In particular, it contains the field FunctionTable, which is a structure array, where each structure contains information about one of the calls during the execution of Main.m. To keep only the functions, we will have to check, for each element in FunctionTable, if it is a function, i.e. if p.FunctionTable(ii).Type is 'M-function'
In order to represent the information, let's use a MATLAB's digraph object:
N = numel(p.FunctionTable);
G = digraph;
G = addnode(G,N);
nlabels = {};
for ii = 1:N
Children = p.FunctionTable(ii).Children;
if ~isempty(Children)
for jj = 1:numel(Children)
G = addedge(G,ii,Children(jj).Index);
end
end
end
Count = 1;
for ii=1:N
if ~strcmp(p.FunctionTable(ii).Type,'M-function') % Keep only the functions
G = rmnode(G,Count);
else
Nchars = min(length(p.FunctionTable(ii).FunctionName),10);
nlabels{Count} = p.FunctionTable(ii).FunctionName(1:Nchars);
Count = Count + 1;
end
end
plot(G,'NodeLabel',nlabels,'layout','layered')
G is a directed graph, where node #i refers to the i-th element in the structure array p.FunctionTable where an edge connects node #i to node #j if the function represented by node #i is a parent to the one represented by node #j.
The plot is pretty ugly when applied to my big program but it might be nicer for smaller functions:
Zooming in on a subpart of the graph:
I agree with the m2html answer, I just wanted to say the following the example from the m2html/mdot documentation is good:
mdot('m2html.mat','m2html.dot');
!dot -Tps m2html.dot -o m2html.ps
!neato -Tps m2html.dot -o m2html.ps
But I had better luck with exporting to pdf:
mdot('m2html.mat','m2html.dot');
!dot -Tpdf m2html.dot -o m2html.pdf
Also, before you try the above commands you must issue something like the following:
m2html('mfiles','..\some\dir\with\code\','htmldir','doc_dir','graph','on')
I found the m2html very helpful (in combination with the Graphviz software). However, in my case I wanted to create documentation of a program included in a folder but ignoring some subfolders and .m files. I found that, by adding to the m2html call the "ignoreddir" flag, one can make the program ignore some subfolders. However, I didn't find an analogue flag for ignoring .m files (neither does the "ignoreddir" flag do the job). As a workaround, adding the following line after line 1306 in the m2html.m file allows for using the "ignoreddir" flag for ignoring .m files as well:
d = {d{~ismember(d,{ignoredDir{:}})}};
So, for instance, for generating html documentation of a program included in folder "program_folder" but ignoring "subfolder_1" subfolder and "test.m" file, one should execute something like this:
m2html( 'mfiles', 'program_folder', ... % set program folder
'save', 'on', ... % provide the m2html.mat
'htmldir', './doc', ... % set doc folder
'graph', 'on', ... % produce the graph.dot file to be used for the visualization, for example, as a flux/block diagram
'recursive', 'on', ... % consider also all the subfolders inside the program folders
'global', 'on', ... % link also calls between functions in different folders, i.e., do not link only the calls for the functions which are in the same folder
'ignoreddir', { 'subfolder_1' 'test.m' } ); % ignore the following folders/files
Please note that all subfolders with name "subfolder_1" and all files with name "test.m" inside the "program_folder" will be ignored.