Manual casting of agents and accessing its parameter of type SelectOutputOut in AnyLogic? - anylogic

I understood that I can insert different types of agents in the same block by changing the agent type in the whole process to the generic Agent (works well thanks to Amy). snapshot
But, I am stuck on how to get them out using a manual casting for the process selectOutputIn1. Each Agent type has a parameter called p_new_location with type SelectOutputOut.
What I need help in
passing what is equivalent to agent.p_new_location if properly casted through selectOutputIn1.
What I have tried
creating a function with manual casting:
if( agent instanceof Wife){
return ((Wife)agent).p_new_location ;
} else if(agent instanceof Child_M){
return ((Child_M)agent).p_new_location ;
} else if(agent instanceof Child_F){
return ((Child_F)agent).p_new_location ;}
how it looks with the error
Unfortunately, as you can see there is an error saying the method must return a result of type SelectOutputOut although it is already defined.
The parameter type in each class looks like exactly like this. And from inside the simulation, it looks like this before passing the value and like this after passing its value. Furthermore, I noticed that the value of an uncommon parameter type like SelectOutputOut, is not showing during the simulation as shown here. As you can see parameters (age, countDb and taken) are all there with their values but, not p_new_location.
The Solution
Thanks to Amy Again :)
The compiler is seeing if / else if / else if. What if none of those are true? If your last else if is the only option, just change that to an else or put in appropriate code for what you want to do.
This is how the code looks like now
if( agent instanceof Wife){
return ((Wife)agent).p_new_location ;
} else if(agent instanceof Child_M){
return ((Child_M)agent).p_new_location ;
} else{
return ((Child_F)agent).p_new_location ;}
Thanks inAdvance;

Yes, AnyLogic can easily handle multiple agent types in a single process block. A few things to keep in mind:
Make sure the process block is set to handle a generic type "Agent" or the parent class of mother, father, child.
Since you have multiple agent types flowing through the same blocks, you should be prepared to do some casting to get any class specific information.
AnyLogic agents cannot be in more than one flowchart block at a time, even though they can be in many collections. They can also be in NO flowchart blocks. Before you send an agent to an enter block, you must first remove it from any other block it is in (if it is in one). For example, if all you wives were in a queue, you would need to remove the wife agent from the queue before calling your enter.take( wife ) line of code.

Related

AnyLogic inject() doesn't accept type

I am trying to inject with a function objects from a population into a source block.
In the function I used this inject() function:
for (mp_lkw mp : mplkws)
{
if (dateToTime(mp.ankunft) <= time()) {
remove_mplkws(mp);
source1.inject(mp);
}
}
Now my source should accept that injection, but an error occurs, that it is only applicable for Integers
Unresolved compilation problem:
The method inject(int) in the type Source<mp_lkw> is not applicable for the arguments (mp_lkw)
I wonder why it doesnt accept my agent type even though the settings in source for "New agent:" and "Agent type:" are set to my agent "mp_lkw"
This is not how the inect() method works. It only lets you specify the number of agents that the Source block creates when you call it. But the details of the agents themselves are set by the Source block.
In your case (where an agent already exists and just needs to start a new flow chart), you replace the Source block with an "Enter" block.
In the code, you call myEnterBlock.take(mp);

Auto-complete a Single created from another Observable

I have a long-running operation that returns a value in code I don't control. I need that value to be published to things that ask for it. For this purpose I am using a BehaviorSubject:
var subject: Subject<Value>? = null
fun retrieveValue(): Single<Value> {
if (subject == null) {
subject = BehaviorSubject.create<Value>()
someOtherThing.retrieveValueAsync { value ->
subject.onNext(value)
}
}
return subject.singleOrError()
}
This lets me perform the operation only once and send the result as a single to all future interested parties. However, it does not work. The single will not emit a value until I call:
subject.onComplete()
But this is a problem because once the subject is completed future things can no longer subscribe to it.
What is the appropriate way to cache a value from another observable and pass it to a Single? If there was a way to have a subject automatically complete once its source observable emitted a value that would work. Single.cache() also looks promising, but I'm unsure how I would handle the fact that my value comes in asynchronously in that case.
It feels like I'm missing something silly.
There is a SingleSubject for this case.
If you don't want experimental code in your codebase, you can use ReplaySubject.createWithSize(1) and call onComplete without losing the last value, then convert it to Single.

Breaking when a method returns null in the Eclipse debugger

