Instantiate OpenModelica model inside package from command line (omc) - openmodelica

I am trying to create the flat modelica code of a model, which is inside a package from the command line using open modelica (omc).
If I have a .mo-file which contains just one model I can easily create the instantiation by
omc myModel.mo > myModel.mof
The question is if I have this file:
package TestPackage
model TestModel2
Real y;
end TestModel2;
model TestModel
Real x(start=1);
TestModel2 a;
equation
x=a.y;
der(x)=a.y;
end TestModel;
end TestPackage;
how do i create the flat code for TestModel?
(Using OMEdit I get the correct code by instantiating TestModel:
class TestPackage.TestModel
Real x(start = 1.0);
Real a.y;
equation
x = a.y;
der(x) = a.y;
end TestPackage.TestModel;
)

Basically as I said in the comment +i=Path.To.Model:
adrpo#dev MINGW64 ~/dev/OpenModelica/build/bin
$ ./omc +i=TestPackage.TestModel myModel.mo
class TestPackage.TestModel
Real x(start = 1.0);
Real a.y;
equation
x = a.y;
der(x) = a.y;
end TestPackage.TestModel;

Related

How can I make each module instance read from a unique file?

In top.v, I generate X_MAX*Y_MAX instances of a pe module. In pe.v, I want to initialize a memory generated specifically for that instance. For example, at x=0,y=1: "pe_memory_x0_y0.dat". This is what my top-level module looks like:
genvar x, y;
generate for (y = 0; y < Y_MAX; y = y + 1) begin : ys
for (x = 0; x < X_MAX; x = x + 1) begin : xs
pe #(
.X_MAX(X_MAX),
.Y_MAX(Y_MAX),
.X(x),
.Y(y)
)
pe_inst(
.clk(clk),
...
);
Inside pe.v, things like
$display("Loading pe memory at (%0d,%0d)", X, Y);
work in an initial block! But when I need to $readmem$,
$readmemb({"pe_memory_", X, "_y", Y, ".dat"}, n_bound_sel_memory);
does not work:
X has indefinite width
Specifying a width for X, a parameter whose values comes from a genvar, just throws more errors.
I'm targeting Xilinx FPGAs, and I'm trying to simulate my design with iverilog.
You can use $sformatf to construct a file name:
$readmemb($sformatf("pe_memory_%0d_y%0d.dat", X, Y), n_bound_sel_memory);
Refer to IEEE Std 1800-2017, section 21.3.3 Formatting data to a string

How to setup library-application including extend/redeclare in OpenModelica?

