Achieving a tunable parameter in OpenModelica - openmodelica

I have the following Modelica code
model RocketCar
Real x;
Real v;
input Real u(min = -1, max = 1);
parameter Real h;
equation
der(x) = h*v;
der(v) = h*u;
end RocketCar;
meant to model the infamous rocket car problem, which I would like to transform into an FMU.
I transform the file using OMShell:
>>> loadFile("RocketCar.mo")
true
>> translateModelFMU(RocketCar)
"/path/to/RocketCar.fmu"
The resulting FMU lists the variable as
<ScalarVariable
name="h"
valueReference="10"
variability="fixed"
causality="parameter"
initial="exact">
<Real start="0.0"/>
</ScalarVariable>
i.e., as a fixed parameter. I would like to change the Modelica code to obtain a tunable parameter in the resulting FMU.
Note that a similar question has been asked and answered already. The suggested solution was to add annotation (Evaluate=false) to the definition of the parameter. However, this answer seems to be specific to Dymola. The suggested annotation seems to have no effect regarding the resulting FMU. Is there an OpenModelica variant of the annotation to achieve the same effect?

Related

Eigen and parallellization makes no difference for conjugate gradient. Precondition also fails

This is related to this question. I have today experimented a bit with Conjugate Gradient, in particular I experimented with max_iterations and tolerance. It is faster but not fast enough. According to the documentation it should be enough to add -fopenmp in the compilation to enable multi-threading.
I have tested using both
`omp_set_num_threads(nbrThreads);
Eigen::setNbThreads(nbrThreads);`
It makes no difference in time if I use 5 threads or 1 thread, and that I think is a bit strange.
Secondly, another way to speed up the solution using pre-conditoning. When I try to do:
Eigen::ConjugateGradient<Eigen::SparseMatrix<float>, Eigen::Lower, Eigen::IncompleteCholesky<float>> cg;
I get the error:
void Eigen::IncompleteCholesky<Scalar, _UpLo, _OrderingType>::_solve_impl(const Rhs&, Dest&) const [with Rhs = Eigen::Matr
ix<float, -1, 1>; Dest = Eigen::Matrix<float, -1, 1>; Scalar = float; int _UpLo = 1; _OrderingType = Eigen::AMDOrdering<int>]: Assertion `m_factorizationIsOk && "factorize() should be called first"' failed.
Given that Eigen::SimplicialLDLT works which is a Cholesky factorization, then the incomplete should also work?
EDIT:
Here is how I call cg:
Eigen::ConjugateGradient<Eigen::SparseMatrix<float>, Eigen::Lower, Eigen::IncompleteCholesky<float>> cg;
cg.setTolerance(0.01);
cg.setMaxIterations(50);
cg.analyzePattern(A_tot);
cg.compute(A_tot);
Eigen::VectorXf opt = cg.solveWithGuess(b_tot, rho_current);
Actually when you read about IterativeSolvers here, then IncompleteCholesky is not listed. Although IncompleCholesky is defined here.
As explained in the documentation, you need to store the full matrix (both upper and lower triangular part), and pass Lower|Upper to ConjugateGradient to get multi-threading with cg.
The problem seems to be that I had an beta-version of Eigen installed. It runs with pre-conditioner using Eigen 3.3.2

Robust higher statistical moments in IDL

I'm working with noisy data in IDL, so I've been using STDDEV and robust_sigma
. There are papers on robust skewness and kurtosis, for instance [1] and [2], but are there implementations, as for standard deviation? (in IDL or maybe C?)
The documentation of http://idlastro.gsfc.nasa.gov/ftp/pro/robust/robust_sigma.pro states:
; OPTIONAL OUPTUT KEYWORD:
; GOODVEC = Vector of non-trimmed indices of the input vector
So one calls robust_sigma with an extra parameter that keeps track of the "good indices" in the data, those used to compute the robust_sigma, as opposed to those ignored in its computation.
good_indices = lonarr(width)
robo_2 = robust_sigma(data[*], GOODVEC=good_indices)
Then use (only) those good indices to compute the other moments.
robo_3 = skewness(data[good_indices])
robo_4 = kurtosis(data[good_indices])
No need for a special implementation.

absolute value in cplex c++

I have to use absolute value in the cost function of some linear problem.
Part that bother me like this
for (t=0;t<T;t++)
for (i=0;i<I; i++){
for (j=1;j<J; j++)
Sum += |x[i][j][t]-x[i][j][t-1]|*L/2;
Sum += |x[i][0][t]-x[i][0][t-1]|*V/2;
}
I am writing my code in c++ and I don't know how to implement absolute value. x is integer value.
I have tried with cplex.getValue(x[i][j][t])-cplex.getValue(x[i][j][t-1]) >0 but it couldn't work.
Since the absolute value function is nonlinear ( the reason is explained in this math question ) you need to linearize the objective function first.
Basically, you need to express each absolute-valued-term of that summation with a new variable and optimize the sum of these new variables (subject to some additional constraints). The method is explained in detail in Section 7.2 of Linear Programming textbook of Thomas S. Ferguson.

Modelica Time Dependent Equations

I am new to Modelica, and I am wondering if it is possible to write a kind of dynamic programming equation. Assume time is discretized by an integer i, and in my specific application x is boolean and f is a boolean function of x.
x(t_i) = f(x(t_{i+d}))
Where d can be a positive or negative integer. Of course, I would initialize x accordingly, either true or false.
Any help or references would be greatly appreciated!
It is possible. In Modelica the discretization in time is usually carried on by the compiler, you have to take care of the equations (continous dynamics). Otherwise, if you want to generate events at discrete time points, you can do it using when statements.
I suggest you to take a look at Introduction to Object-Oriented Modeling and Simulation with OpenModelica (PDF format, 6.6 MB) - a more recent tutorial (2012) by Peter Fritzson. There is a section that on Discrete Events and Hybrid Systems, that should clarify how to implement your equations in Modelica.
Below you can find an example from that tutorial about the model of a bouncing ball, as you can see discretization in time is not considered when you write your dynamic equations. So the continous model of the ball v=der(s), a=der(v) and than the discrete part inside the when clause that handles the contact with the ground:
model BouncingBall "the bouncing ball model"
parameter Real g=9.81; //gravitational acc.
parameter Real c=0.90; //elasticity constant
Real height(start=10),velocity(start=0);
equation
der(height) = velocity;
der(velocity)=-g;
when height<0 then
reinit(velocity, -c*velocity);
end when;
end BouncingBall;
Hope this helps,
Marco
If I understand your question, you want to use the last n evaluations of x to determine the next value of x. If so, this code shows how to do this:
model BooleanHistory
parameter Integer n=10 "How many points to keep";
parameter Modelica.SIunits.Time dt=1e-3;
protected
Boolean x[n];
function f
input Integer n;
input Boolean past[n-1];
output Boolean next;
algorithm
next :=not past[1]; // Example
end f;
initial equation
x = {false for i in 1:n};
equation
when sample(0,dt) then
x[2:n] = pre(x[1:(n-1)]);
x[1] = f(n, x[2:n]);
end when;
end BooleanHistory;

Is it possible to do an algebraic curve fit with just a single pass of the sample data?

I would like to do an algebraic curve fit of 2D data points, but for various reasons - it isn't really possible to have much of the sample data in memory at once, and iterating through all of it is an expensive process.
(The reason for this is that actually I need to fit thousands of curves simultaneously based on gigabytes of data which I'm reading off disk, and which is therefore sloooooow).
Note that the number of polynomial coefficients will be limited (perhaps 5-10), so an exact fit will be extremely unlikely, but this is ok as I'm trying to find an underlying pattern in data with a lot of random noise.
I understand how one can use a genetic algorithm to fit a curve to a dataset, but this requires many passes through the sample data, and thus isn't practical for my application.
Is there a way to fit a curve with a single pass of the data, where the state that must be maintained from sample to sample is minimal?
I should add that the nature of the data is that the points may lie anywhere on the X axis between 0.0 and 1.0, but the Y values will always be either 1.0 or 0.0.
So, in Java, I'm looking for a class with the following interface:
public interface CurveFit {
public void addData(double x, double y);
public List<Double> getBestFit(); // Returns the polynomial coefficients
}
The class that implements this must not need to keep much data in its instance fields, no more than a kilobyte even for millions of data points. This means that you can't just store the data as you get it to do multiple passes through it later.
edit: Some have suggested that finding an optimal curve in a single pass may be impossible, however an optimal fit is not required, just as close as we can get it in a single pass.
The bare bones of an approach might be if we have a way to start with a curve, and then a way to modify it to get it slightly closer to new data points as they come in - effectively a form of gradient descent. It is hoped that with sufficient data (and the data will be plentiful), we get a pretty good curve. Perhaps this inspires someone to a solution.
Yes, it is a projection. For
y = X beta + error
where lowercased terms are vectors, and X is a matrix, you have the solution vector
\hat{beta} = inverse(X'X) X' y
as per the OLS page. You almost never want to compute this directly but rather use LR, QR or SVD decompositions. References are plentiful in the statistics literature.
If your problem has only one parameter (and x is hence a vector as well) then this reduces to just summation of cross-products between y and x.
If you don't mind that you'll get a straight line "curve", then you only need six variables for any amount of data. Here's the source code that's going into my upcoming book; I'm sure that you can figure out how the DataPoint class works:
Interpolation.h:
#ifndef __INTERPOLATION_H
#define __INTERPOLATION_H
#include "DataPoint.h"
class Interpolation
{
private:
int m_count;
double m_sumX;
double m_sumXX; /* sum of X*X */
double m_sumXY; /* sum of X*Y */
double m_sumY;
double m_sumYY; /* sum of Y*Y */
public:
Interpolation();
void addData(const DataPoint& dp);
double slope() const;
double intercept() const;
double interpolate(double x) const;
double correlate() const;
};
#endif // __INTERPOLATION_H
Interpolation.cpp:
#include <cmath>
#include "Interpolation.h"
Interpolation::Interpolation()
{
m_count = 0;
m_sumX = 0.0;
m_sumXX = 0.0;
m_sumXY = 0.0;
m_sumY = 0.0;
m_sumYY = 0.0;
}
void Interpolation::addData(const DataPoint& dp)
{
m_count++;
m_sumX += dp.getX();
m_sumXX += dp.getX() * dp.getX();
m_sumXY += dp.getX() * dp.getY();
m_sumY += dp.getY();
m_sumYY += dp.getY() * dp.getY();
}
double Interpolation::slope() const
{
return (m_sumXY - (m_sumX * m_sumY / m_count)) /
(m_sumXX - (m_sumX * m_sumX / m_count));
}
double Interpolation::intercept() const
{
return (m_sumY / m_count) - slope() * (m_sumX / m_count);
}
double Interpolation::interpolate(double X) const
{
return intercept() + slope() * X;
}
double Interpolation::correlate() const
{
return m_sumXY / sqrt(m_sumXX * m_sumYY);
}
Why not use a ring buffer of some fixed size (say, the last 1000 points) and do a standard QR decomposition-based least squares fit to the buffered data? Once the buffer fills, each time you get a new point you replace the oldest and re-fit. That way you have a bounded working set that still has some data locality, without all the challenges of live stream (memoryless) processing.
Are you limiting the number of polynomial coefficients (i.e. fitting to a max power of x in your polynomial)?
If not, then you don't need a "best fit" algorithm - you can always fit N data points EXACTLY to a polynomial of N coefficients.
Just use matrices to solve N simultaneous equations for N unknowns (the N coefficients of the polynomial).
If you are limiting to a max number of coefficients, what is your max?
Following your comments and edit:
What you want is a low-pass filter to filter out noise, not fit a polynomial to the noise.
Given the nature of your data:
the points may lie anywhere on the X axis between 0.0 and 1.0, but the Y values will always be either 1.0 or 0.0.
Then you don't need even a single pass, as these two lines will pass exactly through every point:
X = [0.0 ... 1.0], Y = 0.0
X = [0.0 ... 1.0], Y = 1.0
Two short line segments, unit length, and every point falls on one line or the other.
Admittedly, an algorithm to find a good curve fit for arbitrary points in a single pass is interesting, but (based on your question), that's not what you need.
Assuming that you don't know which point should belong to which curve, something like a Hough Transform might provide what you need.
The Hough Transform is a technique that allows you to identify structure within a data set. One use is for computer vision, where it allows easy identification of lines and borders within the field of sight.
Advantages for this situation:
Each point need be considered only once
You don't need to keep a data structure for each candidate line, just one (complex, multi-dimensional) structure
Processing of each line is simple
You can stop at any point and output a set of good matches
You never discard any data, so it's not reliant on any accidental locality of references
You can trade off between accuracy and memory requirements
Isn't limited to exact matches, but will highlight partial matches too.
An approach
To find cubic fits, you'd construct a 4-dimensional Hough space, into which you'd project each of your data-points. Hotspots within Hough space would give you the parameters for the cubic through those points.
You need the solution to an overdetermined linear system. The popular methods are Normal Equations (not usually recommended), QR factorization, and singular value decomposition (SVD). Wikipedia has decent explanations, Trefethen and Bau is very good. Your options:
Out-of-core implementation via the normal equations. This requires the product A'A where A has many more rows than columns (so the result is very small). The matrix A is completely defined by the sample locations so you don't have to store it, thus computing A'A is reasonably cheap (very cheap if you don't need to hit memory for the node locations). Once A'A is computed, you get the solution in one pass through your input data, but the method can be unstable.
Implement an out-of-core QR factorization. Classical Gram-Schmidt will be fastest, but you have to be careful about stability.
Do it in-core with distributed memory (if you have the hardware available). Libraries like PLAPACK and SCALAPACK can do this, the performance should be much better than 1. The parallel scalability is not fantastic, but will be fine if it's a problem size that you would even think about doing in serial.
Use iterative methods to compute an SVD. Depending on the spectral properties of your system (maybe after preconditioning) this could converge very fast and does not require storage for the matrix (which in your case has 5-10 columns each of which are the size of your input data. A good library for this is SLEPc, you only have to find a the product of the Vandermonde matrix with a vector (so you only need to store the sample locations). This is very scalable in parallel.
I believe I found the answer to my own question based on a modified version of this code. For those interested, my Java code is here.

Resources