I'm working on an expression evaluator. There is an evaluate() function which is called many times depending on the complexity of the expression processed.
I need to break and investigate when this method returns null. There are many paths and return statements.
It is possible to break on exit method event but I can't find how to put a condition about the value returned.
I got stuck in that frustration too. One can inspect (and write conditions) on named variables, but not on something unnamed like a return value. Here are some ideas (for whoever might be interested):
One could include something like evaluate() == null in the breakpoint's condition. Tests performed (Eclipse 4.4) show that in such a case, the function will be performed again for the breakpoint purposes, but this time with the breakpoint disabled. So you will avoid a stack overflow situation, at least. Whether this would be useful, depends on the nature of the function under consideration - will it return the same value at breakpoint time as at run time? (Some s[a|i]mple code to test:)
class TestBreakpoint {
int counter = 0;
boolean eval() { /* <== breakpoint here, [x]on exit, [x]condition: eval()==false */
System.out.println("Iteration " + ++counter);
return true;
}
public static void main(String[] args) {
TestBreakpoint app = new TestBreakpoint();
System.out.println("STARTED");
app.eval();
System.out.println("STOPPED");
}
}
// RESULTS:
// Normal run: shows 1 iteration of eval()
// Debug run: shows 2 iterations of eval(), no stack overflow, no stop on breakpoint
Another way to make it easier (to potentially do debugging in future) would be to have coding conventions (or personal coding style) that require one to declare a local variable that is set inside the function, and returned only once at the end. E.g.:
public MyType evaluate() {
MyType result = null;
if (conditionA) result = new MyType('A');
else if (conditionB) result = new MyType ('B');
return result;
}
Then you can at least do an exit breakpoint with a condition like result == null. However, I agree that this is unnecessarily verbose for simple functions, is a bit contrary to flow that the language allows, and can only be enforced manually. (Personally, I do use this convention sometimes for more complex functions (the name result 'reserved' just for this use), where it may make things clearer, but not for simple functions. But it's difficult to draw the line; just this morning had to step through a simple function to see which of 3 possible cases was the one fired. For today's complex systems, one wants to avoid stepping.)
Barring the above, you would need to modify your code on a case by case basis as in the previous point for the single function to assign your return value to some variable, which you can test. If some work policy disallows you to make such non-functional changes, one is quite stuck... It is of course also possible that such a rewrite could result in a bug inadvertently being resolved, if the original code was a bit convoluted, so beware of reverting to the original after debugging, only to find that the bug is now back.
You didn't say what language you were working in. If it's Java or C++ you can set a condition on a Method (or Function) breakpoint using the breakpoint properties. Here are images showing both cases.
In the Java example you would unclik Entry and put a check in Exit.
Java Method Breakpoint Properties Dialog
!
C++ Function Breakpoint Properties Dialog
This is not yet supported by the Eclipse debugger and added as an enhancement request. I'd appreciate if you vote for it.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=425744

Can we say that using "pass by reference" is always better than "pass by value"?

In C# or php or other languages, there are 2 ways to pass a value to a function, pass it by value and pass it by referece.
Pass parameter by value make the value copied in the function, so this need a extra memory space although the memory space will be reclaimed after running outside the function.
But passing parameter by reference no need to copy a value, it's save the memory. From this perspective, can we say that using "pass by reference" is always better than "pass by value"?
Pass by reference and pass by value are semantically different and sometimes one is correct approach and sometimes the other one is. In many cases the task at hand already prescribes which approach is needed and in contexts where only one option is supported you often need to manually work around it (e.g., if you need a copy in Java you'll need to clone() the object).
In the context of generic functions the answer is rather the opposite way of your proposed preference: pass arguments of deduced type by value! The reason is that you can use something like std::ref() to obtain reference semantics but there is no way to get value semantics if the functions use reference semantics.
No.
There are tons of cases where you'd want to pass by value.
An example might be when you need both const Type& and Type&& overloads. Passing by value just handles both cases without having to duplicate any code:
void function(Object o) { do_something_with(std::move(o)); }
As opposed to:
void function(Object&& o) { do_something_with(std::move(o)); }
void function(const Object& o) { do_something_with(Object(o)); }
Of course there is much more to the subject, but since you're only asking for "is it always better?" I feel a single disproving example is enough. ;)
Edit: the question was originally tagged c++ hence my very specific answer.
Another, more language-agnostic example would be when you need to make a copy of your parameter because you don't want to modify the original object:
void function(int& val) { int v2 = val; modify(v2); use(v2); }
// vs
void function(int val) { modify(val); use(val); }
You get the idea...
Pass by reference requires copying a reference to the object. If that reference is comparable in cost to the object itself, then the benefit is illusory. Also, sometimes you need a copy of the object, and passing by value provides you one.
Also, there's a key error in the reasoning in the question. If passing by value, and there is no need to copy the value, nothing requires that the value actually be copied. Most languages have an "as-if" rule that states that the program only has to act as if the compiler did what you ask for. So if the copy can be avoided, the compiler is free to avoid it. If the copy can't be avoided, then you needed the copy.

Is there any way to access the current test's parameters (apart from the parameters themselves)?

If I write a parameterized NUnit test, using something like [TestCaseSource] or [ValueSource], NUnit will pass the parameters directly to my test method. But is there any other way to access those parameters, e.g. from SetUp, or from a helper method (without having to explicitly pass the parameter value to that helper method)?
For example, suppose I have three different scenarios (maybe it's "rising rates", "falling rates", and "constant rates"). I'm writing tests for a particular calculation, and some tests will have the same behavior in all three scenarios; others in two of the three (and I'll write a second test for the other scenario); others will have a separate test for each scenario. Parameterized tests seem like a good way to model this; I can write a strategy object for each scenario, and parameterize the tests based on which scenarios each test should apply to.
I can do something like this:
public IEnumerable<RateStrategy> AllScenarios {
get {
yield return new RisingRatesStrategy();
yield return new FallingRatesStrategy();
yield return new ConstantRatesStrategy();
}
}
[TestCaseSource("AllScenarios")]
public void SomethingThatIsTheSameInAllScenarios(RateStrategy scenario) {
InitializeScenario(scenario);
... arrange ...
... act ...
... assert ...
}
The downside to this is that I need to remember to call InitializeScenario in every test. This is easy to mess up, and it also makes the tests harder to read -- in addition to the attribute that says exactly which scenarios this test applies to, I also need an extra line of code cluttering up my test, saying that oh yeah, there are scenarios.
Is there some other way I could access the test parameters? Is there a static property, similar to those on TestContext, that would let me access the test's parameters from, say, my SetUp method, so I could make my tests more declarative (convention-based) and less repetitive?
(TestContext looked promising, but it only tells me the test's name and whether it passed or failed. The test's parameters are sort of there, but only as part of a display string, not as actual objects; I can't grab the strategy object and start calling methods on it.)