How to find the variables selected by the tearing algorithm in Dymola - modelica

I'd like to find the set of variables selected by the tearing algorithm in Dymola. so that I could know which variables link different parts of the system together. But I am not sure how to show these variables in Dymola. I checked the help document of Dymola but didn't find anything related to how to show these variables.

You should be able to see it in dsmodel.mof, which is created after setting Advanced.OutputModelicaCode = true; or activating it in the UI using "Simulation Setup -> Translation -> Generate listing of translated Modelica code in dsmodel.mof".
Dymola will generate the relevant code in the // Torn part. Searching for this in dsmodel.mof is a good option as the file can get pretty big.
The exact code will depend on the type of problem. Two examples:
(1) A rather simple electrical like this
will be solved symbolically, with the resulting code:
...
// Linear system of equations
// Tag: simulation.linear[1]
// Symbolic solution
/* Original equation
resistor1.v = constantVoltage.V-resistor.v-capacitor.v;
*/
resistor1.p.i := -(capacitor.v-constantVoltage.V+resistor.R_actual*
inductor.i)/(resistor.R_actual+resistor1.R_actual);
// Torn part
resistor.p.i := inductor.i+resistor1.p.i;
resistor.v := resistor.R_actual*resistor.p.i;
resistor1.v := resistor1.R_actual*resistor1.p.i;
// End of linear system of equations
...
In this case the tearing variable is resistor1.p.i, with the equation to compute it stated directly there.
(2) Translating Modelica.Thermal.FluidHeatFlow.Examples.TwoMass will give you a non-nonlinear case, i.e. when an iteration is needed to solve the system of equations. You should find something like:
...
// Start values for iteration variables of non-linear system of 1 equations:
// pipe2.V_flow(start = 0)
algorithm // Torn part
pipe2.flowPort_a.m_flow := pipe2.V_flow*pipe2.medium.rho;
pipe1.flowPort_a.m_flow := -(pipe2.flowPort_a.m_flow+ambient1.flowPort.m_flow);
...
The tearing variable is pipe2.V_flow in this case, with the start value for the iteration.

In Dymola 2021X, we could use Equation Incidence Browser to see which variables are used in the nonlinear equations, I guess these variables could be treated as tearing variables. And this works for commercial libraries, too. But it is a pity that Dymola 2021X doesn't allow showing details of nonlinear equations.

Related

How does Dymola choose the iteration variables during nonlinear system initialization process?

Assuming I have a very complicated thermal-fluid model built with Dymola. During the initialization process, how would dymola choose the iteration variables for the nonlinear solver? Is there a standard for this issue in dymola? I wanna make this clear, cause sometimes if the start values of the iteration variables are too far away from the right solution, there would be a divergence issue during the initialization process. I think if I could know the choice of iteration variables, I could make sure their values are appropriate instead of checking all the start values.
I think this information is not available to the public. At least I could not find anything in the user manuals. Therefore, you have only limited options.
What you can do is:
List your current iteration variables
Try to influence the selection
Get information on performed iterations
List iteration variables
You can list your current iteration variables by activating the flag
Advanced.LogNonLinearIterationVariables = true;
The iteration variables will be listed in the Translation tab as info message Variables appearing in the nonlinear systems of equations:
Influence selected variables
You can influence (but not control) the variables selected for iteration by setting start values. Take this code for example:
model MyNonLinear
Real x;
Real y;
Real z(start=-1);
equation
0 = y - z;
x = (y + z)^2;
x = (y + z) + time;
end MyNonLinear;
If you translate it with the above flag active, Dymola will give this information in the translation tab of the message window:
Iteration variables:
y
When you additionally set a start value for x, (e.g. start=1) x becomes the iteration variable in this case.
Information on performed iterations
To get more information on the performed iterations, activate the Nonlinear solver diagnostics flags in the Debug tab of the Simulation Setup:
Dymola will then display additional information in the simulation log. Note that some of these flags can generate a log of output.
This is possible via a very lightly documented feature. See the 2019 FD01 release highlights for some limited info: https://www.3ds.com/fileadmin/PRODUCTS/CATIA/DYMOLA/PDF/Dymola-2019FD01-highlights.pdf
Specifically:

Simulink S-Functions - Retrieve Initial Values from another S-Function

I'm trying to model the respective processes of an internal combustion engine. My current modelling approach is to have different sub functions which model the different processes.
Within each sub function is a Level 2 S-Function which solves the ODEs to give the in cylinder state (pressure, temperature, etc).
The problem that I'm having is that each sub function is enabled depending on the current crank angle which is computed from the current timestep in Simulink. The first process works fine as I manually set the initial values, but then I can't pass the latest in-cylinder state (the output from the first sub function) to the second sub function to use as the initial conditions (it insists on using the initial values I set at the beginning of the simulation).
Is there any way round this? Currently I'm going along a path of global data stores, but haven't had any joy so far.
There are a lot of different ways to solve this problem.
I'll show some of them as examples.
You can create additive output with Unit dalay block like this:
So you can get value of your crank angle from previous timestep and USE IT in formula for solving you equations.
Also you can use some code like this:
if (t == 0)
% equations with your initial values
sred = 0;
else
% equations with other values
y = uOld + myCoeef;
end
Another idea: sometimes I use persistent variables in Matlab function to save values of some variable from previous step. But I think it makes calculation slower.
One more idea - if you have Stateflow you can create chart with two states: first for initial moment with your coefficient and second to solve new equations.
If I understood you in wrong way you can show your code and we'll offer some new ideas!
P.S. Example of my using of S-Function:
My S-Function needs 2 values: Q is calculated in simulink at every step, ro is initial I took from big matrix I loaded from workspace in table and took necessary value depending of time.
So there is no any initial values in S-Function - all needed values I transmit into it from simulink!

