Testing state machine transitions implemented as Map - testing

I have a state machine with a relatively small set of states and inputs and I want to test the transitions exhaustively.
Transitions are coded using a Map<State, Map<Input, State>>, the code is something like this:
enum State {
S1,
// ...
}
enum Input {
I1,
// ...
}
class StateMachine {
State current;
Map<State, Map<Input, State>> transitions = {
S1: {
I1: S2,
// ...
},
// ...
};
State changeState(Input x) {
if (transitions[current] == null)
throw Error('Unknows state ${current}');
if (transitions[current][x] == null)
throw Error('Unknown transition from state ${current} with input ${x}');
current = transitions[current][x];
return current;
}
void execute() {
// ...
}
}
To test it I see 3 approaches:
1) Write lot of boilerplate code to check every single combination
2) Automate the tests creation: this seems a better approach to me, but this would end up using a structure that is identical to the Map used in the StateMachine. What should I do? Copy the Map in the test file or import it from the implementation file? The latter would make the test file depend on the implementation and doesn't seem a good idea.
3) Test Map for equality, same problem as before: equality with itself or with a copy? This approach is essentially what I do with the other 2 but doesn't seem like a canonical test

Maybe you want to have a look at this: https://www.itemis.com/en/yakindu/state-machine/documentation/user-guide/sctunit_test-driven_statechart_development_with_sctunit
It shows, how you can do a model based and test driven development of state machines including the option to generate unit test code and measuring the test coverage.

Related

Whats the best way to write an iterator supporting multiple logic branches?

