How can I make a string executable?
I'm 开发者_StackOverflow中文版trying to execute a string in Modelica. This string would be saved in a variable in order to be able to change it when I need to.
function Test
input String inComp="resistor.R:=2";
output String outComp;
algorithm
outComp:=inComp;
end Test;
Could you please
I am using Dymola.
What I need to do is the following.
-Read component names from a text file (or input them while executing the function) -Then change parameters of these components. This code is an example:
function Test
input String inComp="resistor"; //Entered by the user, or read from a text file
output Real result;
algorithm
inComp.R :=2 ; /*This is incorrect since it wouldn't understand that
I want to enter : resistor.R := 2; */
result := inComp.R ; //In order to view the result
end Test;
What you are trying to do is not generally possible in Modelica. It may be that some tools have a "reflective API" that allows this (or perhaps a built-in function that takes a command string and executes it) but there is certainly no universal API that works across tools.
If you want to run a bunch of simulations in Dymola with different parameter values, I can suggest at least three different wants to proceed.
- Use the DDE interface to send commands to Dymola. This way you can formulate the parameter values "somehow" (externally from Dymola) and then just request Dymola to run simulations. I'm not sure how rich the DDE interface is, so I'm not sure if it will do what you need (e.g. reaping results).
- Write a script file. This is a bit different from writing a function, but nearly the same in syntax. For example, to run the "CoupledClutches" example with several different inertia values, you can do this (in the command window):
for j in {1.0, 1.1, 1.2, 1.5, 1.8} loop J1.J := j; simulateModel("Modelica.Mechanics.Rotational.Examples.CoupledClutches", resultFile="CoupledClutches_"+String(j)); end for;
- Use a function (as you were) but call simulateModel with modifiers, e.g.
function RunLoop algorithm for j in {1.0, 1.1, 1.2, 1.5, 1.8} loop simulateModel("Modelica.Mechanics.Rotational.Examples.CoupledClutches(J1(J="+String(j)+"))", resultFile="CoupledClutches_"+String(j)); end for; end RunLoop;
- Use the built-in functions
simulateExtendedModel
andsimulateMultiExtendedModel
which actually do pretty much the same as above but in a cleaner way (typedocument("simulateExtendedModel")
anddocument("simulateMultiExtendedModel")
in the Dymola command window to get more info on these).
OK, that should give you a start. If none of those work for whatever reason, just update the question with whatever additional requirements you have.
A different option to use Perl etc. to dynamically write and execute some script. For example Text::Template
could be used as a templating engine. I do this for LaTeX regularly.
精彩评论