A way to restrict the domain of a variable? - gams-math

I have a code snippet for a transport problem like:
set i /1*50/
d /1*10/
Alias(i,j,k)
parameter
edge(i,j)
distance(i,j)
possible(i,d) 'a collection of possible nodes for d'
possible_edge(i,j,d) 'a collection of possible edge for d';
binary variable x(i,j,d);
I import all the edges from an excel file. But to reduce the number of variables, I'd like to create another parameter like possible node and possible edge.
suppose we run a shortest path algorithm form a source node i and we define possible(i,d) to be all i where distance(i,j) is smaller than a predefined threshold.
In other words, when the network node become larger and larger, I want to find out if there's any possibility to not define x(i,j,d) for every (i,j) combination? Like forcing to only have x(i,j,d)$possible_edge(i,j,d)?? Is there anything like this??

Yes, you can limit the domain of variables in the model statement, like this
Model m / all, x(possible_edge) /;
So, here, the variable x would be limited by the set possible_edge wherever it occurs in model m. Note, that possible_edge must be a set here, not a parameter.
You can find more info about this concept here: https://www.gams.com/latest/docs/UG_ModelSolve.html#UG_ModelSolve_LimitedDomain

Related

Run-State values within shape script EA

Enterprise Architect 13.5.
I made MDG technology extending Object metatype. I have a shape script for my stereotype working well. I need to print several predefined run-state parameters for element. Is it possible to access to run-state params within Shape ?
As Geert already commented there is no direct way to get the runstate variables from an object. You might send a feature request to Sparx. But I'm pretty sure you can't hold your breath long enough to see it in time (if at all).
So if you really need the runstate in the script the only way is to use an add-in. It's actually not too difficult to create one and Geert has a nice intro how to create it in 10 minutes. In your shape script you can print a string restult returned from an operation like
print("#addin:myAddIn,pFunc1#")
where myAddIn is the name of the registered operation and pFunc1 is a parameter you pass to it. In order to control the script flow you can use
hasproperty('addin:myAddIn,pFunc2','1')
which evaluates the returned string to match or not match the string 1.
I once got that to work with no too much hassle. But until now I never had the real need to use it somewhere in production. Know that the addin is called from the interpreted script for each shaped element on the diagram and might (dramatically) affect rendering times.

Is it possible to preserve variable names when writing and reading term programatically?

I'm trying to write an SWI-Prolog predicate that applies numbervars/3 to a term's anonymous variables but preserves the user-supplied names of its non-anonymous variables. I eventually plan on adding some kind of hook to term_expansion (or something like that).
Example of desired output:
?- TestList=[X,Y,Z,_,_].
> TestList=[X,Y,Z,A,B].
This answer to the question Converting Terms to Atoms preserving variable names in YAP prolog shows how to use read_term to obtain as atoms the names of the variables used in a term. This list (in the form [X='X',Y='Y',...]) does not contain the anonymous variables, unlike the variable list obtained by term_variables, making isolation of the anonymous variables fairly straightforward.
However, the usefulness of this great feature is somewhat limited if it can only be applied to terms read directly from the terminal. I noticed that all of the examples in the answer involve direct user input of the term. Is it possible to get (as atoms) the variable names for terms that are not obtained through direct user input? That is, is there some way to 'write' a term (preserving variable names) to some invisible stream and then 'read' it as if it were input from the terminal?
Alternatively... Perhaps this is more of a LaTeX-ish line of thinking, but is there some way to "wrap" variables inside single quotes (thereby atom-ifying them) before Prolog expands/tries to unify them as variables, with the end result that they're treated as atoms that start with uppercase letters rather than as variables?
You can use the ISO core standard variable_names/1 read and write option. Here is some example code, that replaces anonymous variables in a variable name mapping:
% replace_anon(+Map, +Map, -Map)
replace_anon([_=V|M], S, ['_'=V|N]) :- member(_=W, S), W==V, !,
replace_anon(M, S, N).
replace_anon([A=V|M], S, [A=V|N]) :-
replace_anon(M, S, N).
replace_anon([], _, []).
variable_names/1 is ISO core standard. It was always a read option. It then became a write option as well. See also: https://www.complang.tuwien.ac.at/ulrich/iso-prolog/WDCor3
Here is an example run:
Welcome to SWI-Prolog (threaded, 64 bits, version 7.7.25)
?- read_term(X,[variable_names(M),singletons(S)]),
replace_anon(M,S,N),
write_term(X,[variable_names(N)]).
|: p(X,Y,X).
p(X,_,X)
To use the old numbervars/3 is not recommended, since its not compatible with attribute variables. You cannot use it for example in the presence of CLP(FD).
Is it possible to get (as atoms) the variable names for terms that are not obtained through direct user input?
if you want to get variable names from source files you should read them from there.
The easiest way to do so using term expansion.
Solution:
read_term_from_atom(+Atom, -Term, +Options)
Use read_term/3 to read the next term from Atom.
Atom is either an atom or a string object.
It is not required for Atom to end with a full-stop.
Use Atom as input to read_term/2 using the option variable_names and return the read term in Term and the variable bindings in variable_names(Bindings).
Bindings is a list of Name = Var couples, thus providing access to the actual variable names. See also read_term/2.
If Atom has no valid syntax, a syntax_error exception is raised.
write_term( Term ) :-
numbervars(Term, 0, End),
write_canonical(Term), nl.

