Switch type based on boolean parameter (without inheriting)? - modelica

I have a model representing some chemical process, and I want the reaction model to be switchable between an absorption and a desorption class (which define the respective model), based on a boolean parameter.
I tried to do it like this:
model Sorption
boolean parameter absorbing;
AbsorptionModel if absorbing else Desorptionmodel reaction;
equation
reaction.T = T; //dummy usage
...
Use it like:
Sorption TestAbsorption(absorbing=true); // uses the absorption model
Sorption TestDesorption(absorbing=false); // uses the desorption model
Of course, this way does not work. absorbing is known at compile time, so I have a feeling it should be ok to achieve this somehow.
I tried to use replaceable, but I don't want to (unnecessarily) make two separate subclasses of Sorption just to switch the type of reaction model. It seems replaceable/redeclare is only useable when inheriting, but I may be wrong? Is there a way to do what I want?
AbsorptionModel and DesorptionModel both inherit from the same base class, and have identical interfaces, if that is relevant.

No if is needed and you cannot use if with component declaration, except for conditional components (but that will only remove the component declaration and its connection equations).
model Sorption
boolean parameter absorbing;
replaceable model RModel = AbsorptionModel;
RModel reaction;
equation
reaction.T = T; //dummy usage
...
Use it like:
Sorption TestAbsorption(redeclare model RModel = AbsorptionModel); // uses the absorption model
Sorption TestDesorption(redeclare model RModel = Desorptionmodel); // uses the desorption model

Related

Validate property to be a sublclass of an abstract class in MATLAB

I'm brand new to OOP in Matlab, and still fairly green when it comes to OOP in general, but what I do know I learnt in C++.
I'm following the Matlab documentation found here Property class and size validation. I want to validate a property so that it must be a specific class and I'm using the example from the link. This is what my class looks like:
classdef simpoint
...
properties
...
outputType dataType
...
end
...
end
In my code dataType is a class I've written. What's more it's abstract.
I'm getting the error
Error defining property 'outputType' of class 'simpoint':
Class dataType is abstract. Specify a default value for property outputType.
The class dataType is abstract to force the user to implement some methods. I'm trying to use property validation to make sure when outputType is set, the class is a subclass of dataType.
I don't really want to set a default value, because forgetting to set outputType should throw an error.
How can I validate outputType to make sure it is a subclass of dataType? Is there a better way to do this in Matlab?
There is a more elegant solution to this problem, which is apparently not well known.
MATLAB has a concept of Heterogeneous Class Hierarchies. This is just fancy way of explicitly declaring the common root class (abstract or not) so that it can be used for property validation. In practice, all you need to do is to make your abstract class inherit from matlab.mixin.Heterogeneous.
Here is a quick example:
classdef (Abstract) AbstractItem < handle & matlab.mixin.Heterogeneous
end
classdef Collection < handle
properties
items AbstractItem
end
end
Then you have no problem:
>> x = Collection
x =
Collection with properties:
items: [0×0 AbstractItem]
Without the matlab.mixin.Heterogeneous inheritance you would get an error like you described:
Error defining property 'items' of class 'Collection'. Class AbstractItem is abstract. Specify a default value for property items.
Your current code uses the following logic:
Create a new simpoint object
Ah this object needs an outputType property
Initialise the outputType property to be an empty dataType object
Uhoh, we can't instantiate an abstract object - error.
Instead, you could also use setters and getters to validate data types. This removes steps 3 and 4 above, since the initial property value will be [].
classdef simpoint < matlab.mixin.SetGet
properties
outputType
end
methods
% ...
end
methods % Setters and getters
function set.outputType( obj, v )
% When the 'obj.outputType = X' is called, this function is
% triggered. We can validate the input first
assert( isa( v, 'dataType' ) );
% If the assertion didn't error, we can set the property
obj.outputType = v;
end
function v = get.outputType( obj )
% Nothing bespoke in the getter (no not strictly needed), just return the value
v = obj.outputType;
end
end
end
For more informative validation, you could use validateattributes instead of assert.
In this case, the default value of outputType will be [] unless you initialise it in the constructor.
Note, by using matlab.mixin.SetGet to enable setters and getters, I've implicitly made your object a handle. In broader OOP terms, the object is now accessed "by reference" rather than "by value". Read more here.
If you don't want a handle then you can remove the < matlab.mixin.SetGet and, by your own comment, define the setter more explicitly
function obj = set.outputType( obj, v )
% Have to return 'obj' if the class isn't a handle.
% ...
end

