Model alloy for series and parallel electric circuit - analyzer

I am newbie in alloy .
i need help for series and parallel electric circuit in alloy .
I had model a graph for series circuit but when I omit self loop in series it does not work
also it show only one instance for the series . i have to show when switch is on ,bulbs in series are on ... so their is signature of state and On and Off extends state..
my code is :
abstract sig state{}
one sig on extends state{}
one sig off extends state{}
sig CE{}
//one sig battery extends CE{}
abstract sig bulb extends CE{
bs : one state
}
abstract sig switch extends CE{
ss : one state
}
sig Circuit{
battery: one CE,
/*eles: set state,
battery:one eles,
switch : set eles,
bulb : set eles,
wire: eles one-> one eles*/
wire: CE->CE
}{
//all e:CE | #(e.wire)=1 and #(wire.e)=1
battery.^wire=CE
//no iden & wire
//all e:CE | e->e not in wire
}
pred show{}
run show for 1 Circuit, 5 CE

My advice is to start with something really tiny and simple. For example, you could have wires, batteries and bulbs, and subset bulbs into bulbs that are on or off. One thing that looks wrong with your model: it won't be good enough just to have wires connect to elements: you'll need to identify which side of the element the wire is connected to.

Related

Alloy modeling language - how to write filters?

How can I write a filter function in Alloy?
For example If I have:
sig Student {
enrollments: set Enrollment
}
sig Course {}
abstract sig Status {}
one sig Complete, Incomplete extends Status {}
sig Enrollment {
student: Student,
course: Course,
status: Status
}
How can I, for a given student, check if he completed a given course?
I suppose I'd have to write a function that for a student s returns its completed courses:
fun completed[s: Student]: set Course { ... }
Writing such a function is indeed a possibility. I think that, to formalize a property successfully, you should first state your query in simple terms, e.g.: you want to return the set of courses followed by s that are completed. With that said, the formalization is fairly easy with a comprehension set. Later, you may try to see whether you can achieve the same result with other Alloy constructs.
The term filter is somehow misleading. If you want to write a function that returns the set of completed course to which a student s is enrolled then you are on the right track.
You just need to feel those dots by the right expression. An intersection using the & operator will definitely do the trick to only consider completed enrollements.
Note that if you are only interested in answering the yes/no question: Did the student complete a given course, then declaring a predicate taking the given course as parameter would be a more appropriate solution.

Entity-Component System : fear of losing type & readability