SWI prolog make set of variables name with rbtrees or others means

I have got a term from which I want to get set of variables name.
Eg. input: my_m(aa,b,B,C,max(D,C),D)
output: [B,C,D] (no need to be ordered as order of appearance in input)
(That would call like set_variable_name(Input,Output).)
I can simply get [B,C,D,C,D] from the input, but don't know how to implement set (only one appearance in output). I've tried something like storing in rbtrees but that failed, because of
only_one([],T,T) :- !.
only_one([X|XS],B,C) :- rb_in(X,X,B), !, only_one(XS,B,C).
only_one([X|XS],B,C) :- rb_insert(B,X,X,U), only_one(XS,U,C).
it returns tree with only one node and unification like B=C, C=D.... I think I get it why - because of unification of X while questioning rb_in(..).
So, how to store only once that name of variable? Or is that fundamentally wrong idea because we are using logic programming? If you want to know why I need this, it's because we are asked to implement A* algorithm in Prolog and this is one part of making search space.
You can use sort/2, which also removes duplicates.

conditional component declaration and a following if equation

I am trying to build a model that will have slightly different equations based on whether or not certain components exist (in my case, fluid ports).
A code like the following will not work:
parameter Boolean use_component=false;
Component component if use_component;
equation
if use_component then
component.x = 0;
end if;
How can I work around this?
If you want to use condition components, there are some restrictions you need to be aware of. Section 4.4.5 of the Modelica 3.3 specification sums it up nicely. It says "If the condition is false, the component, its modifiers, and any connect equations
involving the component, are removed". I'll show you how to use this to solve your problem in just a second, but first I want to explain why your solution doesn't work.
The issue has to do with checking the model. In your case, it is obvious that the equation component.x and the component component either both exist or neither exist. That is because you have tied them to the same Boolean variable. But what if you had don't this:
parameter Real some_number;
Component component if some_number*some_number>4.0;
equation
if some_number>=-2 and some_number<=2 then
component.x = 0;
end if;
We can see that this logically identical to your case. There is no chance for component.x to exist when component is absent. But can we prove such things in general? No.
So, when conditional components were introduced, conservative semantics were implemented which can always trivially ensure that the sets of variables and equations involved never get "out of sync".
Let us to return to what the specification says: "If the condition is false, the component, its modifiers, and any connect equations
involving the component, are removed"
For your case, the solution could potentially be quite simple. Depending on how you declare "x", you could just add a modification to component, i.e.
parameter Boolean use_component=false;
Component component(x=0) if use_component;
The elegance of this is that the modification only applies to component and if component isn't present, neither is the modification (equation). So the variable x and its associated equation are "in sync". But this doesn't work for all cases (IIRC, x has to have an input qualifier for this to work...maybe that is possible in your case?).
There are two remaining alternatives. First, put the equation component.x inside component. The second is to introduce a connector on component that, if connected, will generate the equation you want. As with the modification case (this is not a coincidence), you could associate x with an input connector of some kind and then do this:
parameter Boolean use_component;
Component component if use_component;
Constant zero(k=0);
equation
connect(k.y, component.x);
Now, I could imagine that after considering all three cases (modification, internalize equation and use connect), you come to the conclusion that none of them will work. If this is the case, then I would humbly suggest that you have an issue with how you have designed the component. The reason these restrictions arise is related to the necessity to check components by themselves for correctness. This requires that the component be complete ("balanced" in the terminology of the specification).
If you cannot solve the problem with approaches I mentioned above, then I suspect you really have a balancing issue and that you probably need to redefine the boundaries of your component somehow. If this is the case, I would suggest you open another question here with details of what you are trying to do.
I think that the reason why this will not work is that the parser will look for the declaration of the variable "component.x" that, if the component is not active, does not exist. It does not work even if you insert the "Evaluate=true" in the annotation.
The cleanest solution in my opinion is to work at equation level and enable different sets of equations in the same block. You can create a wrapper model with the correct connectors and paramenters, and then if it is a causal model for example you can use replaceable classes in order to parameterize the models as functions, or else, in case of acausal models, put the equations inside if statements.
Another possible workaround is to place two different models inside one block, so you can use their variables into the equation section, and then build up conditional connections that will enable the usage of the block with the choosen behaviour. In other words you can build up a "wrap model" with two blocks inside, and then place the connection equations to the connectors of the wrap model inside if statements. Remember to build up the model so that there will be a consistent system of quations even for the blocks that are not used.
But this is not the best solution, because if the blocks are big you will have to wait longer time for compilation since everything will be compiled.
I hope this will help,
Marco
You can also make a dummy component that is not visible in the graphical layer:
connector DummyHeatPort
"Dummy heatport to facilitate optional heatport. Use this with a conditional heatport by connecting it to the heatport. Then use the -DummyHeatPort.Q_flow in the thermal energy balance."
Modelica.SIunits.Temperature T "Port temperature";
flow Modelica.SIunits.HeatFlowRate Q_flow
"Heat flow rate (positive if flowing from outside into the component)";
end DummyHeatPort;
Then when this gets used in a two port model
Modelica.Thermal.HeatTransfer.Interfaces.HeatPort_a heatport if use_heat_port;
DummyHeatPort dummy_heatport;
...
equation
flowport_a.H_flow + flowport_b.H_flow - dummy_heatport.Q_flow = storage
"thermal energy balance";
connect(dummy_heatport, heatport);
This way the heatport gets used if present but does not cause an error otherwise.