Is there a way to pass parameter to a replaceable/redeclared component?

This question is related to this previous question.
I have some submodels that are interchangeable and I use the replaceable/redeclare mechanism to include them in a model (e.g. submodels of different type of heat-exchangers in a cooling loop model).
I would like to "link" some parameters of the main model (let's say the pipes' length and diameter) to the corresponding parameters of the submodule. This is usually done when defining a model instance (i.e. in the replaceable line), but how can this link be applied also when the componenet is redeclared? Expecially if choicesAllMatching is used?
Here is "my" model (thanks to helpers in the previous question):
package Test
// Original definition of Component 1 and 2 in the external library
// COMP1 (COMP2) has a parameter p1 (p2) defined with a default value
package ReadOnlyLibrary
model COMP1
parameter Real p1=1 "";
Real v "";
equation
v=p1*time;
end COMP1;
model COMP2
parameter Real p2=1 "";
Real v "";
equation
v=p2*time;
end COMP2;
end ReadOnlyLibrary;
// Interface and variants with modified default values
partial model Call_Interface
parameter Real pp = 10; // New parameter definition to have the same name for all variants
Real v "";
end Call_Interface;
// Both Call1 and Call2 parameters (p1 and p2) are linked to pp
model Call1 "Default"
extends Call_Interface;
extends ReadOnlyLibrary.COMP1(p1=pp);
end Call1;
model Call2 "Variant"
extends Call_Interface;
extends ReadOnlyLibrary.COMP2(p2=pp);
end Call2;
// Main module (system)
model Main
parameter Real pm=100 "";
parameter Real pp0=1 ""; //Actual parameter value to be used by submodules for this application -> pp
Real vm "";
replaceable Test.Call1 OBJ(pp=pp0) constrainedby Test.Call_Interface annotation (choicesAllMatching); //For default definition, pp, and finally p1, are linked to pp0. But when OBJ is redeclarated, the link is lost and p1/p2 gets its default value.
equation
vm = OBJ.v+pm;
end Main;
// Application model, using the main model
model App
Main main;
end App;
end Test;
I could add all possible redeclarations in the annotation by writing for example choice(redeclare Test.Call2 OBJ(pp=pp0)) instead of using choiceAllMatching but that may become tedius and error prone when many submodules are interchangeables (it would be easier and safer to write the "link" just once).
I tried by adding a generic OBJ.pp = pp0 in Main model parameter section, but this is not accepted. What is the proper way of doing that?
You simply have to write the modifiers to the constraining class:
replaceable Test.Call1 OBJ constrainedby Test.Call_Interface(pp=pp0)
annotation (choicesAllMatching);

Inheriting from Sealed classes in MATLAB

