Design pattern import files alters behaviour - import

I am developing an application where the program can do a number of operations. It relies on a XML file being imported and DB connection established. However, some of the functions can work without an xml file imported, and some can work only if the XML is imported or only if the DB is connected.
So, my question is what design pattern I should use in order to model this ? I read about the state pattern where an object's behaviour changes relative to the current state. Is this a good way of doing it ? For example, I can have several states : XML_FILE_IMPORTED_ONLY, DB_CONNECTED_ONLY, XML_IMPORTRED_AND_DB_CONNECTED, NOTHING_IMPORTED and based on the current state of the object relevant functions will be available ?
Any help will be much appreciated.
Regards,
Petar

You have two state machines, each controlling a portion of your overall state. Each state machine will perform transitions independent of the other.
XML Imported Statemachine
Initial state: Not Imported
Not Imported. transitions: "import happens" -> Imported.
Imported. transitions: "unload" -> Not Imported.
DB Connection Statemachine
Initial State: Not Connected
Not Connected. transitions: "connect succeeded" -> Connected.
Connected. transitions: "disconnect" -> Not Connected.
Edit: State machines are overkill for this problem.
The state machines in question each have two states with one transition in each direction. A much better way to represent this situation would be to use a boolean variable.
boolean dbConnected;
boolean xmlImported;

Related

How do I Refresh AnyLogic ModelDatabase from code?

I have linked many parameters in my model to values in the internal ModelDatabase. This works great.
Now I want to allow the user to import a new "Input File" for a specific scenario. I have added a fileChooser element on the Simulation Experiment screen and in the onUpload action I use the ModelDatabase.importFromExternalDB to upload the relevant sheet to the relevant table.
However, this does not seem to work. Initially I thought that the update simply did not happen but when I stop the model in the AnyLogic IDE and start it again in the IDE, the new values are used.
It appears as if the update only happens on startup/close and that the database is "static" while running. I did set the auto-commit parameter to true on the importFromExternalDB function, but this made no difference.
Is there a function I can call to force a "refresh" of the internal database?
You probably load the data at runtime using the default code such as selectFrom("some String with query")
However, these always load from the cached dbase to speed things up.
Instead, you must force AnyLogic to load from the live dbase using an additional argument. In this example, it would be selectFrom(false, "some String query")
This is also documented in the help:
So go through all queries in your model and add the appropriate boolean arg to force-load from the non-cached dbase.

State Machine - What is the best way to define boolean for different states?

I have got the following question which is pondering me for some time. I'm new to state machine modeling so would really appreciate your help, ideas, and suggestions.
Let's say I have a "Valve" which can be in state "opened" or "closed". Now when I model the state machine.
Should I define two booleans for each state?
bool opened;
bool closed;
Hence, I should use both booleans for each state?
Example: State "opened" will have the booleans--> opened = 1 and closed = 0;
OR
Simply can I define only one boolean variable?
bool opened;
Example: State "opened" will have only one boolean-->opened = 1 and in the state "closed" it will have boolean opened = 0;
What is the best practice here? Any advantages of using two booleans over one boolean? I can imagine in this case too many variables have to been defined and reset every time state transitions into another state.
Thank you in advance
I think you could consider not using boolean at all to represent object state. Most objects will have more than two states, and if you use boolean flags you'll end up with qute a lot of them. This can make it quite hard to test and verify that the code works as expected all the time. I worked with someone who had 22 boolean flags in one class. This meant that the class has over 4 million possible states.
I usually use an enum to represent class state. The Valve could be Open or Closed, but what if it became defective, and impossible to operated? I can easily add more states to the enum increasing the number of states by 1, but if I use an boolean I will exponentially increase the number of possible states when adding more flags.
I'd also recommend using a state machine library, instead of manually handling state in your own code. There are many state machine libraries available, I use (and contribute to) the stateless state machine library on Github.
If the two states are mutually exclusive, there's no point in having a redundant state variable, which you'd need to maintain. A single boolean provides you with two possible states already.
Depending on the language, you might be able to introduce an alias such that you'd be able to refer to the same state under different names, purely for aesthetic purposes, and the compiler would remove the redundancy. But again, it may be more of a nuisance than something truly useful.
You want to have additional state variables when you need to deal with independent states or when you want to describe substates.

Which method is generally used to communicate between programs in Structured Text

