Dymola solving stationary equation systems for Media-Model - modelica

I'm building a Media-Library in Dymola similar to Helmholtz-Media but for Ammonia+Water, a mixture.
You get a lot of not explicitly solvable equations.
Because of the structure of the Media and Fluid libraries in Modelica I need to be able to get my thermodynamic state from p, h and x. The state-vector consists of d, T, and x.
This is a simple example how to get the state-vector:
model getState_phX
parameter AbsolutePressure p = 500000 "pressure";
parameter SpecificEnthalpy h = 2500000 "enthalpy";
parameter SI.MassFraction x = 0.7 "mole fraction of amonia";
parameter Real[2] start = getStart_Td_phx(p,h,xL);
output ThermodynamicState state(d(start=start[2]),T(start=start[1]),X={(1 - xL),xL});
DerivateFull f = Derivates(state);
equation
p = (1 + f.delta*f.phirdelta)*R*state.T*state.d/molarMass(state);
h = state.T*R*(1 + f.delta*f.phirdelta + f.tau*f.phirtau + f.tau0*f.phi0tau0)/molarMass(state);
end getState_phX;
Please don't mind the parts of the equations. They consist of many parts (sums and log) dependent on the state-vector.
This is solved by the solver in Dymola with good start values.
But I don't really need all of the 'time-dependent' solving capabilities of Dassl.
Are there build in libraries for solving such stationary equation systems without the solver?
Is it possible to make a Function out of this Model using these?
I know I could write a simple solver by hand but for other parts of the Media-Model (VLE) I need highly reliable stationary solver too (but with 4 nonlinear independent equations)
Please tell me if I didn't explain myself clearly. Thank you for the help.

The basis of your fluid properties library is a forward part, that is the actual Helmholtz energy equation of state (EoS). It takes d,T,X as input. That part is more or less straigthforward to implement.
If you want to specify the thermodynamic state using p,h,X or if you want to find the equilibrium between multiple phases, you will usually set up a system of resdiual functions and try to find the root of your system of equations using some iterative procedures. Span (2000) writes
"the formulation of reliable iterative procedures [for root finding]
is often the most crucial problem when setting up program packages for
the evaluation of equations of state".
Re-using existing solvers has advantages and disadvantages, they are usually very well tested, writing them takes a lot of effort, but if you write your own solver, you have more control about what it does. As far as I know, Dassl has various strength, but solving that kind of equations is not its original objective.
Olson, Tummescheit and Elmqvist (2005) tried to use the Dymola solver to find the VLE, see section 3.2 of the linked pdf. Sounds like it works, but not very reliable.
The MSL already includes a non-linear solver, based on the Brent algorithm, which works with one unknown only, see Modelica.Math.Nolinear.solveOneNonlinearEquation. You could, if you want, add additional generic solvers.
Before writing your own solver, you should get in touch with the developers of the Modelica.Media interface (it will be extended in future versions of the MSL to include multi-component, multi-phase mixtures) and also consider re-using existing fluid properties libraries like RefProp, CoolProp, FluidProp or MultiFlash, to name just a few.

Related

An error of using multi-mode DAEs in Dymola

