AnyLogic inject agents from existing population with characteristics - anylogic

I created a population with objects from a database with individual characteristics.
I am trying that the objects with a specific value are injected into a source for process-modelling.
("ankunftszeit" means "arrival time")
for (mp_lkw l : pop_mp_lkw){
if (l.ankunftszeit == getTime()){
source_mp_lkw.inject(mp_lkw l, 1, false, false);
}
}
But somehow an Error occurs and I cannot find any solution...
It says taht the inject() only accepts integers
The method inject(int) in the type Source<mp_lkw> is not applicable for the arguments (mp_lkw, int, boolean, boolean)
Syntax error on token "l", delete this token
Where is my mistake and how can it be corrected?

Not sure I understand your issue, but if the agents already exist, you shouldn't use a source, instead use an enter block, and then change your code to (even though this code seems like a terrible idea... instead you should use dynamic events but I'm not sure your purpose)
for (mp_lkw l : pop_mp_lkw){
if (l.ankunftszeit == getTime()){
enter.take(l);
}
}

Related

How to create a newtype operation in Q#?

I am working with Q# on a generic grover search implementation and I wanted to define a custom Oracle type
newtype ModelOracle = ((Qubit[], Qubit[], Int[], Qubit) => Unit);
// ...
function GroverMaxMatchingOracle(search_set: (Int,Int)[], vertices: Int[], marked_pts: Bool[]): ModelOracle {
return ModelOracle(ApplyMaxMatchingOracle(_,_,_,_,search_set, vertices, marked_pts));
}
that will fit into my model. But when I try to use it (kind of in the same way as they use StateOracle in the DatabaseSearch sample), I get an error saying that the new type ModelOracle is not a valid operation
fail: Microsoft.Quantum.IQSharp.Workspace[0]
QS5021: The type of the expression must be a function or operation type. The given expression is of type OracleHelper.ModelOracle.
What am I getting wrong about the types here?
It looks like you have defined things ok, so it might be that you have to unwrap the user defined type first with the ! operator.
So where you are using it you may have to do something like GroverMaxMatchingOracle!(...)
Another approach could be to name the tuple in your UDT:
newtype ModelOracle = (Apply: (Qubit[], Qubit[], Int[], Qubit) => Unit);
Then wherever you want to use it you can directly used the named item Apply like this: GroverMaxMatchingOracle::Apply(...)
If its helpful, there is a section on user defined types (8.2) in the book #cgranade and I are working on, Learn Quantum Computing with Python and Q#

get an element index in ocl collection ? [ocl_Eclipse]