I am maintaining a project for a PLC written in ST. To implement a new feature I need to let cyclic program A know when an event happened in cyclic program B.
How is this generally done in ST? Do I simply use global variables or is there a different method? If I use global variables, how are these then protected from concurrent modification?
I use the X20 PLCs from B&R Automation.
Asynchronous communication is tricky.
So imagine a global A_DONE initialized to false, with B inspecting it occasionally. A runs, and sets A_DONE. B can react to this event... but what does it do if it needs to handle another event?
If you believe that the event that tells A to signal A_DONE occurs only long after B sees A_DONE, B can simply reset A_DONE to false (assuming this always happens before the next A_DONE event) and the cycle can repeat.
If A_DONE can occur "again" while B is handling the results of seeing A_DONE, B cannot just reset A_DONE: you might get a timing splinter in which B reads A_DONE, A sets A_DONE again and B then clears A_DONE; now you've lost an event. If that event is controlling your reactor emergency rods, this could be pretty bad because poof, B missed it.
In this case you will likely need a handshake from A to B and back. We add a signal from B back to A, call it A_DONE_SEEN, to let B tell A that it has processed the event. Then A sets A_DONE, waits for A_DONE_SEEN; A clears A_DONE, waits for A_DONE_SEEN to go false, and continues its business. If A_DONE needs to be set while A_DONE is already set, or A_DONE_SEEN is set, we know we missed an event and some disaster recovery procedure can be run. B watches for A_DONE, handles the A_DONE action, sets A_DONE_SEEN, watches for A_DONE going false, and sets A_DONE_SEEN_FALSE.
I don't know about your specific PLCs, but in many systems there are atomic operations that increment counts, etc. You could use this instead of the handshake.
Yes, you need to declare a variable that has a shared scope to both cyclic programs.
You can do this by using the existing global.var file or you can create a new variable file, and limit what programs can read or write to it by placing it within a "package" (folder in your project).
To create a new var declaration file...
-right click within the logical view
-add object
-select "file" category, and choose new file
-name, and change to "save as *.var" in the drop down
By default, the new variable declaration visibility will be limited to the package it is contained within. To verify this, right click the file and go to properties. Select the details tab.
There is no way to protect from concurrent modification, but you can use the cross reference tool to see where a selected variable is being written and read within your project. First build a cross reference, and then use the tab at the bottom.
Good luck!

VHDL Bus Functional Modelling - Can't put groups of procedures into a package to clean up the code