I build a simple model in Dymola, using different equations during different periods, but it surprises me that Dymola could NOT handle this simple model. It seems the system is singular after index reduction.
My questions are:
Is this a usual question when using Modelica?
If so, how should I modify this model, I know when I replace the equation x=100 with der(x)=0, the model works fine, but I am wondering if there is a universal rule for more complicated cases. I would appreciate it if a detailed explanation provided.
Here is the code of the model:
model ErrorWhenUsingIf
Real x(start=100);
equation
if time<=0.5 then
x=100;
else
der(x)=5;
end if;
end ErrorWhenUsingIf;
The error message is :
Failed to evaluate model for ODE-Jacobian
Error: The following error was detected at time: 7.62939453125E-012
Error: Singular inconsistent scalar system for der(x) = ( -(if time <= 0.5 then x-100 else -5.0))/((if time <= 0.5 then 0.0 else 1.0)) = 8e-008/0
Solver will attempt to handle this problem.
Failed to evaluate model for ODE-Jacobian
The given model does not obey one of the current rules following the common typical straight-forward approach for realizing simulate-able / compilable Modelica models:
a model shall not change its differential index throughout the
simulation
Realizing such models is not explicitly prevented by the actual version of Modelica language specification guide and there is nothing against realizing that.
Common simulation environments won't simulate apparently such a simple model, unless it is explicitly stated that multi-modes of DAEs are allowed.
Now going a bit into details, the differential index informally corresponds to the inherent degree of implicit / explicit dependencies among state variables. There are two ways a differential index can change throughout the simulation, a structural way or numerical way.
In the structural way, the model (similar to the given one) is stated in terms of several branches of equation systems. Each branch corresponds to a different differential index. In the given model, a branch corresponds to a linear equation while the other corresponds to a differential equation. A typical implementation of structural analysis would reveal that the model corresponds to an ODE system (which is not true for the first branch). My guess here is that the linear equation is submitted to the ODE solver. If we add a dummy differential equation outside the if condition such as der(z) = -1, the system will be simulated since the structural analysis is accidentally (semi-)correct.
If we are dealing with higher-index DAEs in different branches, we may get a numerically imprecise solution, since the index reduction is not seperately conducted for each possible branch. Applying the solver to a non-reduced DAE may cause a draft in the numerical solution since an implicit algebraic equation was not explicitly revealed in the resulting reduced equation that is passed to the solver.
In the numerical way there are cases where different values of model parameters lead to different differential indices (think about a parameter value that changes a sophisticated equation to a trivial one). Similarly, the differential index may change its value during simulation runtime. This type is difficult to capture using the common ways of treating higher-index differential equations.
The structural index:The common approach is to approximate the differential index using s.c. structural index: which is a graph-based representation of the equation system out of which the differential index can be approximated. An ODE system has a structural index 0 while a non-differential equation system has a structural index -1. Index reduction is conducted using a combination of Pantelides algorithm and dummy derivatives methods, cf. relevant literatures. Such graph-based methods don't capture the numerical aspects of a varying differential index that is not the same during a simulation or different values of parameters.
Multi-modes DAEs, resulting from both types, are subject to active research and there have been novel publications dealing with multimode DAEs, cf. Hilding Elmqvist' publications at Modelica conferences and journals among other related publications to multi-mode DAEs (As a note I am not identifying what is the best publication regarding this topic).
If there is a universal role to follow, then this would be that all branches of a model should have the same structural index (and ideally the same differential index during a simulation). In the former, the structural index can be easily approximated by the modeler for small models. For large models, it is beneficial if the simulation environment can dump information regarding the graph-based structure (i.e. computational graph) of a given model, its differential index, etc. In the later type, this is difficult for the modeler to capture. It is ideal if the simulation environment can dump such information regarding a numerically varying differential index.
This is related to the ongoing discussion of https://github.com/modelica/ModelicaSpecification/issues/2411, where (in Modelica Language Specification version 3.4) it is not specified if variable-structure models are legal or rather tool-specific or illegal. There are tools (and proof of concepts) with DAE solvers that can successfully simulate such models.

How to solve this system of differential equations in matlab?

My task is to model a certain physical problem and use matlab to solve it's differential equations. I made the model but it seems far more complex than what I've learned so far so I have no idea how to solve this.
The black color means it's a constant
I assume that by "solve" you seek a closed form solution of the form x(t) = ..., z(t) = ... Unforunately, it's very likely you cannot solve this system of differential equations. Only very specific canonical systems actually have a closed-form solution, and they are the most simple (few terms and dependent variables). See Wikipedia's entry for Ordinary Differential Equations, in particular the section Summary of exact solutions.
Nevertheless, the procedure for attempting to solve with Matlab's Symbolic Math Toolbox is described here.
If instead you were asking for numerical integration, then I will give you some pointers, but you must carry out the math:
Convert the second order system to a first order system by using a substitution w(t) = dx/dt, allowing you to replace the d2x/dt2 term by dw/dt. Example here.
Read the documentation for ode15i and implement your transformed model as an implicit differential equation system.
N.B. You must supply numerical values for your constants.

Managing of Navier-Stokes PDEs by means of SBF in Dymola