Using coupled system of PDEs in modelica

Just few questions, i hope someone will find time to answer :).
What if we have COUPLED model example: system of n indepedent variables X and n nonlinear partial differential equations PDEf(X,PDEf(X)) with respect to TIME that depends of X,PDEf(X)(partial differential equation depending of variables X ). Can you give some advice? Here is one example:
Let’s say that c is output, or desired variable. Let’s say that r is independent variable.Partial differential equation looks like:
∂c/∂t=D*1/r+∂c/∂r+2(D* (∂^2 c)/(∂r^2 ))
D=constant
r=0:0.1:Rp- Matlab syntaxis, how to represent same in Modelica (I use integrator,but didn't work)?
Here is a code (does not work):
model PDEtest
/* Boundary conditions
1. delta(c)/delta(r)=0 for r=0
2. delta(c)/delta(r)=-j*d for r=Rp*/
parameter Real Rp=88*1e-3; // length
parameter Real initialConc=1000;
parameter Real Dp=1e-14;
parameter Integer np=10; // num. of points
Real cp[np](start=fill(initialConc,np));
Modelica.Blocks.Continuous.Integrator r(k=1); // independent x1
Real j;
protected
parameter Real dr=Rp/np;
parameter Real ts= 0.01; // for using when loop (sample(0,ts) )
algorithm
j:=sin(time); // this should be indepedent variable like x2
r.u:=dr;
while r.y<=Rp loop
for i in 2:np-1 loop
der(cp[i]):=2*Dp/r.y+(cp[i]-cp[i-1])/dr+2*(Dp*(cp[i+1]-2*cp[i]+cp[i-1])/dr^2);
end for;
if r.y==Rp then
cp[np]:=-j*Dp;
end if;
cp[1]:=if time >=0 then initialConc else initialConc;
end while;
annotation (uses(Modelica(version="3.2")));
end PDEtest;
Here are more questions:
This code don’t work in OpenModelica 1.8.1, also don’t work in Dymola 2013demo. How can we have continuos function of variable c, not array of functions ?
Can we place values of array cp in combiTable? And how?
If instead “algorithm” stay “equation” code can’t be succesfull checked.Why? In OpenModelica, error is :could not flattening model :S.
Is there any simplified way to use a set of equation (PDE’s) that are coupled? I know for PDEs library in Modelica, but I think they are complicated. I want to write a function for solving PDE and call these function in “main model”, so that output of function be continuos function of “c”.I don’t know what for doing with array of functions.
Can you give me advice how to understand Modelica language, if we “speak” like in Matlab? For example: Values of independent variable r,we can specife in Matlab, like r=0:TimeStep:Rp…How to do same in Modelica? And please explain me how section “equation” works, is there similarity with Matlab, and is there necessary sequancial approach?
Cheers :)
It's hard to answer your question, since you assuming that Modelica ~ Matlab, but that's not the case. So I won't comment your code, since it's really wrong. Let me give you an example model to the burger equation. Maybe you could use it as starting point.
model burgereqn
Real u[N+2](start=u0);
parameter Real h = 1/(N+1);
parameter Integer N = 10;
parameter Real v = 234;
parameter Real Pi = 3.14159265358979;
parameter Real u0[N+2]={((sin(2*Pi*x[i]))+0.5*sin(Pi*x[i])) for i in 1:N+2};
parameter Real x[N+2] = { h*i for i in 1:N+2};
equation
der(u[1]) = 0;
for i in 2:N+1 loop
der(u[i]) = - ((u[i+1]^2-u[i-1]^2)/(4*(x[i+1]-x[i-1])))
+ (v/(x[i+1]-x[i-1])^2)*(u[i+1]-2*u[i]+u[i+1]);
end for;
der(u[N+2]) = 0;
end burgereqn;
Your further questions:
cp is an continuous variable and the array is representing
every discretization point.
Why you should want to do that, as far as I understand cp is
your desired solution variable.
You should try to use almost always equation section
algorithm sections are usually used in functions. I'm pretty
sure you can represent your desire behaviour with equations.
I don't know that library, but the hard thing on a pde is the
discretization and the solving it self. You may run into issues
while solving the pde with a modelica tool, since usually
a Modelica tool has no specialized solving algorithm for pdes.
Please consider for that question further references. You could
start with Modelica.org.

Getting the solver type and step size (for fixed step solvers)