I have Modelica code divided in a small library DEMO_v11.mo and an application D11_APP7.mo The application code include parts that adapt interface of the library to the application using: import-extend-redeclare. It all works in JModelica. Now I want to set it up in OpenModelica but I do not know how to handle my two different files. Browsing through the documentation I could find little help.
I have before managed to bring in a library and in OpenModelica add graphical notation and then compose a new model based on components from the library.
However, now I need to do a more “advanced” import that extend-redeclare the imported models. Thus my problem is how to do this more “advanced” part.
Appreciate some advice, or suggestion on where to read.
The answer to this questions I have found is both easy and difficult.
The easy part is that you should in OpenModelica load both the library and application code in the same way using command “File/Open Modelica/Library File(s). Then the library and the application land side by side, sort of. The icons for them appear in the pane to the left and below the MSL library Modelica. The application code can then import (and redeclare) from both the loaded library and from MSL if needed in a similar way.
The difficult part is that here seems to be bugs in OpenModelica when you refer to models in two (or more) steps instead of one. This question I discuss with OpenModelica support.
A code that works to import as described above are library DEMO_v15 and application D15_app7 and shown below (and slightly modified from DEMO_v11 and D11_app7 mentioned and described in another thread).
package DEMO_v15
// ---------------------------------------------------------------------------------------------
// Interfaces
// ---------------------------------------------------------------------------------------------
import Modelica.Blocks.Interfaces.RealInput;
import Modelica.Blocks.Interfaces.RealOutput;
package Medium2
replaceable constant String name = "Two components" "Medium name";
replaceable constant Integer nc = 2 "Number of substances";
replaceable type Concentration = Real[nc] "Substance conc";
replaceable constant Real[nc] mw = {10, 20} "Substance weight";
constant Integer A = 1 "Substance index";
constant Integer B = 2 "Substance index";
end Medium2;
package Medium3
import M2 = DEMO_v15.Medium2;
extends M2
(name="Three components" "Medium name",
nc=3 "Number of substances",
mw = cat(1,M2.mw,{30}) "Substance weight",
redeclare type Concentration = Real[nc] "Substance conc");
constant Integer C = 3 "Substance index";
end Medium3;
connector LiquidCon3
Medium3.Concentration c "Substance conc";
flow Real F (unit="m3/s") "Flow rate";
end LiquidCon3;
// ---------------------------------------------------------------------------------------------
// Equipment dependent on the medium
// ---------------------------------------------------------------------------------------------
package Equipment
replaceable connector LiquidCon
end LiquidCon;
model PumpType
LiquidCon inlet, outlet;
RealInput Fsp;
equation
inlet.F = Fsp;
connect(outlet, inlet);
end PumpType;
model FeedtankType
LiquidCon outlet;
constant Integer medium_nc = size(outlet.c,1);
parameter Real[medium_nc] c_in (each unit="kg/m3")
= {1.0*k for k in 1:medium_nc} "Feed inlet conc";
parameter Real V_0 (unit="m3") = 100 "Initial feed volume";
Real V(start=V_0, fixed=true, unit="m3") "Feed volume";
equation
for i in 1:medium_nc loop
outlet.c[i] = c_in[i];
end for;
der(V) = outlet.F;
end FeedtankType;
model HarvesttankType
LiquidCon inlet;
constant Integer medium_nc = size(inlet.c,1);
parameter Real V_0 (unit="m3") = 1.0 "Initial harvest liquid volume";
parameter Real[medium_nc] m_0
(each unit="kg/m3") = zeros(medium_nc) "Initial substance mass";
Real[medium_nc] c "Substance conc";
Real[medium_nc] m
(start=m_0, each fixed=true) "Substance mass";
Real V(start=V_0, fixed=true, unit="m3") "Harvest liquid volume";
equation
for i in 1:medium_nc loop
der(m[i]) = inlet.c[i]*inlet.F;
c[i] = m[i]/V;
end for;
der(V) = inlet.F;
end HarvesttankType;
end Equipment;
// ---------------------------------------------------------------------------------------------
// Control
// ---------------------------------------------------------------------------------------------
package Control
block FixValueType
RealOutput out;
parameter Real val=0;
equation
out = val;
end FixValueType;
end Control;
// ---------------------------------------------------------------------------------------------
// Adaptation of package Equipment to Medium3
// ---------------------------------------------------------------------------------------------
// package Equipment3 = Equipment(redeclare connector LiquidCon=LiquidCon3); // Just shorter
package Equipment3
import DEMO_v15.Equipment;
extends Equipment(redeclare connector LiquidCon=LiquidCon3);
end Equipment3;
// ---------------------------------------------------------------------------------------------
// Examples of systems
// ---------------------------------------------------------------------------------------------
model Test
Medium3 medium;
Equipment3.FeedtankType feedtank;
Equipment3.HarvesttankType harvesttank;
Equipment3.PumpType pump;
Control.FixValueType Fsp(val=0.2);
equation
connect(feedtank.outlet, pump.inlet);
connect(pump.outlet, harvesttank.inlet);
connect(Fsp.out, pump.Fsp);
end Test;
end DEMO_v15;
And application code:
encapsulated package D15_app7
// ---------------------------------------------------------------------------------------------
// Interfaces
// ---------------------------------------------------------------------------------------------
import Modelica.Blocks.Interfaces.RealInput;
import Modelica.Blocks.Interfaces.RealOutput;
package Medium7
import M2 = DEMO_v15.Medium2;
extends M2
(name = "Seven components" "Medium name",
nc = 7 "Number of substances",
mw = cat(1,M2.mw,{30,40,50,60,70}) "Substance weight",
redeclare type Concentration = Real[nc] "Substance conc");
constant Integer C = 3 "Substance index";
constant Integer D = 4 "Substance index";
constant Integer E = 5 "Substance index";
constant Integer F = 6 "Substance index";
constant Integer G = 7 "Substance index";
end Medium7;
connector LiquidCon7
Medium7.Concentration c "Substance conc";
flow Real F (unit="m3/s") "Flow rate";
end LiquidCon7;
// ---------------------------------------------------------------------------------------------
// Adaptation of library DEMO_v15 to Medium7
// ---------------------------------------------------------------------------------------------
package Equipment7
import DEMO_v15.Equipment;
extends Equipment(redeclare connector LiquidCon=LiquidCon7);
end Equipment7;
// ---------------------------------------------------------------------------------------------
// Examples of systems
// ---------------------------------------------------------------------------------------------
import DEMO_v15.Control;
model Test
Medium7 medium; // Instance not necessary but helpful for user interface
Equipment7.PumpType pump;
Equipment7.FeedtankType feedtank;
Equipment7.HarvesttankType harvesttank;
Control.FixValueType Fsp(val=0.2);
equation
connect(feedtank.outlet, pump.inlet);
connect(pump.outlet, harvesttank.inlet);
connect(Fsp.out, pump.Fsp);
end Test;
end D15_app7;

Configure Iterative Closest Point PCL