can a variable have multiple values

In algebra if I make the statement x + y = 3, the variables I used will hold the values either 2 and 1 or 1 and 2. I know that assignment in programming is not the same thing, but I got to wondering. If I wanted to represent the value of, say, a quantumly weird particle, I would want my variable to have two values at the same time and to have it resolve into one or the other later. Or maybe I'm just dreaming?
Is it possible to say something like i = 3 or 2;?
This is one of the features planned for Perl 6 (junctions), with syntax that should look like my $a = 1|2|3;
If ever implemented, it would work intuitively, like $a==1 being true at the same time as $a==2. Also, for example, $a+1 would give you a value of 2|3|4.
This feature is actually available in Perl5 as well through Perl6::Junction and Quantum::Superpositions modules, but without the syntax sugar (through 'functions' all and any).
At least for comparison (b < any(1,2,3)) it was also available in Microsoft Cω experimental language, however it was not documented anywhere (I just tried it when I was looking at Cω and it just worked).
You can't do this with native types, but there's nothing stopping you from creating a variable object (presuming you are using an OO language) which has a range of values or even a probability density function rather than an actual value.
You will also need to define all the mathematical operators between your variables and your variables and native scalars. Same goes for the equality and assignment operators.
numpy arrays do something similar for vectors and matrices.
That's also the kind of thing you can do in Prolog. You define rules that constraint your variables and then let Prolog resolve them ...
It takes some time to get used to it, but it is wonderful for certain problems once you know how to use it ...
Damien Conways Quantum::Superpositions might do what you want,
https://metacpan.org/pod/Quantum::Superpositions
You might need your crack-pipe however.
What you're asking seems to be how to implement a Fuzzy Logic system. These have been around for some time and you can undoubtedly pick up a library for the common programming languages quite easily.
You could use a struct and handle the operations manualy. Otherwise, no a variable only has 1 value at a time.
A variable is nothing more than an address into memory. That means a variable describes exactly one place in memory (length depending on the type). So as long as we have no "quantum memory" (and we dont have it, and it doesnt look like we will have it in near future), the answer is a NO.
If you want to program and to modell this behaviour, your way would be to use a an array (with length equal to the number of max. multiple values). With this comes the increased runtime, hence the computations must be done on each of the values (e.g. x+y, must compute with 2 different values x1+y1, x2+y2, x1+y2 and x2+y1).
In Perl , you can .
If you use Scalar::Util , you can have a var take 2 values . One if it's used in string context , and another if it's used in a numerical context .