OpenModelica and JModelica deliver significantly different results - modelica

Following this question, I'm trying to compare the results of the simulation between JModelica and OpenModelica. The Modelica file is identical to the above-mentioned post and the JModelica wrapper is the corrected version:
#%%
from pymodelica import compile_fmu
from pyfmi import load_fmu
import matplotlib.pylab as plt
#%%
model_name = 'friction1D.fricexample_1'
mofile = 'friction1D.mo'
#%%
fmu_name = compile_fmu(model_name, mofile)
sim = load_fmu(fmu_name)
#%%
opts = sim.simulate_options()
opts["ncp"] = 500
opts['CVode_options']['rtol'] = 1.0e-8
res = sim.simulate(final_time=10, options=opts)
#%%
time = res['time']
vel = res['v']
ffo = res['ffo']
sfo = res['sfo']
#%%
plt.plot(time, vel)
plt.xlabel("Time (s)")
plt.ylabel("Velocity (m/s)")
plt.show()
#%%
plt.plot(time, ffo, label="friction force")
plt.plot(time, sfo, label="shear force")
plt.xlabel("Time (s)")
plt.ylabel("Force (N)")
plt.legend()
plt.show()
resulting in:
Fig.1 - Velocity versus time solved by JModelica.
and
Fig.2 - Friction and shear force versus time solved by JModelica.
but if I set the simulation options in OpenModelica as:
Fig.3 - Simulation options in OpenModelica.
which results in:
Fig.4 - Velocity versus time solved by OpenModelica.
and
Fig.5 - Friction and shear force versus time solved by OpenModelica.
I would appreciate it if you could help me know why the results are so different and how I can achieve a similar simulation with these two different compilers.
P.S. posted a follow-up question here on the OpenModelica forum.

First of all the code, I had mentioned in my previous post was wrong. In addition to some small issues which have been discussed here, one should use the noEvent function to be sure the conditions of an if-statement are compiled correctly (more info here). The correct version of the code is mentioned here.
For JModelica to deliver similar results as OpenModelica I was instructed by Christian Winther here to play with the opts["CVode_options"]["maxh"] parameter which has a default value of 0. I set the option to:
opts['CVode_options']['maxh'] = 0.01
and JModelica worked fine.

Related

How to add different priors for each of ARD lengthscales hyperparameters in GPflow