I am having trouble configuring ICP in PCL 1.6(I use Android) and I believe that is the cause of an incorrect transformation matrix. What I've tried so far is this;
Downsample the point clouds I use in ICP with the following code:
pcl::VoxelGrid <pcl::PointXYZ> grid;
grid.setLeafSize(6, 6, 6);
grid.setInputCloud(output);
grid.filter(*tgt);
grid.setInputCloud(cloud_src);
grid.filter(*src);
Try to align the two point clouds with the following code :
pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;
icp.setInputCloud(tgt);
icp.setInputTarget(src);
pcl::PointCloud<pcl::PointXYZ> Final;
pcl::PointCloud<pcl::PointXYZ> transformedCloud;
icp.setMaxCorrespondenceDistance(0.08);
icp.setMaximumIterations(500);
//icp.setTransformationEpsilon (0.000000000000000000001);
icp.setTransformationEpsilon(1e-12);
icp.setEuclideanFitnessEpsilon(1e-12);
icp.setRANSACIterations(2000);
icp.setRANSACOutlierRejectionThreshold(0.6);
I have tried all kinds of values in the options of ICP but with no success.
The code I use to create the point cloud:
int density = 1;
for (int y = 0; y < depthFrame.getHeight(); y = y + density) {
for (int x = 0; x < depthFrame.getWidth(); x = x + density) {
short z = pDepthRow[y * depthVideoMode.getResolutionX() + x];
if (z > 0 && z < depthStream.getMaxPixelValue()) {
cloud_src->points[counter].x = x;
cloud_src->points[counter].y = y;
cloud_src->points[counter].z = z;
}
}
}
Any chance somebody can help me out configuring ICP?
From what I know, PCL uses meters as a unit of measurement. so, is it intended that leaf size for downsampling is 6*6*6 !? I think it's huge !!
Try with some lower values and if it didn't work either, try ICP with the most simple configuration as follows :
pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;
icp.setInputCloud(tgt);
icp.setInputTarget(src);
pcl::PointCloud<pcl::PointXYZ> Final;
icp.align(Final);
once, you got this working (and it should be), then start tuning the other parameters and it shouldn't be that hard to do.
Hope that helps, Cheers!

Initial Conditions in OpenModelica

Will somebody please explain why the initial conditions are properly taken care of in the following openmodelica model compiled and simulated in OMEdit v1.9.1 beta2 in Windows, but if line 5 is commentd and 6 uncommented (x,y) is initialized to (0.5,0)?
Thank you.
class Pendulum "Planar Pendulum"
constant Real PI = 3.141592653589793;
parameter Real m = 1,g = 9.81,L = 0.5;
Real F "Force of the Rod";
output Real x(start=L*sin(PI/4)) ,y(start=-0.35355);
//output Real x(start = L * sin(PI / 4)), y(start=-L*sin(PI/4));
output Real vx,vy;
equation
m * der(vx) = -x / L * F;
m * der(vy) = (-y / L * F) - m * g;
der(x) = vx;
der(y) = vy;
x ^ 2 + y ^ 2 = L ^ 2;
end Pendulum;
The short answer is that initial values are treated merely as hints, you have to add the fixed=true attribute to force them as in:
output Real x(start=L*cos(PI/4),fixed=true);
If initialized variables are constrained, the fixed attribute should not be used on all initialized variables but on a 'proper' subset, in this case on just one.
The long answer can be found here

Truly declarative language?