In MATLAB, one of the attributes of a class (defined after classdef) is Sealed, which means that no class can use it as a superclass (or to be more precise, "to indicate that these classes have not been designed to support subclasses."1).
For example, if I try to instantiate a class that's defined as below (considering table is Sealed):
classdef SomeLie < table
end
I would get the 'MATLAB:class:sealed' error:
>> A = SomeLie;
Error using SomeLie
Class 'table' is Sealed and may not be used as a superclass.
As I refuse to be told by a machine what I may or may not do, I would like to subclass a Sealed class, regardless. How can I do that in MATLAB R2017a?
I'm having a hard time believing that this system is completely airtight, so I'm looking for a solution that would cause the Sealed attribute to be silently ignored (or something of that sort). The desired solution should work without modifying any "library class definitions" to remove Sealed from them.
I tried playing around with "reflection", but arrived at a dead end...
classdef SomeLie % < table
properties (Access = private)
innerTable table;
end
properties (GetAccess = public)
methodHandles struct = struct();
end
methods
function slObj = SomeLie(varargin)
slObj.innerTable = table(varargin{:});
% methodHandles = methods(slObj.innerTable);
ml = ?table; ml = {ml.MethodList.Name}.';
ml = setdiff(ml,'end');
tmpStruct = struct;
for indM = 1:numel(ml)
tmpStruct.(ml{indM}) = str2func([...
'#(varargin)' ml{indM} '(slObj.innerTable,varargin{:})']);
end
slObj.methodHandles = tmpStruct;
end
function varargout = subsref(slObj,varargin)
S = struct(slObj);
varargout{:} = S.methodHandles.(varargin{1}.subs)(varargin{:});
end
end
end
(There's no need to fix the above code, I was just sharing)
I do not think the machine is the problem, but the class designer and he certainly has good motivations to seal the class. "Philosophy" of coding, a part, you could 'own' the class in a wrapper class without defining it sealed.
For example, supposer the class Hello is sealed and has a method (or function, if you wish) sayHello which you would like to use in inherited classes you could define a class FreeHello (public) which contains an instance of Hello. At the constructor you build the corresponding Hello and then you define a sayHello method whose body simply calls your Hello instance and makes it execute the sayHello method (and returns the output, accordingly).
In order to 'open' the sealed class, you need to do these for all properties and public methods; of course you are still not capable of accessing private methods, but now you can subclass your wrapper class, as you wish.

Is there any method to know whether a member is declared random or not in a class in SV

// Current Class
class x;
rand int a;
int b; // b is nonrandom as of now
function new();
endfunction
function abc;
// if a != ref.a, where ref is reference object of class x, declared somewhere else
a.rand_mode(0);
endfunciton
// Future Possible Class
class x;
rand int a;
rand int b; // b is also a random variable now
function new();
endfunction
function abc;
// if a != ref.a, where ref is reference object of class x, declared somewhere else
a.rand_mode(0);
// if b != ref.b, where ref is reference object of class x, declared somewhere else
b.rand_mode(0);
endfunciton
So in function abc, depending upon whether a rand member value matches or doesn't match with the value of that member in reference class, that rand declared members of class x, should be active or inactive accordinly.
Purpose - I need to check if a rand variable matches with reference class value then only it should be randomized, otherwise not.
I want to generalize method abc, for all possible future variations (So I don't need to modify it, as done in the above example), and as I don't know, when a class member may become rand or nonrand member, Is there any inbuilt method to know, whether a member of a class is declared as rand or not in that class?
You could change your perspective on the problem slightly. Instead of trying to disable randomization for fields that are declared rand, why not say that when they get randomized, they should keep their value?
According to this nice post, there's a new construct in SV 2012, const'(...) that would work in this case. Unfortunately I don't think many vendors support it. Your randomize() call would look like this:
if (!rand_obj.randomize() with {
const'(a) != ref_obj.a -> a == const'(a);
})
$fatal(0, "rand error");
Let's dissect this code. const(a) will sample the value of a prior to doing any sort of randomization. If the value of a before randomization is not equal to the reference value, then we have the second part of the constraint that says a should keep its value. I've tried this code on two simulators but it wasn't supported by either (though it should be legal SV 2012 syntax). Maybe you're lucky enough to have a vendor that supports it.
You can write such constraints even for state variables, as they will still hold.
If you can't get the const syntax to work in your simulator, then the same post shows how you could work around the issue. You could store the values prior to randomization inside the object and use those in the constraint:
class some_class;
rand bit [2:0] a;
bit [2:0] b;
bit [2:0] pre_rand_a;
bit [2:0] pre_rand_b;
function void pre_randomize();
pre_rand_a = a;
pre_rand_b = b;
endfunction
endclass
When you want to randomize, you'd add the following constraints:
if (!rand_obj.randomize() with {
pre_rand_a != ref_obj.a -> a == pre_rand_a;
pre_rand_b != ref_obj.b -> b == pre_rand_b;
})
$fatal(0, "rand error");
You can find a full example on EDAPlayground.
You mention that your function that does randomization is defined outside of the object. Because of that, the pre_rand_* fields can't be local/protected, which isn't very nice. You should consider making the function a class member and pass the reference object to it, so that you can enforce proper encapsulation.
This isn't possible as SystemVerilog doesn't provide any reflection capabilities. You could probably figure this out using the VPI, but I'm not sure how complete the implementation of the VPI is for classes.
Based on what you want to do, I'd say it anyway doesn't make sense to implement such a query just to future proof your code in case some fields will one day become rand. Just as how you add the rand modifier to the field, you can also add it to the list of fields for which randomization should be disabled. Both code locations reside in the same file, so it's difficult to miss.
One certain simulator will return -1 when interrogating a state variable's rand_mode(), but this is non-standard. The LRM explicitly states that it's a compile error to call rand_mode() on non-random fields.

OOP Terminology: class, attribute, property, field, data member

I am starting studying OOP and I want to learn what constitutes a class. I am a little confused at how loosely some core elements are being used and thus adding to my confusion.
I have looked at the C++ class, the java class and I want to know enough to write my own pseudo class to help me understand.
For instance in this article I read this (.. class attribute (or class property, field, or data member)
I have seen rather well cut out questions that show that there is a difference between class property and class field for instance What is the difference between a Field and a Property in C#?
Depending on what language I am studying, is the definition of
Property
Fields
Class variables
Attributes
different from language to language?
"Fields", "class variables", and "attributes" are more-or-less the same - a low-level storage slot attached to an object. Each language's documentation might use a different term consistently, but most actual programmers use them interchangeably. (However, this also means some of the terms can be ambiguous, like "class variable" - which can be interpreted as "a variable of an instance of a given class", or "a variable of the class object itself" in a language where class objects are something you can manipulate directly.)
"Properties" are, in most languages I use, something else entirely - they're a way to attach custom behaviour to reading / writing a field. (Or to replace it.)
So in Java, the canonical example would be:
class Circle {
// The radius field
private double radius;
public Circle(double radius) {
this.radius = radius;
}
// The radius property
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
// We're doing something else besides setting the field value in the
// property setter
System.out.println("Setting radius to " + radius);
this.radius = radius;
}
// The circumference property, which is read-only
public double getCircumference() {
// We're not even reading a field here.
return 2 * Math.PI * radius;
}
}
(Note that in Java, a property foo is a pair of accessor methods called getFoo() and setFoo() - or just the getter if the property is read-only.)
Another way of looking at this is that "properties" are an abstraction - a promise by an object to allow callers to get or set a piece of data. While "fields" etc. are one possible implementation of this abstraction. The values for getRadius() or getCircumference() in the above example could be stored directly, or they could be calculated, it doesn't matter to the caller; the setters might or might not have side effects; it doesn't matter to the caller.
I agree with you, there's a lot of unnecessary confusion due to the loose definitions and inconsistent use of many OO terms. The terms you're asking about are used somewhat interchangeably, but one could say some are more general than others (descending order): Property -> Attributes -> Class Variables -> Fields.
The following passages, extracted from "Object-Oriented Analysis and Design" by Grady Booch help clarify the subject. Firstly, it's important to understand the concept of state:
The state of an object encompasses all of the (usually static) properties of the object plus the current (usually dynamic) values of each of these properties. By properties, we mean the totality of the object's attributes and relationships with other objects.
OOP is quite generic regarding certain nomenclature, as it varies wildly from language to language:
The terms field (Object Pascal), instance variable (Smalltalk), member object (C++), and slot (CLOS) are interchangeable, meaning a repository for part of the state of an object. Collectively, they constitute the object's structure.
But the notation introduced by the author is precise:
An attribute denotes a part of an aggregate object, and so is used during analysis as well as design to express a singular property of the class. Using the language-independent syntax, an attribute may have a name, a class, or both, and optionally a default expression: A:C=E.
Class variable: Part of the state of a class. Collectively, the class variables of a class constitute its structure. A class variable is shared by all instances of the same class. In C++, a class variable is declared as a static member.
In summary:
Property is a broad concept used to denote a particular characteristic of a class, encompassing both its attributes and its relationships to other classes.
Attribute denotes a part of an aggregate object, and so is used during analysis as well as design to express a singular property of the class.
Class variable is an attribute defined in a class of which a single copy exists, regardless of how many instances of the class exist. So all instances of that class share its value as well as its declaration.
Field is a language-specific term for instance variable, that is, an attribute whose value is specific to each object.
I've been doing oop for more than 20 years, and I find that people often use different words for the same things. My understanding is that fields, class variables and attributes all mean the same thing. However, property is best described by the stackoverflow link that you included in your question.
Generally fields, methods, static methods, properties, attributes and class (or static variables) do not change on a language basis... Although the syntax will probably change on a per language basis, they will be function in the way you would expect across languages (expect terms like fields/data members to be used interchangably across languages)
In C#....
A field is a variable that exists for a given instance of a class.
eg.
public class BaseClass
{
// This is a field that might be different in each instance of a class
private int _field;
// This is a property that accesses a field
protected int GetField
{
get
{
return _field;
}
}
}
Fields have a "visibility" this determines what other classes can see the field, so in the above example a private field can only be used by the class that contains it, but the property accessor provides readonly access to the field by subclasses.
A property lets you get (sometimes called an accessor) or set (sometimes called a mutator) the value of field... Properties let you do a couple of things, prevent writing a field for example from outside the class, change the visibility of the field (eg private/protected/public). A mutator allows you to provide some custom logic before setting the value of a field
So properties are more like methods to get/set the value of a field but provide more functionality
eg.
public class BaseClass
{
// This is a field that might be different in each instance of a class
private int _field;
// This is a property that accesses a field, but since it's visibility
// is protected only subclasses will know about this property
// (and through it the field) - The field and property in this case
// will be hidden from other classes.
protected int GetField
{
// This is an accessor
get
{
return _field;
}
// This is a mutator
set
{
// This can perform some more logic
if (_field != value)
{
Console.WriteLine("The value of _field changed");
_field = value;
OnChanged; // Call some imaginary OnChange method
} else {
Console.WriteLine("The value of _field was not changed");
}
}
}
}
A class or static variable is a variable which is the same for all instances of a class..
So, for example, if you wanted a description for a class that description would be the same for all instance of the class and could be accessed by using the class
eg.
public class BaseClass
{
// A static (or class variable) can be accessed from anywhere by writing
// BaseClass.DESCRIPTION
public static string DESCRIPTION = "BaseClass";
}
public class TestClass
{
public void Test()
{
string BaseClassDescription = BaseClass.DESCRIPTION;
}
}
I'd be careful when using terminology relating to an attribute. In C# it is a class that can be applied to other classes or methods by "decorating" the class or method, in other context's it may simply refer to a field that a class contains.
// The functionality of this attribute will be documented somewhere
[Test]
public class TestClass
{
[TestMethod]
public void TestMethod()
{
}
}
Some languages do not have "Attributes" like C# does (see above)
Hopefully that all makes sense... Don't want to overload you!
Firstly, you need to select a language. For example, I would recommend you to select Ruby language and community. Until you select a language, you cannot escape confusion, as different communities use different terms for the same things.
For example, what is known as Module in Ruby, Java knows as abstract class. What is known as attributes in some languages, is known as instance variables in Ruby. I recommend Ruby especially for its logical and well-designed OOP system.
Write the following in a *.rb file, or on the command line in irb (interactive Ruby interpreter):
class Dog # <-- Here you define a class representing all dogs.
def breathe # <-- Here you teach your class a method: #breathe
puts "I'm breathing."
end
def speak # <-- Here you teach your class another method: #speak
puts "Bow wow!"
end
end
Now that you have a class, you can create an instance of it:
Seamus = Dog.new
You have just created an instance, a particular dog of class Dog, and stored it in the constant Seamus. Now you can play with it:
Seamus.breathe # <-- Invoking #breathe instance method of Seamus
#=> I'm breathing.
Seamus.speak # <-- Invoking #speak instance method of Seamus
#=> Bow wow!
As for your remaining terminology questions, "property" or "attribute" is understood as "variable" in Ruby, almost always an instance variable. And as for the term "data member", just forget about it. The term "field" is not really used in Ruby, and "class variable" in Ruby means something very rarely used, which you definitely don't need to know at this moment.
So, to keep the world nice and show you that OOP is really simple and painless in Ruby, let us create an attribute, or, in Ruby terminology, an instance variable of Dog class. As we know, every dog has some weight, and different dogs may have different weights. So, upon creation of a new dog, we will require the user to tell us dog's weight:
class Dog
def initialize( weight ) # <-- Defining initialization method with one argument 'weight'
#weight = weight # <-- Setting the dog's attribute (instance variable)
end
attr_reader :weight # <-- Making the dog's weight attribute visible to the world.
end
Drooly = Dog.new( 16 ) # <-- Weight now must provide weight upon initialization.
Drooly.weight # <-- Now we can ask Drooly about his weight.
#=> 16
Remember, with Ruby (or Python), things are simple.
I discovered in my question that Properties as defined in .Net are just a convenience syntax for code, and they are not tied to underlying variables at all (except for Auto-Implemented Properties, of course). So, saying "what is the difference between class property and class field" is like saying: what is the difference between a method and an attribute. No difference, one is code and the other is data. And, they need not have anything to do with each other.
It is really too bad that the same words, like "attribute" and "property", are re-used in different languages and ideologies to have starkly different meanings. Maybe someone needs to define an object-oriented language to talk about concepts in OOP? UML?
In The Class
public class ClassSample
{
private int ClassAttribute;
public int Property
{
get { return ClassAttribute; }
set { ClassAttribute = value; }
}
}
In the Program
class Program
{
static void Main(string[] args)
{
var objectSample = new ClassSample();
//Get Object Property
var GetProperty = objectSample.Property;
}
}