I want to organize a working bus functional model and push commonly used procedures (which look like CPU subroutines) out into a package and get them out of the main cpu model, but I'm stuck.
The procedures don't have access to the hardware bits when they're pushed out in a package.
In Verilog, I would put commonly used procedures out into an include file and link them into the CPU model as required for a given test suite.
More details:
I have a working bus functional model of a CPU, for simulation test benching.
At the "user interface" level I have a process called "main" running inside the CPU model which calls my predefined "instruction set" like this:
cpu_read(address, read_result);
cpu_write(address, write_data);
etc.
I bundle groups of those calls up into higher level procedures like
configure_communication_bus;
clear_all_packet_counters;
etc.
At the next layer these generic functions call a more hardware specific version which knows the interface timing for the design,
and those procedures then use an input record and output record to connect to the hardware module ports and waggle the cpu bus signals as required.
cpu_read calls hardware_cpu_read(cpu_input_record, cpu_output_record, address);
Something like this:
procedure cpu_read (address : in std_logic_vector(15 downto 0);
read_result : out std_logic_vector(31 downto 0));
begin
hardware_cpu_read(cpu_input_record, cpu_output_record, address, read_result);
end procedure;
The cpu_input_record and cpu_output_record are declared as signals of type nnn_record in the cpu model vhdl file.
So this is all working, but every single one of these procedures is all stored in the cpu VHDL module file, and all in the procedure declaration section so that they are all in the same scope.
If I share the model with team members they will need to add their own testing subroutines, and those also are all in the same location in the file, as well, their simulation test code has to go into the "main" process along with mine.
I'd rather link in various tests from outside the model, and only keep model specific procedures in the model file..
Ironically I can push the lowest level hardware procedure out to a package, and call those procedures from within the "main" process, but the higher level processes can't be put out into that package or any other packages because they don't have access to the cpu_read_record and cpu_write_record.
I feel like there must be a simple way to clean up this code and make it modular, and I'm just missing something obvious.
I don't really think making a command interpreter and loading my test code into a behavioral ROM is the right way to go by the way. Nor is fighting with the simulator interface to connect up a C program, but I may break down and try this..
Quick sketch of an answer (to the question I think you are asking! :-) though I may be off-beam...
To move the BFM subprograms into a reusable package, they need to be independent of the execution scope - that usually means a long parameter list for each of them. So using them in a testbench quickly gets tedious compared with the parameterless (or parameter-lite) versions you have now..
The usual workaround is to implement the BFM in a package, with long parameter lists.
Then write parameter-lite local equivalents (wrappers) in the execution scope, which simply call the package versions supplying all the parameters explicitly.
This is just boilerplate - not pretty but it does allow you to move the BFM into a package. These wrappers can be local to the testbench, to a process within it, or even to a subprogram within that process.
(The parameter types can be records for tidiness : these are probably declared in a third package, shared between BFM. TB, and synthesisable device under test...)
Thanks to overloading, there is no ambiguity between the local and BFM package versions, so the actual testbench remains as simple as possible.
Example wrapper function :
function cpu_read(address : unsigned) return slv_32 is
begin
return BFM_pack.cpu_read (
address => address,
rd_data_bus => tb_rd_data_bus,
wait => tb_wait_signal,
oe => tb_mem_oe,
-- ditto for all the signals constants variables it needs from the tb_ scope
);
end cpu_read;
Currently your test procedures require two extra signals on them, cpu_input_record and cpu_output_record. This is not so bad. It is not uncommon to just have these on all procedures that interact with the cpu and be done with it. So use hardware_cpu_read and not cpu_read. Add cpu_input_record, cpu_output_record to your configure_communication_bus and clear_all_packet_counters procedures and be done. Perhaps choose shorter names.
I do a similar approach, except I use only one record with resolved elements. To make this work, you need to initialize the record so that all elements are non-driving (ie: 'Z' for std_logic). To make this more flexible, I have created resolution functions for integer, time, and real. However, this only saves you one signal. Not a real huge win. Perhaps half way to where you think you want to be. But it is more work than what you are doing.
For VHDL-201X, we are working on syntax to allow parameters/ports automatically map to a identically named signal. This will get you to where you want to be with any of the approaches (yours, mine, or Brian's without the extra wrapper subprogram). It is posted here: http://www.eda.org/twiki/bin/view.cgi/P1076/ImplicitConnections. Given this, I would add the two records to your procedures and call it good enough for now.
Once you get by this problem, you seem to also be asking is how do I write separate tests using the same testbench. For this I use multiple architectures - I like to think of these as a Factory Class for concurrent code. To make this feasible, I separate the stimulus generation code from the rest of the testbench (typically: netlist connections and clock). My presentation, "VHDL Testbench Techniques that Leapfrog SystemVerilog", has an overview of this architecture along with a number of other goodies. It is available at: http://www.synthworks.com/papers/index.htm
You're definitely on the right track, in fact I have a variant like this (what you describe).
The catch is, now I build up a whole subroutine using the "parameter light" procedures, and those are what I want to put in a package to share and reuse. The problem is that any procedure pushed out to a package can't call to the parameter light procedures in the main vhdl file..
So what happens is we have one main vhdl file with all the common CPU hardware setup routines, and every designer's test code all in the same vhdl file..
Long story short, putting our test subroutines into separate files is really what I was hoping for..

Inconsistent behavior between local actor and remote actor

This is sort of a follow up to an earlier question at Scala variable binding when used with Actors
Against others' advice, I decided to make a message containing a closure and mutate the variable that closure is closed under between messages.. and explicitly wait for them.
The environment is akka 1.2 on scala 2.9
Consider the following
var minAge = 18
val isAdult = (age: Int) => age >= minAge
println((actor ? answer(19, isAdult)).get)
minAge = 20
println((actor ? answer(19, isAdult)).get)
The message handler for answer essentially applies isAdult to the first parameter (19).
When actor is local, I get the answers I expect.
true
false
But when it is remote, I get
false
false
I am simply curious why this would be the behavior? I would have expected consistent behavior between the two..
Thanks in advance!
Well, you have come across what may (or may not) be considered a problem for a system where the behaviour is specified by rules which are not enforced by the language. The same kind of thing happens in Java. Here:
Client: Data d = rmiServer.getSomeData();
Client: d.mutate()
Do you expect the mutation to happen on the server as well? A fundamental issue with any system which involves remote communication, especially when that communication is transparent to a client, is understanding where that communication is occurring and what, exactly, is going on.
The communication with the actor takes the form of message-passing
An effect can pass a boundary only by the mechanism of message-passing (that is, the effect must reside within the returned value)
The actor library may transparently handle the transmission of a message remotely
If your effect is not a message, it is not happening!
What you encounter here is what I would call “greediness” of Scala closures: they never close “by-value”, presumably because of the uniform access principle. This means that the closure contains an $outer reference which it uses to obtain the value of minAge. You did not give enough context to show what the $outer looks like in your test, hence I cannot be more precise in how it is serialized, from which would follow why it prints what you show.
One word, though: don’t send closures around like that, please. It is not a recipe for happiness, as you acknowledge yourself.