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.
Related
In order to make my model simulation's in Modelica run faster am asking the following quesion :
What does impact simulation runtime in Modelica ?
i will aprecicate any help possible.
Edit: More details can be consulted from my book "Modelica by Application -- Power Systems" (URL)
What does impact the runtime performance?
I. Applied compilation techniques
Naturally, object-oriented Modelica models, even trivial ones, would correspond to a large-scale system of equations. Modelica simulation environments would usually optimize such generated models:
reduce the number of possible equations by removing trivial ones (i.e. alias equations)
decompose a large-block of equation system with so called BLT-transformation into smaller cascaded blocks of equation systems that can be solved faster in a sequential manner and not as a single block of equations,
solve s.c. large algebraic loops using tearing methods.
It can theoretically even go too far and attempt to solve blocks of equation system in an analytical manner if possible instead of conducting expensive numerical integration
Thus, the runtime performance would be influenced by the underlying Modelica compiler and how far does it exploit equation-based compiler methods. Usually some extra settings need to be activated to exploit all possible kind of such techniques. Digging the documentation to enable such settings is needed.
II. The nature of the model
The nature of the model would influence the runtime performance, particularly:
Is the model a large-scale system? or a small-scale one?
Is it strongly nonlinear or semi-linear one?
Is the resulting optimized equation system corresponding to the model sparse (i.e. large set of equations each with few number of variables, e.g. power system network models) or dense (e.g. multibody systems and biochemical networks)
Is it a stiff system? (e.g. a system with several subsystems some exhibiting very quick dynamics and others very slow dynamics)
Does the system exhibit large number of state events
...
III The choice of the solver
The mentioned characteristics of a given model would typically influence the ideal choice of the solver. The solver can largely influence the runtime performance (and accuracy). A strategy for solver choice could be made in the following order:
For a non-stiff weakly nonlinear model, the ideal choice would be an explicit method, e.g. Single-step Runga-Kutta or Multi-step Adam-Bashforth of higher order. If accuracy is less significant, one can attempt an explicit method of a lower order which would executes faster. Naturally, increasing the solver error tolerance would also speed-up the simulation.
However, it could happen, particularly for large-scale systems, that numerical stability could be more difficult to guarantee. Then, smaller solver step-sizes (and/or smaller error tolerance) for explicit solvers should be attempted. In this case, an implicit solver with larger error tolerance can be comparable with an explicit solver with a smaller tolerance.
Actually, it is wise to try both methods, comparing the accuracy of the results, and figuring out if explicit methods produce comparably accurate results. However, as a warning this would be just a heuristic, since the system does not necessarily have the same behavior over the entire space of admissible parameter values.
For increasing nonlinearity of the model, the choice would tend more towards modern solvers making use of variable step-size techniques. Here I would start with implicit variable-step Runga-Kutta (i.e. single-step) and/or the implicit variable-step multi-step methods, Adams–Moulton. For both of these classes, one can enlarge the solver tolerance and/or lower the solver error order and figure out if the simulation produces comparably accurate solutions (but with faster runtime).
Implementations of the previous classes of methods are usually less conservative with error control, and therefore, for increasing stiffness of the model or badly scalable models, the choice would tend more towards modern solvers implementing so-called numerically more stable backward differentiation formula (BDF), s.a. DASSL, CVODE, IDA. These solvers (can) also make use of the s.c. Jacobian of the system for adaptive step-size control.
A modern solver like LSODAR that switches between explicit and implicit solvers and also perform automatic error order control (switching between different orders) is a good choice if one does not know that much information about the behavior of the model. May be some Modelica environments have an advanced solver making use of automatic switching. However, if one knows the behavior of the model in advance, it is also wise to use other suggested methods since LSODAR may not perform the most optimal switching when needed.
x. ...
The comparisons between solvers from classes 3,4 and 5 are not straightforward to judge and it depends also on whether the system is continuous or hybrid, i.e. the underlying root-finding algorithms.
Usually DASSL could be slower as it is more conservative with step-size/error control. So it seems that IDA and others are faster. Some published works exist that can give some intuitions regarding such comparisons. It would be nice to have a Modelica library including all possible types of models and running all possible benchmarks w.r.t. accuracy and runtime to draw some more solver/model specific conclusions. A library that could be used and extended for such a purpose is the ScalableTestSuite Modelica library.
IV. Advanced aspects
There have been some published works in the Modelica community regarding making use of sparse solvers to exploit the expected sparsity of the Jacobian. If such a feature is provided by the simulation environment, this would usually significantly improve the runtime performance of large-scale models.
For models with massive number of events, numerical integration in the standard way can be extremely inefficient. Particularly challenging is when an event is triggered, other sets of state-events could be further triggered and a queue of state-events should be evaluated. The root-finding algorithm could further trigger other events and the solver could be hanging on in a s.c. chattering situation. There are advanced strategies for such situations, s.c. sliding mode, however I am not sure how far Modelica simulation environments are handing this issue.
One set of suggested solutions (also for systems with high degree of stiffness) is to employ so called QSS (quantized state system) methods. This would be significantly beneficial particularly for models that can not be solved using explicit solvers. There are both explicit and implicit QSS methods. There have been also other worth-to-try numerical integration strategies where only subsets of the entire equation system is evaluated when approximating a state event. Here I am not sure about availability of such solvers.
Some simulation environments differentiate between two simulation modes which can influence the simulation runtime: the ODE Mode and DAE Mode. In the first mode, the system is reduced to an ODE system with potentially additional cascaded blocks of nonlinear equation systems. In the DAE mode, the system is reduced to a DAE system of index one. The former mode would be beneficial for dense systems exhibiting such large cascaded blocks of nonlinear equations to be solved using s.c. Tearing methods instead of numerical integration. The DAE mode would be beneficial for large-scale sparse systems solved using sparse solvers. I think the ODE mode is usually activated by choosing CVODE or LSODAR while DAE mode is activated by choosing IDA or DASSL. But digging the documentation here and there is also recommended.
There are also some published works regarding so called multirate numerical integration solvers. Here, in each numerical integration step, only the numerically-significant portion of the equation system and not the entire equation system is integrated. Hence, this is significantly beneficial for large-scale stiff systems.
x. ...
V. Parallelization
Obviously, making use of multicore / GPUs for executing numerical integration in parallel, among other approaches for applying parallelization can speed-up computations.
VI. quite very advanced topics
In order to pay attention at some excellent research attempts some of which can be exploited for speeding up the simulation runtime performance of large-scale (loosely-coupled) hybrid networked models, I am listing this here as well. Speed-up can be obtained by making use of hybrid paradigms, agent-based modeling paradigm and/or multimode paradigm. The idea behind is that it is possible to describe a loosely coupled system in several smaller subsystems and conduct the communication among subsystems only when necessary. This can be beneficial and the reasons can be traced by searching for relevant publications. There have been some excellent work in some of the mentioned directions, and it is worth to continue them where they have stopped if this is the case.
Remark: Any of the mentioned solvers is not necessarily present in all possible Modelica simulation environments. If a solver is not provided as a choice, one would still be able to produce an FMU-ME (Functional mockup unit for model exchange) and write code that numerically integrate this FMU with a desired solver.
Warning: Some of the above aspects are based on personal experiences for a particular type of models and are not necessarily true for all model types.
Few suggested reading and I am definitely missing a lot of key publications:
F. Casella, Simulation of Large-Scale Models in Modelica: State of the Art and Future Perspectives, Modelica 2016
Liu Liu, Felix Felgner and Georg Frey, Comparison of 4 numerical solvers for stiff and hybrid systems simulation, Conference 2010
Willi Braun, Francesco Casella and Bernhard Bachmann, Solving large-scale Modelica models: new approaches and experimental results using OpenModelica, Modelica 2017
Erik Henningsson and Hans Olsson and Luigi Vanfretti, DAE Solvers for Large-Scale Hybrid Models, Modelica 2019
Tamara Beltrame and François Cellier, Quantised state system simulation in Dymola/Modelica using the DEVS formalism, Modelica 2006
Victorino Sanz and Federico Bergero and Alfonso Urquia, An approach to agent-based modeling with Modelica, Simpra 2010
I got a model working fine with the following controlling system parameters,
but if I change one of the parameters, the system would be stiff and no chance to solve it at all.
So my question is:
Why changing just one parameter would cause the system stiff?
If I meet the stiff problem again, how could I locate the exact parameter that causes the problem?
DASSL is an implicit solver and should therefore be able to deal with stiff systems pretty well. Still it seems there are many >500 steps it has to do within <2s, as this is your output interval (which causes the message). In your case this could relate to fast dynamics that happen within the model.
Regarding your questions:
If the model simulates to the end, check the controlled variables and see if the have fast oscillations (Frequency of > 100Hz) occur. This can happen when increasing the proportional gain of the controller, which is making the overall system "less stable".
A general advice on this is pretty difficult, but the linearSystems2 library can help. Creating a "Full Linear Analysis" gives a list of states and how they correlate to poles. The poles with highest frequency are usually responsible for the stiffness and from seeing which states relate to poles of interest, indicates which states to investigate. The way from the state to the parameter is up to the modeler - at least I don't know a general advice on this.
For 2. applied to Modelica.Blocks.Examples.PID_Controller the result looks like:
Seeing that likely the spring causes the fastest states in the system.
The answer is yes! Changing only one parameter value may cause the system to be stiff.
Assuming that a given model maps to an explicit ODE system:
dx/dt = f(x,p,...)
Conventionally, a system can be characterized as stiff via some stiffness indices expressed in terms of the eigenvalues of the Jacobian df/dx. For instance, one of these indices is the stiffness ratio: the ratio of the largest eigenvalue to the smallest eigenvalue of the Jacobian. If this ratio is large, some literature assume > 10^5, then the system is characterized to be stiff around the chosen initial and the parameter values.
The Jacobian df/dx as well as its eigenvalues is a time-dependent function of p and initial values. So theoretically and depending on the given system, one single parameter could be capable of causing such undesired system behavior.
Having a way to access the Jacobian and to perform eigenvalue analysis together with parametric sensitivity analysis, e.g. via computation of dynamic parameter sensitivities, identifying such evil parameters is possible.
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.
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.
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)