I've seen how to add a prior to the lengthscales hyperpameter in the MCMC notebook:
model.kernel.lengthscales.prior = tfd.Gamma(f64(1.0), f64(1.0))
From above, it seems we can only add a prior to a single length-scale of the RBF (radial basis function) kernel. I would like to add a prior to each of the lengthscales of a ARD (Automatic Relevance Determination) kernel. Any suggestions on how to do this is much appreciated.
Your code snippet,
model.kernel.lengthscales.prior = tfd.Gamma(f64(1.0), f64(1.0))
does add a prior to all the lengthscales of your ARD RBF kernel, but it's the same prior for each dimension.
To assign different priors to different dimensions of the ARD lengthscale, you can simply use the batch feature of tfp Distributions, e.g.
model.kernel.lengthscales.prior = tfd.Gamma(
concentration=np.array([1.0, 2.0]),
rate=np.array([3.0, 4.0]),
)
You can probably make it work for different distributions, too (there's tfd.JointDistribution); for that you'll have to consult the tensorflow_probability docs.

Does KernelDensity.estimate in pyspark.mllib.stat.KernelDensity work when input data is normally distributed?

Does pyspark's KernelDensity.estimate work correctly on a dataset that is normally distributed? I get an error when I try that. I have filed https://issues.apache.org/jira/browse/SPARK-20803 (KernelDensity.estimate in pyspark.mllib.stat.KernelDensity throws net.razorvine.pickle.PickleException when input data is normally distributed (no error when data is not normally distributed))
Example code:
vecRDD = sc.parallelize(colVec)
kd = KernelDensity()
kd.setSample(vecRDD)
kd.setBandwidth(3.0)
# Find density estimates for the given values
densities = kd.estimate(samplePoints)
When data is NOT Gaussian, I get for e.g.
5.6654703477e-05,0.000100010001,0.000100010001,0.000100010001,.....
For reference, using Scala, for Gaussian data,
Code:
vecRDD = sc.parallelize(colVec)
kd = new KernelDensity().setSample(vecRDD).setBandwidth(3.0)
// Find density estimates for the given values
densities = kd.estimate(samplePoints)
I get:
[0.04113814235801906,1.0994865517293571E-163,0.0,0.0,.....
I faced the same issue and was able to track down the issue to a very minimal test case. If you're using Numpy in Python to generate the data in the RDD, then that's the problem!
import numpy as np
kd = KernelDensity()
kd.setSample(sc.parallelize([0.0, 1.0, 2.0, 3.0])) # THIS WORKS
# kd.setSample(sc.parallelize([0.0, np.float32(1.0), 2.0, 3.0])) # THIS FAILS
kd.setBandwidth(0.35)
kd.estimate([0.0, 1.0])
If this was your issue as well, simply convert the Numpy data to Python base type until the Spark issue is fixed. You can do that by using the np.asscalar function.

Do I have to preprocess test data using neural networks?

I am using Keras (version 2.0.0) and I'd like to make use of pretrained models like e.g. VGG16.
In order to get started, I ran the example of the [Keras documentation site ][https://keras.io/applications/] for extracting features with VGG16:
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np
model = VGG16(weights='imagenet', include_top=False)
img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
features = model.predict(x)
The used preprocess_input() function bothers me
(the function does Zero-centering by mean pixel what can be seen by looking at the source code).
Do I really have to preprocess input data (validation/test data) before using a trained model?
a)
If yes, one can conclude that you always have to be aware of what preprocessing steps have been performed during training phase?!
b)
If no: Does preprocessing of validation/test data cause a bias?
I appreciate your help.
Yes you should use the preprocessing step. You can retrain the model without it but the first layers will learn to center your datas so this is a waste of parameters.
If you do not recenter your performances will suffer.
Great thread on reddit : https://www.reddit.com/r/MachineLearning/comments/3q7pjc/why_is_removing_the_mean_pixel_value_from_each/

How can I visualise results of a simulation in OpenModelica as animation?

I want to know how I can visualise the results of a Modelica simulation in the form of an animation.
Imagine I have a simple simulation as below:
model test
//parameters
parameter Real m_1 = 1;
parameter Real m_2 = 10;
parameter Real K_c = 100000;
//variables
Real x_1;
Real v_1;
Real x_2;
Real v_2;
Real f_1;
Real f_12;
initial equation
x_1 = 0;
v_1 = 0;
x_2 = 0.2;
v_2 = 0;
equation
v_1 = der(x_1);
m_1 * der(v_1) = f_1 - f_12;
v_2 = der(x_2);
m_2 * der(v_2) = f_12;
f_12 = if x_2 >= x_1 then 0 else K_c * (x_1 - x_2);
f_1 = 1;
end test;
(it is actually a very simple elastic collision)
and I have part1.obj and part2.obj (or other possible formats rather than .obj), designed in other CAD software, which I want to import and assign to x_1 and x_2 and then animate. OpenModelica 1.11.0 is already installed on Ubuntu using these instructions.
What I have found so far and the problems I have encountered:
From this page I have learned that Modelica3D should also be installed. However I couldn't find this library using apt or aptitude.
I found the installation instructions for windows and mac on OpenModelica official website, but no Ubuntu (or other Linux distro) one.
I have also found this github repo which claims to be a regularly maintained mirror of the original distribution, however the latest commit is for 2 years ago! Not to mention that the original website is dead.
Do I still need to install this library separately or it has already been integrated into the latest stable OpenModelica release? if yes how can I install it? what other libraries/packages might be needed?
Edit: It seems that Modelica3D has been depreciated (same for OMVisualize). Now the ModelicaServices is being used for animation. more information here
This post gives a very simple example of animating using Wolfram SystemModeller. When I open it into the OpenModelica, it does compile and shows the results. I tried exporting the model as FMU and XML and then use animation icon from the top menus to import the model.
but when tried to import the .mat file I got the error:
Scripting Error
Could not find the visual XML file /tmp/OpenModelica_user/OMEdit/SimpleCarModel_visual.xml.
Is this example compatible with OpenModelica? and if yes what is the problem and how I can solve it? (you can also download the example from this Github gist)
Edit: This example is compatible with OpenModelica. I was doing it wring. I had to choose the "simulate with Animation" instead of "Simulate". I still can't assign an external CAD object to the simulation and a cylinder is being shown instead.
I also tried to learn using OMShell scripting to run the Modelica3D example from this page. However it seems that the code is wrong because I get many errors running it in my OMShell.
One of the linked websites has mentioned that it is possible to use blender for animated results however the author hadn't succeed to do so. I would appreciate if you could help learn this in simple and clear steps.
Visualizing CAD-files is currently only possible for .stl and .dxf.
You can specify the URI of your CAD-file in the shapeType-parameter of your shape. Please use the following notation:
"modelica://packageName/relativePath/To/Your/CADfile.stl"
It is also possible to set the absolute path in the *_visual.xml that has been generated with your simulation results(and should be in the same directory if you want to load simulation from OMEdit).
If you want to move your animation shapes, simply assign variables to i.e. the position vector
r = {x,0,0};

One sample Kolmogorov-Smirnov to test gof of theoretical distribtion (makedist error) matlab

I have few continuous variables that look like this:
durs1=[3,40933 0,033630 0,25103 0,6361 0,71971 1,18311 1,91946 0,12842 0,97639 1,1383 0,46871 3,05241 2,34907 1,03788 0,76434 1,08798 1,462 0,4241 2,32128 0,29017..]
Each has more than 1000 values (all positive). I used
[a, b]=gamfit(durs1)
a =
2.3812 0.4200
b =
2.2316 0.3907
2.5408 0.4514
to find parameters of gamma distribution. Now I want to make a goodness of fit test in order to see how well the model fits my data. Matlab provides the one sample Kolmogorov-Smirnov test to solve the problem (http://www.mathworks.com/help/stats/kstest.html#btnyrvz-1)
But when I run my code (based on their examples):
test_cdf=makedist('Gamma','a',2.38,'b',0.42)
[h, p]=kstest(durs1,'CDF',test_cdf)
I have this error: "Undefined function 'makedist' for input arguments of type 'char'."
Can somebody help me to fix my code?
It seems like the function makedist of the statistics toolbox is available only from Matlab version r2013a. Looking in the documentation of earlier versions, even as late as r2012b, there is no mention of makedist. So I think updating to the latest version of matlab should solve your problem.