In Rust I've started writing iterators, converting them from code which took a callback function.
I ran into the problem where the code that used a callback in multiple branches of the function didn't convert so cleanly into a Rust iterator.
To give some pseudo-code.
// function using callbacks where the caller can exit at any time,
// can be used in a similar way to an iterator.
fn do_stuff(args, callback_fn(cb_args)) {
// define a, b, c... args
if callback_fn(a, b, 0) == false { return; }
for i in 0..n {
if callback_fn(c, d, i) == false { return; }
}
if callback_fn(e, f, -1) == false { return; }
}
Converting this to an iterator was rather awkward since I needed to store some state representing each branch.
impl Iterator for MyStruct {
fn next(&mut self) -> Option<MyResult> {
let out = match (self.state) {
0 => {
self.state += 1;
Some(MyResult(self.a, self.b, 0))
},
1 => {
self.i += 1;
if self.i == self.n {
self.state += 1;
}
Some(MyResult(self.c, self.d, self.i - 1))
},
2 => {
self.state += 1;
Some(MyResult(self.e, self.f, -1))
},
_ => {
None
},
}
return out;
}
// --- snip
With the example above, this is arguably acceptable, (if a little awkward). Consider cases with multiple for loops, variable scopes, where its much harder to track state.
While I didn't try these, I imagine there are some ways to achieve this which in most cases are less-then-ideal workarounds:
Using the callback version, building a vector, then iterating over it... (works but defeats the purpose of using an iterator, no way to early exit and avoid creating the entire data set for eg).
Writing an iterator which communicates with a thread that uses similar logic to the callback version.(while possible, the overhead of creating OS threads makes it a poor choice in many cases).
Besides the workarounds above:
Are there ways to write iterators like the example given, with less convoluted logic?Ideally more like the example that uses callbacks.
Otherwise are there other ways to handle this?
Or is this simply not supported in Rust?
Note, the same logic applies coming from Python generators (using yield instead of a callback, using callbacks as an example here since they're ubiquitous with first class functions).
Languages like C# and Python provide a way to generate iterators from methods written using a special yield keyword. As of Rust 1.11, there is no such feature in the language. However, such a feature is planned (see RFC) (indeed, yield is a reserved keyword!) and would likely work as in C# (i.e. the compiler would generate a struct with the necessary state and implementation for Iterator).
In the meantime, you could try Stateful, a project that attempts to provide this feature. (This blog post explains how Stateful works, and the challenges involved.)

How do I use Strategy Pattern in this context?

Let me begin by saying I am a mathematician and not a coder. I am trying to code a linear solver. There are 10 methods which I coded. I want the user to choose which solver she wishes to use, like options.solver_choice='CG'.
Now, I have all 10 methods coded in a single class. How do I use the strategy pattern in this case?
Previously, I had 10 different function files which I used to use in the main program using a switch case.
if options.solver_choice=='CG'
CG(A,x,b);
if options.solver_choice=='GMRES'
GMRES(A,x,b);
.
.
.
This isn't the most exact of answers, but you should get the idea.
Using the strategy pattern, you would have a solver interface that implements a solver method:
public interface ISolver {
int Solve();
}
You would implement each solver class as necessary:
public class Solver1 : ISolver {
int Solve() {
return 1;
}
}
You would then pass the appropriate solver class when it's time to do the solving:
public int DoSolve(ISolver solver) {
return solver.solve();
}
Foo.DoSolve(new Solver1());
TL;DR
As I've always understood the strategy pattern, the idea is basically that you perform composition of a class or object at run-time. The implementation details vary by language, but you should be able to swap out pieces of behavior by "plugging in" different modules that share an interface. Here I present an example in Ruby.
Ruby Example
Let's say you want to use select a strategy for how the #action method will return a set of results. You might begin by composing some modules named CG and GMRES. For example:
module CG
def action a, x, b
{ a: a, x: x, b: b }
end
end
module GMRES
def action a, x, b
[a, x, b]
end
end
You then instantiate your object:
class StrategyPattern
end
my_strategy = StrategyPattern.new
Finally, you extend your object with the plug-in behavior that you want. For example:
my_strategy.extend GMRES
my_strategy.action 'q', nil, 1
#=> ["q", nil, 1]
my_strategy.extend GMRES
my_strategy.action 'q', nil, 1
#=> {:a=>"q", :x=>nil, :b=>1}
Some may argue that the Strategy Pattern should be implemented at the class level rather than by extending an instance of a class, but this way strikes me as easier to follow and is less likely to screw up other instances that need to choose other strategies.
A more orthodox alternative would be to pass the name of the module to include into the class constructor. You might want to read Russ Olsen's Design Patterns in Ruby for a more thorough treatment and some additional ways to implement the pattern.
Other answers present the pattern correctly, however I don't feel they are clear enough. Unfortunately the link I've provided does the same, so I'll try to demonstrate what's the Strategy's spirit, IMHO.
Main thing about strategy is to have a general procedure, with some of its details (behaviours) abstracted, allowing them to be changed transparently.
Consider an gradient descent optimization algorithm - basically, it consists of three actions:
gradient estimation
step
objective function evaluation
Usually one chooses which of these steps they need abstracted and configurable. In this example it seems that evaluation of the objective function is not something that you can do in more than one way - you always just ... evaluate the function.
So, this introduces two different strategy (or policy) families then:
interface GradientStrategy
{
double[] CalculateGradient(Function objectiveFunction, double[] point);
}
interface StepStrategy
{
double[] Step(double[] gradient, double[] point);
}
where of course Function is something like:
interface Function
{
double Evaluate(double[] point);
}
interface FunctionWithDerivative : Function
{
double[] EvaluateDerivative(double[] point);
}
Then, a solver using all these strategies would look like:
interface Solver
{
double[] Maximize(Function objectiveFunction);
}
class GradientDescentSolver : Solver
{
public Solver(GradientStrategy gs, StepStrategy ss)
{
this.gradientStrategy = gs;
this.stepStrategy = ss;
}
public double[] Maximize(Function objectiveFunction)
{
// choosing starting point could also be abstracted into a strategy
double[] currentPoint = ChooseStartingPoint(objectiveFunction);
double[] bestPoint = currentPoint;
double bestValue = objectiveFunction.Evaluate(bestPoint);
while (...) // termination condition could also
// be abstracted into a strategy
{
double[] gradient = this.gradientStrategy.CalculateGradient(
objectiveFunction,
currentPoint);
currentPoint = this.stepStrategy.Step(gradient, currentPoint);
double currentValue = objectiveFunction.Evaluate(currentPoint);
if (currentValue > bestValue)
{
bestValue = currentValue;
bestPoint = currentPoint;
}
else
{
// terminate or step back and reduce step size etc.
// this could also be abstracted into a strategy
}
}
return bestPoint;
}
private GradientStrategy gradientStrategy;
private StepStrategy stepStrategy;
}
So the main point is that you have some algorithm's outline, and you delegate particular, general steps of this algorithm to strategies or policies. Now you could implement GradientStrategy which works only for FunctionWithDerivative (casts down) and just uses function's analytical derivative to obtain the gradient. Or you could have another one implementing stochastic version of gradient estimation. Note, that the main solver does not need to know about how the gradient is being calculated, it just needs the gradient. The same thing goes for the StepStrategy - it can be a typical step policy with single step-size:
class SimpleStepStrategy : StepStrategy
{
public SimpleStepStrategy(double stepSize)
{
this.stepSize = stepSize;
}
double[] Step(double[] gradient, double[] point)
{
double[] result = new double[point.Length];
for (int i = 0;i < result.Length;++i)
{
result[i] = point[i] + this.stepSize * gradient[i];
}
return result;
}
private double stepSize;
}
, or a complicated algorithm adjusting the step-size as it goes.
Also think about the behaviours noted in the comments in the code: TerminationStrategy, DeteriorationPolicy.
Names are just examples - they're probably not the best, but I hope they give the intent. Also, usually best to stick with one version (Strategy or Policy).
PHP Examples
You'd define your strategies that implement only singular method called solve()
class CG
{
public function solve($a, $x, $y)
{
//..implementation
}
}
class GMRES
{
public function solve($a, $x, $y)
{
// implementation..
}
}
Usage:
$solver = new Solver();
$solver->setStratery(new CG());
$solver->solve(1,2,3); // the result of CG
$solver->setStrategy(new GMRES());
$solver->solve(1,2,3); // the result of GMRES
class Solver
{
private $strategy;
public function setStrategy($strategy)
{
$this->strategy = $strategy;
}
public function solve($a, $x, $y)
{
return $this->strategy->solve($a, $x, $y);
}
}

Can a finite state machine work with persistence without breaking the FSM encapsulation?

Say we have a (UK) Traffic Light simulation app and a class TrafficLight has an associated finite state machine defined as:-
* --> RED --> RED_AMBER --> GREEN --> AMBER --> RED --> ...
(repeat until the proverbial cows make an appearance )
On construction TrafficLight's state is RED
Some kind of time trigger causes a state change.
In the app there may be some code like ( removing any code that takes away from point ) ...
TrafficLight trafficLightsAtBigJunction = new TrafficLight(); // state = RED
trafficLightsAtBigJunction.setState( TrafficLightState.RED_AMBER );
trafficLightsAtBigJunction.setState( TrafficLightState.GREEN );
trafficLightsAtBigJunction.setState( TrafficLightState.AMBER );
trafficLightsAtBigJunction.setState( TrafficLightState.RED );
trafficLightsAtBigJunction.setState( TrafficLightState.RED_AMBER );
:
:
:
The crux is, using the state pattern to implement the state machine, if we do
TrafficLight trafficLightsAtBigJunction = new TrafficLight(); // state = RED
trafficLightsAtBigJunction.setState( TrafficLightState.GREEN ); // Exception!!!!!
an exception is thrown ( by our design ) because it's an illegal state move. That's what we want. Everything is good with the world.
However if we then persist the traffic light and it happens to be at state = AMBER say then there appears to be a problem. When our user comes back 3 days later to watch the awesome traffic light simulation it is restored from the current state in some ( who cares ) persistent store.
How do we get the traffic light instance to be in state AMBER without breaking the encapsulation that the state pattern provides here?
There appears to be 2 choices:-
(1) Create a new instance and run through the relevant states
(2) Provide a special method to set the state to whatever we want that, by convention, is only used after reading from some persistence store. e.g.
trafficLight.setStateAfterReadingFromPersistanceSource( AMBER );
Issue with (1) as I see it is that there may very well be side effects I don't want when running through the states, plus the logic could be quite complex depending on the state machine
Issue with (2) is obviously it only works by convention so could introduce a bug without knowing when incorrectly used. More importantly it pretty much breaks all your nice pattern encapsulating which is what you wanted in the first place.
The question is persistence technology agnostic - same issue with ORM, Files, serialisation etc
I'm assuming there is a solution here but I can't think of one myself and my googling skills have not been sufficient.
Any pointers would be great.
Implementing a state machine by representing states and transitions as objects is certainly possible, but those objects require initialization (which appears to be your problem) and take the precious RAM.
However, there is also a completely different way of implementing state machines as pure code. This has so many advantages that I would never go back to the "state machine as data" method.
For a specific example, the DDJ article "UML Statecharts at $10.99" at http://www.drdobbs.com/architecture-and-design/uml-statecharts-at-1099/188101799 shows exactly how to implement a Pedestrian LIght CONtrolled (PELICAN) crossing as a hierarchical state machine.
This example is coded in C for a low-end microcontroller. If you are interested in C++ implementation, you can take a look at the open source QP/C++ framework available from SourceForge.net at https://sourceforge.net/projects/qpc/files/QP_C%2B%2B/
The way I see it, you want two ways to manipulate the state:
1) Transition from this state to another state, performing all side effects of this transition, throwing exception if illegal, etc
2) Set the machine directly to a state/set of internal values. Do nothing else.
You should persist everything that describes the FSM's internal state and have two methods, one that does the former, one that does the latter.
The latter will be used when setting up or when unpersisting. It's also much simpler to code since it'll just be transferring values into variables without worrying about what else needs to happen.
The former will be used during simulation.
The simplest approach may just be to pass the initial state as a constructor parameter - it's only your convention that the system starts with all lights as red.
Another approach would be to make the function which pulls data from the store a friend or member ( depending whether you're using operator>> to read it or something else ). This gives you the option to either transition to a state as per your example, or read an initial state from a store. There isn't much ambiguity as to what is happening, and it's up to the FSM to pull its state and whatever else it needs to and from the store when persisting.
For the short answer I agree with Pete that, in this simplistic example, you can pass it as
a constructor arg.
But I honestly think the entire design is flawed. I would think this should be modeled using the standard State design pattern. Something like this:
class TrafficLight
{
private TrafficLightState _lightState;
TrafficLight(initialState)
{
// utilize lookup table or factory-method to assign _lightState with the correct TrafficLightState subclass
}
// UI can use this to identify/render the appropriate color
Color getColorCode()
{
return _lightState.getColorCode();
}
// UI uses this to know when to signal the next light change (each color can have different duration)
int getDuration()
{
return _lightState.getDuration();
}
// assuming the UI has a timer that is set based on the current light's duration
void changeLight()
{
TrafficLightState nextState = _lightState.onChangeLight();
_lightState = nextState;
}
}
abstract class TrafficLightState
{
abstract Color getColorCode()
abstract TrafficLightState onChangeLight()
abstract int getDuration()
}
class RedLight : TrafficLightState
{
Color getColorCode()
{
return Color.Red;
}
TrafficLightState onChangeLight()
{
return new RedAmberLight();
}
int getDuration()
{
return 30;
}
}
class RedAmberLight : TrafficLightState
{
Color getColorCode()
{
return Color.Orange;
}
TrafficLightState onChangeLight()
{
return new GreenLight();
}
int getDuration()
{
return 10;
}
}
class GreenLight: TrafficLightState
{
Color getColorCode()
{
return Color.Green;
}
TrafficLightState onChangeLight()
{
return new AmberLight();
}
int getDuration()
{
return 25;
}
}
class AmberLight: TrafficLightState
{
Color getColorCode()
{
return Color.Yellow;
}
TrafficLightState onChangeLight()
{
return new RedLight();
}
int getDuration()
{
return 10;
}
}
State machines should not have an explicitly-exposed "change state" method that is used to transition in normal operations. Instead, think of them as having stimuli that allow the state machine to transition its own state. In this example, the stimuli was very simple but normally you'd have a bank of possible inputs that can cause a state transition. But with proper encapsulation, the caller need not be overly aware of the details.

How do I execute Dynamically (like Eval) in Dart?

Since getting started in Dart I've been watching for a way to execute Dart (Text) Source (that the same program may well be generating dynamically) as Code. Like the infamous "eval()" function.
Recently I have caught a few hints that the communication port between Isolates support some sort of "Spawn" that seems like it could allow this "trick". In Ruby there is also the possibility to load a module dynamically as a language feature, perhaps there is some way to do this in Dart?
Any clues or a simple example will be greatly appreciated.
Thanks in advance!
Ladislav Thon provided this answer on the Dart forum:
I believe it's very safe to say that Dart will never have eval. But it will have other, more structured ways of dynamically generating code (code name mirror builders). There is nothing like that right now, though.
There are two ways of spawning an isolate: spawnFunction, which runs an existing function from the existing code in a new isolate, so nothing you are looking for, and spawnUri, which downloads code from given URI and runs it in new isolate. That is essentially dynamic code loading -- but the dynamically loaded code is isolated from the existing code. It runs in a new isolate, so the only means of communicating with it is via message passing (through ports).
You can run a string as Dart code by first constructing a data URI from it and then passing it into Isolate.spawnUri.
import 'dart:isolate';
void main() async {
final uri = Uri.dataFromString(
'''
void main() {
print("Hellooooooo from the other side!");
}
''',
mimeType: 'application/dart',
);
await Isolate.spawnUri(uri, [], null);
}
Note that you can only do this in JIT mode, which means that the only place you might benefit from it is Dart VM command line apps / package:build scripts. It will not work in Flutter release builds.
To get a result back from it, you can use ports:
import 'dart:isolate';
void main() async {
final name = 'Eval Knievel';
final uri = Uri.dataFromString(
'''
import "dart:isolate";
void main(_, SendPort port) {
port.send("Nice to meet you, $name!");
}
''',
mimeType: 'application/dart',
);
final port = ReceivePort();
await Isolate.spawnUri(uri, [], port.sendPort);
final String response = await port.first;
print(response);
}
I wrote about it on my blog.
Eval(), in Ruby at least, can execute anything from a single statement (like an assignment) to complete involved programs. There is a substantial time penalty for executing many small snippets over most any other form of execution that is possible.
Looking at the problem closer, there are at least three different functions that were at the base of the various schemes where eval might be used. Dart handles at least 2 of these in at least minimal ways.
Dart does not, nor does it look like there is any plan to support "general" script execution.
However, the NoSuchMethod method can be used to effectively implement the dynamic "injection" of variables into your local class environment. It replaces an eval() with a string that would look like this: eval( "String text = 'your first name here';" );
The second function that Dart readily supports now is the invocation of a method, that would look like this: eval( "Map map = SomeClass.some_method()" );
After messing about with this it finally dawned on me that a single simple class can be used to store the information needed to invoke a method, for a class, as a string which seems to have general utility. I can replace a big maintenance prone switch statement that might otherwise be necessary to invoke a series of methods. In Ruby this was almost trivial, however in Dart there are some fairly less than intuitive calls so I wanted to get this "trick" in one place, which fits will with doing ordering and filtering on the strings such as you may need.
Here's the code to "accumulate" as many classes (a whole library?) into a map using reflection such that the class.methodName() can be called with nothing more than a key (as a string).
Note: I used a few "helper methods" to do Map & List functions, you will probably want to replace them with straight Dart. However this code is used and tested only using the functions..
Here's the code:
//The used "Helpers" here..
MAP_add(var map, var key, var value){ if(key != null){map[key] = value;}return(map);}
Object MAP_fetch(var map, var key, [var dflt = null]) {var value = map[key];if (value==null) {value = dflt;}return( value );}
class ClassMethodMapper {
Map _helperMirrorsMap, _methodMap;
void accum_class_map(Object myClass){
InstanceMirror helperMirror = reflect(myClass);
List methodsAr = helperMirror.type.methods.values;
String classNm = myClass.toString().split("'")[1]; ///#FRAGILE
MAP_add(_helperMirrorsMap, classNm, helperMirror);
methodsAr.forEach(( method) {
String key = method.simpleName;
if (key.charCodeAt(0) != 95) { //Ignore private methods
MAP_add(_methodMap, "${classNm}.${key}()", method);
}
});
}
Map invoker( String methodNm ) {
var method = MAP_fetch(_methodMap, methodNm, null);
if (method != null) {
String classNm = methodNm.split('.')[0];
InstanceMirror helperMirror = MAP_fetch(_helperMirrorsMap, classNm);
helperMirror.invoke(method.simpleName, []);
}
}
ClassMethodMapper() {
_methodMap = {};
_helperMirrorsMap = {};
}
}//END_OF_CLASS( ClassMethodMapper );
============
main() {
ClassMethodMapper cMM = new ClassMethodMapper();
cMM.accum_class_map(MyFirstExampleClass);
cMM.accum_class_map(MySecondExampleClass);
//Now you're ready to execute any method (not private as per a special line of code above)
//by simply doing this:
cMM.invoker( MyFirstExampleClass.my_example_method() );
}
Actually there some libraries in pub.dev/packages but has some limitations because are young versions, so that I can recommend you this library expressions to dart and flutter.
A library to parse and evaluate simple expressions.
This library can handle simple expressions, but no blocks of code, control flow statements and so on. It supports a syntax that is common to most programming languages.
There I create an example of code to evaluate arithmetic operations and comparations of data.
import 'package:expressions/expressions.dart';
import 'dart:math';
#override
Widget build(BuildContext context) {
final parsing = FormulaMath();
// Expression example
String condition = "(cos(x)*cos(x)+sin(x)*sin(x)==1) && respuesta_texto == 'si'";
Expression expression = Expression.parse(condition);
var context = {
"x": pi / 5,
"cos": cos,
"sin": sin,
"respuesta_texto" : 'si'
};
// Evaluate expression
final evaluator = const ExpressionEvaluator();
var r = evaluator.eval(expression, context);
print(r);
return Scaffold(
body: Container(
margin: EdgeInsets.only(top: 50.0),
child: Column(
children: [
Text(condition),
Text(r.toString())
],
),
),
);
}
I/flutter (27188): true

Object oriented design patterns for parsing text files?

As part of a software package I'm working on, I need to implement a parser for application specific text files. I've already specified the grammar for these file on paper, but am having a hard time translating it into easily readable/updatable code (right now just it passes each line through a huge number of switch statements).
So, are there any good design patterns for implementing a parser in a Java style OO environment?
Any easy way to break a massive switch into an OO design would be to have
pseudo code
class XTokenType {
public bool isToken(string data);
}
class TokenParse {
public void parseTokens(string data) {
for each step in data {
for each tokenType in tokenTypess {
if (tokenType.isToken(step)) {
parsedTokens[len] = new tokenType(step);
}
...
}
}
...
}
}
Here your breaking each switch statement into a method on that token object to detect whether the next bit of the string is of that token type.
Previously:
class TokenParse {
public void parseTokens(string data) {
for each step in data {
switch (step) {
case x:
...
case y:
...
...
}
}
...
}
}
One suggestion is to create property file where you define rules. Load it during run time and use if else loop (since switch statements also does the same internally). This way if you want to change some parsing rules you have to change .property file not code. :)
You need to learn how to express context free grammars. You should be thinking about the GoF Interpreter and parser/generators like Bison, ANTRL, lex/yacc, etc.