I have a Entity-Component System.
Components : classes with data, but have no complex function
Entity : integer + list of Components (<=1 instance per type per entity)
Systems : a lot of function with minimum data, do complex game logic
Here is a sample. A bullet entity pewpew is exploded, so it will be set to be invisible (at #2):-
class Component_Projectile : public ComponentBase{
public: GraphicObject* graphicObject=nullptr; //#1
public: Entity whoCreateMe=nullptr;
public: Entity targetEnemy=nullptr;
//.... other fields ....
};
class System_Projectile : public SystemBase {
public: void explodeDamage(Entity pewpew){ //called every time-step
Pointer<Component_Projectile> comPro=pewpew;
comPro->graphicObject->setVisible(false); //#2
//.... generate some cool particles, damage surrounded object, etc
}
//.... other functions ....
};
It works OK.
New Version
Half year later, I realized that my architecture looks inconsistent.
I cache all game-logic object using Entity.
But cache Physic Object and Graphic Object by direct pointer. (e.g. #1)
I have a crazy idea :
Physic Object and Graphic Object should also be game-logic object!
They should be encapsulated into Entity.
Now the code will be (the change is marked with #1 and #2):-
class Component_Projectile : public ComponentBase{
public: Entity graphicObject=nullptr; //#1
public: Entity whoCreateMe=nullptr;
public: Entity targetEnemy=nullptr;
//.... other fields ....
};
class System_Projectile : public SystemBase {
public: void explodeDamage(Entity pewpew){ //called every time-step
Pointer<Component_Projectile> comPro=pewpew;
system_graphic->setVisible(comPro->graphicObject,false); //#2
//.... generate some cool particles, damage surrounded object, etc
}
//.... other functions ....
};
After playing them for a week, I can conclude pro/cons of this approach as below :-
Advantage
1. Drastically reduce couple between game logic VS graphic-engine/physic-engine
All graphics-specific function is now encapsulated inside 1-3 systems.
No other game systems (e.g. System_Projectile) refer to the hardcode type e.g. GraphicObject.
2. Dramatically increase flexibility in design
Old vanilla graphic object is not just a graphic object anymore!
I can change it to something else, especially add special feature that is totally insane / too specific for physic/graphic engine, e.g.
rainbow blinking graphic
strange gravity, magnet
swap in/out many physic-object type in the same Entity (not sure)
3. Reduce compile time
It is accidentally become a pimpl idiom.
For example, System_Projectile don't have to #include "GraphicObject.h" any more.
Disadvantage
1. I have to encapsulate many graphic/physic-object's functions.
For example,
system_graphic->setVisible(comPro->graphicObject,false);
is implemented as
public: void setVisible(Entity entity,bool visible){
entity.getComponent<Graphic_Component>()->underlying->setVisible(visible);
}
It is tedious, but not a very hard work.
It can be partially alleviated by <...>.
2. Performance is (only) little bit worse.
Need a few additional indirection.
3. Code is less readable.
The new version is harder to read.
comPro->graphicObject->setVisible(false); //old version
system_graphic->setVisible(comPro->graphicObject,false); //new version
4. Losing type + Ctrl+space is less usable
In old version, I can easily ctrl+space in this code :-
comPro->graphicObject-> (ctrl+space)
It is now harder. I have to think which system I want to call.
system_(ctrl+space)graphic->(ctrl+space)setVisible
Question
In most code location, the advantage overcome the disadvantage, so I decided I will use the new version.
How to alleviate the disadvantages, especially number 3 and 4?
Design-pattern? C++ magic?
I may use Entity-Component System in a wrong way. (?)

Design and implementation for a job pool with dependencies

I have a collection of data, with "agents" that operate on that data. I have also built up an dependency list between the agents because some agents depend on what other agents do. I also have a structure set up to enforce what data within the collection of data can be accessed or mutated by each agent. I am stuck on how to implement this design, a job pool seems too simple to handling the dependencies . My question is related to how to actually implement this type of design. The design is very similar to FlowBased programming(if I understand it correctly), but data is operated on in bulk.
My first thought was to have a tree heirarchy of the tasks that need to be done:
Root
/ | \
a1 a2 a3
| /
a4
For example, I can run a1, a2, and a3 concurrently. But to run a4, a1 and a2 need to be finished.
What would the best tools to set this up? Should I use a signal/slot implementation, roll my own Channels, use futures and promises to emulate a channel/signal/slot system? Maybe make each Node have a number of dependencies, and when each dependent agent finishes a counter is incremented when the next Node is called until it matches the number of deps. Or this could be implemented as a "gate" type of structure that holds the number of deps and sends a signal or w/e to the agent when the deps are satisfied.
I could make make my own TaskManager that does the scheduling, but I'd rather call each top-level Node once, and have the hierarchy automatically traversed. Is their something else entirely I could try. I'm interested in any crazy ideas you might have.
I'm leaning towards something like this, using "signals" and "slots":
+----------+ +----------+
| Actor1 | | Actor2 |
| update() | | update() |
+----|-----+ +----|-----+
\____ _____/
\ /
+---v---+
| Gate |
+---|---+
V
+----------+
| Actor4 |
| update() |
+----------+
How is this type of problem typically tackled? I would like to keep it somewhat generic and use popular libraries if I can. I also need good response times since this will be running in the update() loop of a game engine.
You have an object which encapsulates data, and agents working on that data, which together are the underpinnings for the Visitor design pattern. According to the Gang of Four, the intent of the Visitor patter is to
Represent an operation to be performed on the elements of an object/structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
The abstract base visitor, visited classes would have at least the following functionality:
class DataElement
{
public:
virtual ~DataElement() = default;
virtual void Accept(DataVisitor*);
protected:
DataElement() = default;
};
DataElement::Accept(DataVisitor* v)
{
v->gendata(this); // double dispatch
}
class DataVisitor
{
public:
virtual ~DataVisitor() {} = default;
virtual void visit_SpreadData(SpreadData*) = 0;
virtual void gendata(DataElement*) = 0;
protected:
DataVisitor() = default;
};
For the chain of responsibility that you are setting up, using a Mediator would be a good start - intent:
Define an object that encapsulates how a set of objects interact. mediator promises loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
For that we would modify at least the DataVisitor class to contain a private mediator class. The abstract mediator base class might look something like:
class Mediator
{
public:
virtual ~Mediator() = default;
virtual void mediate() = 0;
std::list<DataVisitor*> get_visitors() const
protected:
Mediator() = default;
virtual void CreateVisitors() = 0;
std::list<DataVisitor*> visitors_;
};
In a concrete mediator class, the one that specifies the behavior in your diagram, the main ingredients are:
define private std::mutex, std::condition_variable, and possibly a threadsafe queue;
in CreateVisitors(), push a1, a2, a3, a4 onto visitors_ list;
create thread methods for each a_i, a1_thread(),a2_thread(),a3_thread() will run immediately, while a4_thread() will wait for the completion of a1, a2, possibly using the results of gendata() (via notify_one()) which have been pushed to the queue;
fill in mediate():
std::vector threadv;
threadv.emplace_back(&ConcreteMediator::a1_thread, this);
...
threadv.emplace_back(&ConcreteMediator::a4_thread, this);
std::for_each(threadv.begin(), threadv.end(), std::mem_fn(&std::thread::join));
This is a pretty unsophisticated setup, but it certainly maintains the loose coupling (Mediator) and scalability (Visitor) that you desire.

What are the drawbacks of writing an algorithm in a class or in an object (in Scala)?

class A {
def algorithmImplementation (...) = { ... }
}
object A {
def algorithmImplementation (...) = { ... }
}
In which circumstances should the class be used and in which should the object be used (for implementing an algorithm, e.g. Dijkstra-Algorithm, as shown above) ?
Which criterias should be considered when making such a decision ?
At the moment, I can not really see what the beneftis of using a class are.
If you only have one implementation, this can largely be a judgement call. You mentioned Dijkstra's algorithm, which runs on a graph. Now you can write that algorithm to take a graph object as an explicit parameter. In that case, the algorithm would presumably appear in the Graph singleton object. Then it might be called as something like Graph.shortestPath(myGraph,fromNode,toNode).
Or you can write the algorithm in the Graph class, in which case it no longer takes the graph as an explicit parameter. Now it is called as something like myGraph.shortestPath(fromNode,toNode).
The latter case probably makes more sense when there is one main argument (eg, the graph), especially one that serves as a kind of context for the algorithm. But it may come down to which syntax you prefer.
However, if you have multiple implementations, the balance tips more toward the class approach, especially when the choice of which implementation is better depends on the choice of representation. For example, you might have two different implementations of shortestPath, one that works better on adjacency matrices and one that works better on adjacency lists. With the class approach, you can easily have two different graph classes for the two different representations, and each can have its own implementation of shortestPath. Then, when you call myGraph.shortestPath(fromNode,toNode), you automatically get the right implementation, even if you don't know whether myGraph uses adjacency matrices or adjacency lists. (This is kind of the whole point of OO.)
Classes can have subclasses which override implementation, objects cannot be subclassed.
Classes can also be type parametric where objects cannot be.
There's only ever one instance of the object, or at least one instance per container. A class has multiple instances. That means that the class can be parameterized with values
class A(param1 : int, param2 : int) {
def algorithmImplementation(arg : List[String]) = // use arg and params
}
And that can be reused like
val A42_13 = new A(42, 13)
val result1 = A42_13.algorithmImplementation(List("hello", "world"))
val result2 = A42_13.algorithmImplementation(List("goodbye", "cruel", "world"))
To bring all this home relative to your example of Djikstra's algorithm: imagine you want to write one implementation of the algorithm that is reusable across multiple node types. Then you might want to parameterize by the Node type, the type of metric used to measure distance, and the function used to calculate distance.
val Djikstra[Node, Metric <: Comparable[Metric]](distance : (Node, Node) => Metric) {
def compute(node : Node, nodes : Seq[Node]) : Seq[Metric] = {...}
}
You create one instance of Djikstra per distinct type of node/metric/distance function that you use in your program and reuse that instance without having to pass all that information in everytime you compute Djikstra.
In summary, classes are more flexible. Use them when you need the flexibility. Otherwise objects are fine.

How to observe different concepts of an interface separately?

Basically, what I am trying to do is have a generic simulator-interface which acts as the lose coupling between the model and the user interface, which acts as the view. My simulator interface looks like this:
type ISimulator<'Collection, 'Item, 'Value> =
inherit System.IObservable<'Collection>
inherit System.IObservable<ISimulator<'Collection, 'Item, 'Value>>
abstract Start: unit -> unit
abstract Stop: unit -> unit
abstract Reset: unit -> unit
abstract Reset: 'Collection -> unit
abstract Advance: int<gen> -> unit
abstract InitialState: 'Collection
with get
abstract CurrentState: 'Collection
with get
abstract Rule: ('Item -> 'Value)
with get, set
abstract Generation: int<gen>
with get, set
abstract Speed: float<gen/sec>
with get, set
abstract Running: bool
with get
'Collections is the type of a data collection, 'Item is the type of a single data item, and 'Value is the type of its actual value (for example <Matrix, Cell, float>, <Tree, Node, string> etc.). Now, the line
inherit System.IObservable<ISimulator<'Collection, 'Item, 'Value>>
produces an error:
This type implements or inherits the same interface at different generic instantiations 'System.IObservable<Interface.ISimulator<'Collection,'Item,'Value>>' and 'System.IObservable<'Collection>'. This is not permitted in this version of F#.
Effectively, I want this interface to say that both the Collection which serves as the data the simulation is running upon and the Simulator itself to be observable separately. In the end, I want a part of my user interface to display the current data (for example a matrix) and a different part to display and control the simulator, with some buttons like "run", "stop", "reset" etc. Since the simulator might also be stopped by other means than just clicking a button (for example, after reaching some specific state, generation etc.), that control needs updates from the simulator, too, but not on the state of the data, but the simulator itself.
It is not possible to make the collection interface I would write observable, as that collection wouldn't be modified during simulation, but transformed by applying a function, and the transformation would produce a new collection, which the simulator then stores (and notifies the observers of the collection).
What shall I do?
Break the immutability concept and
always keep the same collection (in
terms of identity, not contained
values) which just changes over time
instead of producing new, modified
collections?
Break lose coupling and have my user
interface know the exact
implementation which would, outside
of the interface, provide a second
means to observer the simulator
itself? Have all user interface
components which require updates from
the simulator observe the whole
thing, not just the relevant data?
Create a seperate interface to
observe the collection, and have my
simulator implementation implement
both interfaces?
Something else?
Have you considered exposing the observables through properties, sort of like traditional events?
type ISimulator<'Collection, 'Item, 'Value> =
abstract Items: System.IObservable<'Collection>
abstract Control: System.IObservable<ISimulator<'Collection, 'Item, 'Value>>
abstract Start: unit -> unit
...
This allows consumers to be explicit about which behavior they're observing.
Here we go, I made this bare-bones implementation of IObservable, of which I then expose public properties according to the interface definition dahlbyk provided. I've found the basic idea for this implementation on this website and generalized a bit from there:
open System
type Observable<'a>() =
let mutable _observers: List<IObserver<'a>> = []
let Notify func =
_observers
|> Seq.map(fun (observer: IObserver<'a>) -> async { return func observer} )
|> Async.Parallel
|> Async.RunSynchronously
|> ignore
interface IObservable<'a> with
member this.Subscribe (observer: IObserver<'a>) =
_observers <- observer :: _observers
{ new IDisposable with
member this.Dispose() =
_observers <- _observers |> List.filter((<>) observer) }
member this.Next value =
Notify(fun (observer: IObserver<'a>) -> observer.OnNext value)
member this.Error error =
Notify(fun (observer: IObserver<'a>) -> observer.OnError error)
member this.Completed() =
Notify(fun (observer: IObserver<'a>) -> observer.OnCompleted)
The class containing instances of this implementation as properties just treats it as an Observable<'a> object, while to everyone else it is exposed only as an IObservable<'a> interface. I think this is nice in terms of loose coupling and still allows very straightforward usage on either end of the Observer/Observable pair.
P.S.: This is also why I love F# - this entire construct would be a total mess to implement in a language like C++; but here I can just pass a function into another function in order to apply it on all observers. :)

Resources