i'm working on the following domain :
my domain diagram
i want to express the folowing constraint :
" a succession of two actions of Type Rotate is not allowed "
i tried this declaration but eclipse is not recognizing indexOf(element ) :
class Choreography
{
property actions : Action[+|1] { ordered composes };
attribute name : String[?];
/*Succession of two actions of Type is not permitted */
invariant rotate_succ:
self.actions->asSequence()->forAll(a1:Action,a2:Action
|
a1.oclIsTypeOf(Rotate) and (indexOf(a1)=indexOf(a2)+1) implies
not a2.oclIsTypeOf(Rotate)
)
;
Does anyone have an idea about how to work with the index of a random element from an ocl colletion ?
The
OrderedCollection(T):indexOf(obj : OclAny[?]) : Integer[1]
operation requires an OrderedCollection (Sequence/OrderedSet) as its source and an OclAny as its argument. You have not identified a source so OCL will consider first an implicit iterator leading to an
a1.indexOf(a1)
a2.indexOf(a1)
ambiguity which would be an error if an Action had an indexOf operation. Then it considers an implicit self which also fails since there is no Choreography.indexOf() operation.
I presume you meant
self.actions->indexOf(a1)
etc etc, or more readably put self.actions in a let-variable for multi-use.
(Use of oclIsTypeOf is very rarely right. Use oclIsKindOf unless you have a specific intent.)
(self.actions is already an OrderedCollection so there is no need for the asSequence()).
Your use of indexOf will lead to quadratic performance. Better to use indexes - something like:
let theActions = self.actions in
Sequence{1..theActions->size()-1}->forAll(index |
theActions->at(index).oclIsKindOf(Rotate)
implies not theActions->at(index+1).oclIsKindOf(Rotate))

Supporting "recursive objects" in lua

I'm fairly new to lua and have the following problem with an assignment from a class:
We currently extend lua to support objects and inheritance. The Syntax for that is
Class{'MyClass',
attribute1 = String,
attribute2 = Number
}
Class{'MySubClass', MyClass,
attribute3 = Number
}
This works perfectly fine. The real problem lies within the next task: We should support "recursive types", that means a call like
Class{'MyClass', attribute = MyClass}
should result in an class with a field of the same type as the class. When this "class-constructor" is called the variable MyClass is nil, thats why the parameter table doesnt't have an entry attribute. How is it possible to access this attribute?
My first thought was using some kind of nil-table which gets returned every time the global __index is called with an unset key. This nil-table should behave like the normal nil, but can be checked for in the "class-constructor". The problem with this approach are comparisons like nil == unknown. This should return true, but as the __eq meta method of the nil-table is never called we cannot return true.
Is there another approach I'm currently just ignoring? Any hint is greatly appreciated.
Thanks in advance.
Edit:
Here the relevant part of the "testfile". The test by which the code is rated in class is another one and gets published later.
three = 3
print( three == 3 , "Should be true")
print( unknown == nil , "Should be true" )
Class{'AClass', name = String, ref = AClass}
function AClass:write()
print("AClass:write(), name of AClass:", self.name)
end
aclass = AClass:create("A. Class")
aclass:write()
Since MyClass is just a lookup in the global table (_G), you could mess with its metatable's __index to return a newly-defined MyClass object (which you would later need to fill with the details).
However, while feasible, such an implementation is
wildly unsafe, as you could end up with an undefined class (or worse, you may end up inadvertantly creating an infinite lookup loop. Trust me, I've been there)
very hard to debug, as every _G lookup for a non-existing variable will now return a newly created class object instead of nil (this problem could somewhat be reduced by requiring that class names start with an uppercase character)
If you go that route, be sure to also override __newindex.
How about providing the argument in string form?
Class{'MyClass', attribute = 'MyClass'}
Detect strings inside the implementation of Class and process them with _G[string] after creating the class
Or alternatively, use a function to delay the lookup:
Class{'MyClass', attribute = function() return MyClass end}

Can data be saved between calls to the openCPU server?

I understand that the interface to OpenCPU is RESTful. Nevertheless, I would like to save data between function calls, if possible.
I naively created the following package:
vals <- c()
fnInit <- function() {
vals <<- c('a','b','c')
}
but I got the error: cannot change value of locked binding for 'vals' when I called the fnInit function. I understand why this is happening.
I then tried:
fnBoth <- local({
vals <- c('a','b','c')
function(which) {
if (which == 0) {
vals
} else if (which == 1) {
vals <<- c(vals,'d')
vals
}
}
})
but every time I POST to the fnBoth function with which = 1, I get the same response:
[1] "a" "b" "c" "d"
If I call the function again, I get the same answer. So, it would seem that the value vals is being reset each time.
My question is: Can data be saved between function calls? The above attempts are not meant to be exhaustive - maybe there's another technique? Or, should I simply save the value to disk?
Thanks
It is not completely clear to me what you are trying to accomplish, perhaps you can elaborate a bit on the type of application you wish to build.
OpenCPU supports chaining of function calls to calculate e.g. f(g(x), h(y)). This is done by passing the session ID of a completed call as an argument to a subsequent one. Have a look at the docs about argument formats: https://public.opencpu.org/api.html#api-arguments. It includes an example that illustrates this by calculating summary(read.csv("mydata.csv")):
#upload local file mydata.csv
curl https://public.opencpu.org/ocpu/library/utils/R/read.csv -F "file=#mydata.csv"
#replace session id with returned one above
curl https://public.opencpu.org/ocpu/tmp/x067b4172/R/.val/print
curl https://public.opencpu.org/ocpu/library/base/R/summary -d 'object=x067b4172'
The first request calls the read.csv function which returns a dataframe. In the last line, we call the summary function where we set the object argument equal to the output of the previous call (i.e. the data frame) by passing the session ID.

How to bind parameters in replaced expression nodes in Entity Framework on the fly

I'm trying to replace a function call like (simplified) Utility.GetString(MyEntity.SomePropertyWithRelatedEntity)=="abc" with an expression visitor into something like p => p.SubRelatedEntities.FirstOrDefault(sre => sre.SomeFlag==true).SomePropertyWithRelatedEntity.
It means, the datamodel goes like:
MyEntity -> RelatedEntity -> SubRelatedEntity
I'm trying to return a string value from the SubRelatedEntity, based on some rules in the RelatedEntity, so I don't have to re-write / copy/paste the whole filtering rules in every usage; that's why I put inside a "call-signature", so my expression visitor can identify it and replace the fake-call to Utility.GetString to some complicated lambda expressions.
My expression visitor contains something like:
public override Expression Visit(Expression node)
{
if (node == null)
return null;
Expression result = null;
if (node.NodeType == ExpressionType.Call)
{
MethodCallExpression mce = node as MethodCallExpression;
if (mce.Method.DeclaringType == typeof(Utility) && mce.Method.Name == "GetString")
{
Expression<Func<RelatedEntity, string>> exp = re => re.SubRelatedEntities.FirstOrDefault(sre => sre.SomeFlag == true).SomeStringValue;
result = exp.Body;
}
else
result = base.Visit(node);
}
else
result = base.Visit(node);
return result;
}
Now, the problem is, the "sre" parameter is not bound when called the injected lambda expression. After much research, I see the lambda parameters should be replaced with another expression visitor, specifically searching for the new parameters and replacing them with the old ones. In my situation, however, I don't have an "old parameter" - I have the expression MyEntity.SomePropertyWithRelatedEntity (e.g. an property filled with the related entities) which I need to insert somehow in the generated lambda.
I hope my problem is understandable. Thank you for any insights!
After getting no answers for long time and trying hard to find a solution, I've solved it at the end :o)! It goes like this:
The newly injected lambda expression gets an ParameterExpression - well, this is a 'helper', used when directly calling the lambda, what I don't want (hence, 'parameter not bound' exception when ToEnumerable is called). So, the clue is to make a specialized ExpressionVisitor, which replaces this helper with the original expression, which is of course available in the Arguments[] for the method call, which I try to replace.
Works like a charm, like this you can reuse the same LINQ expressions, something like reusable sub-queries, instead of writing all the same LINQ stuff all time. Notice as well, that expression calling a method is not allowed in EF, in Linq2Sql it worked. Also, all the proposed web articles only replace the parameter instances, when constructing/merging more LINQ expressions together - here, I needed to replace a parameter with an faked-method-call argument, e.g. the method should not be called, it only stands for a code-marker, where I need to put my LINQ sub-query.
Hope this helps somebody, at the end it's pretty simple and logical, when one knows how the expression trees are constructed ;-).
Bye,
Andrej