we are trying to integrate a simulation model into Simulink as a block. We have a custom continuous block which loads an m file that contains the functions Derivatives, Outputs etc.
My question is: is there a way to find out which solver is used currently and with which parameters? Our model won't be able to support variable time solvers and I would like to give a warning. Similarly, the model requires the fixed step time for initialization.
Thanks in advance.
You can get the current solver name using
get_param('modelName', 'SolverName');
Some of the other common solver parameters are
AbsTol
FixedStep
InitialStep
ZcThreshold
ExtrapolationOrder
MaxStep
MinStep
RelTol
SolverMode
You can find other parameters you may wish to query by opening the .mdl file in your favorite text editor and digging through it.
If I'm understanding your use case correctly, you are trying to determine the type of solver (and other solver params) for the top-level simulink system containing your block.
I think the following should give you what you want:
get_param(bdroot, 'SolverType'); % //Returns 'Variable-step' or 'Fixed-step'
get_param(bdroot, 'FixedStep'); % //Returns the fixed step size
Notice that for purposes of generality/reusability, this uses bdroot to identify the top-level system (rather than explicitly specifying the name of this system).
If you want to find out more about other model parameters that you can get/set, I would check out this doc.
Additionally, I'm interested to know why it is that your model doesn't support a variable-step solver?

Modelica execution order

Just starting with Modelica and having trouble understanding how it works.
In the below 'method' of the model, qInflow and qOutflow are used in the second line to evaluate der(h), but they have not received a value yet! (they were not defined in the 'data' of the method)? In what order is the code executed.
equation
assert(minV >= 0, "minV must be greater or equal to zero");
der(h)=(qInflow - qOutflow)/area;
qInflow=if time > 150 then 3*flowLevel else flowLevel;
qOutflow=Functions.LimitValue(minV, maxV, -flowGain*outCtr);
error=ref - h;
der(x)=error/T;
outCtr=K*(error + x);
end FlatTank;
From http://www.mathcore.com/resources/documents/ie_tank_system.pdf
This is an understandable point of confusion when coming from languages and systems that utilize imperative semantics. But Modelica doesn't work like that.
When working with Modelica it is important to understand that an equation section contains equations, not assignments. Consider this, if I gave you the following equations:
x + y = 3;
x + 2*y = 5;
If you understand that this is a mathematical context, you can then determine that x must have a value of 1 and y must have a value of 2. In other words, you have to solve a system of simultaneous equations. You'll note that the left hand side of these equations are not variables (in general), they are expressions. An equation is simply a relationship that equates one expression, on the left hand side, with another expression, on the right hand side. Furthermore, this relationship is always true and so order is irrelevant.
This is quite different from imperative programming languages with imperative semantics. But it is also very powerful because you can state these relationships (linear systems of equations, non-linear systems of equations, implicit equations, etc) and the compiler will work out the most efficient way to solve them.
Getting back to your example, when you look at the code in your question you are interpreting those equations as assignment statements. This notion is reinforced because they just happen to have variables on the left hand sides. But they are really equations. In an equation based system, you do not worry about whether a given variable has been assigned to previously. Instead, the requirement is simply that for every variable there exists (somewhere) an equation and that there are no extra equations. In other words, you should have the same number of variables as unknowns and that the system of equations has a unique solution. That is all that Modelica requires.
Now, Modelica supports the kind of imperative semantics you are used to. But they are only to be used in special cases because they constrain the interpretation of the mathematical behavior in such a way that it interferes with the symbolic manipulation that allows Modelica compilers to generate really fast code. So it is more than a question of style. You should use equations if at all possible and algorithms in Modelica should only be used as a last resort.
One last note. Some people may be wondering "Are you telling me that these equations will be put into some giant system of equations and solved by matrix inversion or Newton-Raphson or something? Why make it so complicated when it could obviously be solved in a much easier way!" But it will not be solved as a giant system of equations. If it can be solved as a simple set of assignments it will. That is one (among many) of the different symbolic manipulation techniques that will be applied. In fact, this is a key point about Modelica...you don't need to worry about optimizing the solution method, the tool will take care of that. And more importantly, if you connect components in such a way that a simultaneous system does arise, you don't need to worry about that either. Modelica tools can handle such "algebraic loops" for you, they will optimize it to find the most computationally efficient formulation and won't depend on you reformulating your model for those cases.
Does that help?
You cannot know the execution order of the equations in a Modelica model until you run a Modelica tool on it (you can re-order any equation in the source model and get the same result). And then the order is only true for this tool with the settings you used.
This was the order chosen by the OpenModelica compiler (omc +s +simCodeTarget=Dump model.mo):
error = ref - h;
outCtr = K * (error + x);
der(x) = DIVISION(error, T, #SHARED_LITERAL_2(String#);
qOutflow = LimitValue(minV, maxV, (-flowGain) * outCtr);
qInflow = if time > 150.0 then 3.0 * flowLevel else flowLevel;
der(h) = DIVISION(qInflow - qOutflow, area, #SHARED_LITERAL_3(String#);
This example was a little boring because the left and right sides of no equation changed place (h = error - ref would be viable if h was not chosen as a state variable, etc).