Does anyone know of a truly declarative language? The behavior I'm looking for is kind of what Excel does, where I can define variables and formulas, and have the formula's result change when the input changes (without having set the answer again myself)
The behavior I'm looking for is best shown with this pseudo code:
X = 10 // define and assign two variables
Y = 20;
Z = X + Y // declare a formula that uses these two variables
X = 50 // change one of the input variables
?Z // asking for Z should now give 70 (50 + 20)
I've tried this in a lot of languages like F#, python, matlab etc, but every time I tried this they come up with 30 instead of 70. Which is correct from an imperative point of view, but I'm looking for a more declarative behavior if you know what I mean.
And this is just a very simple calculation. When things get more difficult it should handle stuff like recursion and memoization automagically.
The code below would obviously work in C# but it's just so much code for the job, I'm looking for something a bit more to the point without all that 'technical noise'
class BlaBla{
public int X {get;set;} // this used to be even worse before 3.0
public int Y {get;set;}
public int Z {get{return X + Y;}}
}
static void main(){
BlaBla bla = new BlaBla();
bla.X = 10;
bla.Y = 20;
// can't define anything here
bla.X = 50; // bit pointless here but I'll do it anyway.
Console.Writeline(bla.Z);// 70, hurray!
}
This just seems like so much code, curly braces and semicolons that add nothing.
Is there a language/ application (apart from Excel) that does this? Maybe I'm no doing it right in the mentioned languages, or I've completely missed an app that does just this.
I prototyped a language/ application that does this (along with some other stuff) and am thinking of productizing it. I just can't believe it's not there yet. Don't want to waste my time.
Any Constraint Programming system will do that for you.
Examples of CP systems that have an associated language are ECLiPSe, SICSTUS Prolog / CP package, Comet, MiniZinc, ...
It looks like you just want to make Z store a function instead of a value. In C#:
var X = 10; // define and assign two variables
var Y = 20;
Func<int> Z = () => X + Y; // declare a formula that uses these two variables
Console.WriteLine(Z());
X = 50; // change one of the input variables
Console.WriteLine(Z());
So the equivalent of your ?-prefix syntax is a ()-suffix, but otherwise it's identical. A lambda is a "formula" in your terminology.
Behind the scenes, the C# compiler builds almost exactly what you presented in your C# conceptual example: it makes X into a field in a compiler-generated class, and allocates an instance of that class when the code block is entered. So congratulations, you have re-discovered lambdas! :)
In Mathematica, you can do this:
x = 10; (* # assign 30 to the variable x *)
y = 20; (* # assign 20 to the variable y *)
z := x + y; (* # assign the expression x+y to the variable z *)
Print[z];
(* # prints 30 *)
x = 50;
Print[z];
(* # prints 70 *)
The operator := (SetDelayed) is different from = (Set). The former binds an unevaluated expression to a variable, the latter binds an evaluated expression.
Wanting to have two definitions of X is inherently imperative. In a truly declarative language you have a single definition of a variable in a single scope. The behavior you want from Excel corresponds to editing the program.
Have you seen Resolver One? It's like Excel with a real programming language behind it.
Here is Daniel's example in Python, since I noticed you said you tried it in Python.
x = 10
y = 10
z = lambda: x + y
# Output: 20
print z()
x = 20
# Output: 30
print z()
Two things you can look at are the cells lisp library, and the Modelica dynamic modelling language, both of which have relation/equation capabilities.
There is a Lisp library with this sort of behaviour:
http://common-lisp.net/project/cells/
JavaFX will do that for you if you use bind instead of = for Z
react is an OCaml frp library. Contrary to naive emulations with closures it will recalculate values only when needed
Objective Caml version 3.11.2
# #use "topfind";;
# #require "react";;
# open React;;
# let (x,setx) = S.create 10;;
val x : int React.signal = <abstr>
val setx : int -> unit = <fun>
# let (y,sety) = S.create 20;;
val y : int React.signal = <abstr>
val sety : int -> unit = <fun>
# let z = S.Int.(+) x y;;
val z : int React.signal = <abstr>
# S.value z;;
- : int = 30
# setx 50;;
- : unit = ()
# S.value z;;
- : int = 70
You can do this in Tcl, somewhat. In tcl you can set a trace on a variable such that whenever it is accessed a procedure can be invoked. That procedure can recalculate the value on the fly.
Following is a working example that does more or less what you ask:
proc main {} {
set x 10
set y 20
define z {$x + $y}
puts "z (x=$x): $z"
set x 50
puts "z (x=$x): $z"
}
proc define {name formula} {
global cache
set cache($name) $formula
uplevel trace add variable $name read compute
}
proc compute {name _ op} {
global cache
upvar $name var
if {[info exists cache($name)]} {
set expr $cache($name)
} else {
set expr $var
}
set var [uplevel expr $expr]
}
main
Groovy and the magic of closures.
def (x, y) = [ 10, 20 ]
def z = { x + y }
assert 30 == z()
x = 50
assert 70 == z()
def f = { n -> n + 1 } // define another closure
def g = { x + f(x) } // ref that closure in another
assert 101 == g() // x=50, x + (x + 1)
f = { n -> n + 5 } // redefine f()
assert 105 == g() // x=50, x + (x + 5)
It's possible to add automagic memoization to functions too but it's a lot more complex than just one or two lines. http://blog.dinkla.net/?p=10
In F#, a little verbosily:
let x = ref 10
let y = ref 20
let z () = !x + !y
z();;
y <- 40
z();;
You can mimic it in Ruby:
x = 10
y = 20
z = lambda { x + y }
z.call # => 30
z = 50
z.call # => 70
Not quite the same as what you want, but pretty close.
not sure how well metapost (1) would work for your application, but it is declarative.
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
x = 10
y = 20
z = function() return x + y; end
x = 50
= z()
70
It's not what you're looking for, but Hardware Description Languages are, by definition, "declarative".
This F# code should do the trick. You can use lazy evaluation (System.Lazy object) to ensure your expression will be evaluated when actually needed, not sooner.
let mutable x = 10;
let y = 20;
let z = lazy (x + y);
x <- 30;
printf "%d" z.Value

Resources