Has anyone tried to implement the Navier Stokes Partial Differential Equations (PDE) in Modelica?
I found the method of the spatial basis functions (SBF) which by means of numerical modifications gets Ordinary Differential Equations (ODE) that could be handled by Dymola.
Regards,
Victor
The aim of the method I was saying before is to convert PDEs in ODEs, so the issues with the CFL coefficient would disappear, the problem is that the Modelica.Fluids elements just define the equations in function of the variables in both ends of each component.
i.e dp=port_a.p-port_b.p
but with that sort of methodology, the variables such as pressure, density, mass flow... would be function also of the surrounding components... it would be a kind of massive interaction between all the components,
I would like to see an example in Modelica, because I hardly haven't found information about that topic linked to Modelica.
Modelica is a language for modeling behavior described by DAEs. As such, as long as you can create a system of ODEs, you should be able to express your problem in Modelica.
However, if your PDEs are hyperbolic, the wave dynamics in the equations might cause some issues with simulation. This is because the CFL condition imposes limits on time steps that an ordinary differential equation solver will be unaware of. If the solver includes error control, it will probably manage to get a solutions but may run quite slow because it won't know how to explicitly limit the simulation step size. If it doesn't include error control and it violates the CFL condition, the system will go unstable. Note, this only applies to systems where the CFL condition applies.

Using a non-matlab ODE simulator to run a model created in matlab/simbiology - how to represent "repeated assignment" rules?

I am using non-matlab ODE simulation software to reproduce a model that was created with the simbiology toolbox in matlab.
One issue is the representation of repeated assignments. Is it possible to re-express repeated assignments in a way that they can be simulated in a standard Runge Kutta (or other iterative method) which only supports ODE systems? Or is it impossible re-express a model with repeated assignments as a system of ODEs?
It is possible. In SimBiology, for most repeated assignments, you can take the assignment statement
x = y + z
and think of it as
dx/dt = dy/dt + dz/dt
and you could integrate that state. That may be the simplest way to implement what you have, keeping in mind that if you have some more complicated function that makes the assignment, you will have to carryout the chain rule correctly.
This is not how repeated assignments are handled in SimBiology. When putting together the solvers in SimBiology we can manipulate both the right hand side of the system of differential equations and the solution of the states. We implement something a bit better from the perspective of ODE solution accuracy and speed of solution, but without knowing more about your solver, I can't advise you on how to proceed.
--Andrew
(one of the SimBiology devs)

Solving a non-polynomial equation numerically

I've got a problem with my equation that I try to solve numerically using both MATLAB and Symbolic Toolbox. I'm after several source pages of MATLAB help, picked up a few tricks and tried most of them, still without satisfying result.
My goal is to solve set of three non-polynomial equations with q1, q2 and q3 angles. Those variables represent joint angles in my industrial manipulator and what I'm trying to achieve is to solve inverse kinematics of this model. My set of equations looks like this: http://imgur.com/bU6XjNP
I'm solving it with
numeric::solve([z1,z2,z3], [q1=x1..x2,q2=x3..x4,q3=x5..x6], MultiSolutions)
Changing the xn constant according to my needs. Yet I still get some odd results, the q1 var is off by approximately 0.1 rad, q2 and q3 being off by ~0.01 rad. I don't have much experience with numeric solve, so I just need information, should it supposed to look like that?
And, if not, what valid option do you suggest I should take next? Maybe transforming this equation to polynomial, maybe using a different toolbox?
Or, if trying to do this in Matlab, how can you limit your solutions when using solve()? I'm thinking of an equivalent to Symbolic Toolbox's assume() and assumeAlso.
I would be grateful for your help.
The numerical solution of a system of nonlinear equations is generally taken as an iterative minimization process involving the minimization (i.e., finding the global minimum) of the norm of the difference of left and right hand sides of the equations. For example fsolve essentially uses Newton iterations. Those methods perform a "deterministic" optimization: they start from an initial guess and then move in the unknowns space essentially according to the opposite of the gradient until the solution is not found.
You then have two kinds of issues:
Local minima: the stopping rule of the iteration is related to the gradient of the functional. When the gradient becomes small, the iterations are stopped. But the gradient can become small in correspondence to local minima, besides the desired global one. When the initial guess is far from the actual solution, then you are stucked in a false solution.
Ill-conditioning: large variations of the unknowns can be reflected into large variations of the data. So, small numerical errors on data (for example, machine rounding) can lead to large variations of the unknowns.
Due to the above problems, the solution found by your numerical algorithm will be likely to differ (even relevantly) from the actual one.
I recommend that you make a consistency test by choosing a starting guess, for example when using fsolve, very close to the actual solution and verify that your final result is accurate. Then you will discover that, by making the initial guess more far away from the actual solution, your result will be likely to show some (even large) errors. Of course, the entity of the errors depend on the nature of the system of equations. In some lucky cases, those errors could keep also very small.