Sage Modeling and Simulation Library

Highpoint.Sage.SimCore Namespace

There are several key areas of interest in SimCore. They are the Executive, the Model, and the State Machine.

The base engine behind Sage® consists of two orthogonal pieces, the executive and the model. The executive is a C# class with several supporting classes, that performs event (callback) registration and sequencing. In essence, through the executive, a model entity may request to receive a callback at a specific time, with a specific priority, on a specified method, and with a specified object provided to that method on the callback. The entity may rescind that request at any point before the call, and the method need not be located on the entity requesting the callback. Further, the entity requesting the callback may select how the callback is to be handled, currently among three choices:

1. Synchronous – the callback is called on the dispatch thread, and upon completion, the next callback is selected based upon scheduled time and priority. This is similar to the “event queue” implementations in Garrido (1993) and Law and Kelton (2000).

2. Detachable – the callback is called on a thread from the .Net thread pool, and the dispatch thread then suspends awaiting the completion or suspension of that thread. If the event thread is sus-pended, an event controller is made available to other entities which can be used to resume or abort that thread. This is useful for modeling “intelligent entities” and situations where the developer wants to easily represent a delay or interruption of a process.

3. Asynchronous – the callback is called on a thread from the thread pool that is, in essence, fire-and-forget. This is useful when the thread has a long task to perform, such as I/O, or external system interfacing (i.e. data export) and the results of that activity cannot affect the simulation.

C#
// public member of Executive class.
   public long RequestEvent(
   ExecEventReceiver eer, // user callback
   DateTime when,
   double priority,
   object userData,
   ExecEventType execEventType){ … }

The Model class provided with Sage® performs containment and coordination between the executive, the model state machine and model entities such as queues, customers, manufacturing stages, transport hubs, etc.

The model’s state machine is used to control and indicate the state of the model – for example, a model that has states such as design, initialization, warmup, run, cooldown, data analysis, and perhaps pause, would represent each of those states in the state machine. Additionally, the application designer may attach a handler to any specified transition into or out of any given state, or between two specific states. Handlers may be given a sequence number to describe the order in which they are to be executed. Each transition is performed through a two-phase-commit protocol, with a prepare phase permitting registrants to indicate approval or denial of the transition, and a commit or rollback phase completing or canceling the attempted transition. The following code describes the interface that is implemented by a transition handler. User code may implement any of the three delegates (API signatures) at the top of the listing, and add the callback to the handlers for transition out of, into, or between specified stages.

C#
public delegate ITransitionFailureReason PrepareTransitionEvent(Model model);
public delegate void CommitTransitionEvent(Model model);
public delegate void RollbackTransitionEvent(Model model, IList reasons);

public interface ITransitionHandler {
    event PrepareTransitionEvent Prepare;
    event CommitTransitionEvent Commit;
    event RollbackTransitionEvent Rollback;
    bool IsValidTransition { get; }

    void AddPrepareEvent(PrepareTransitionEvent pte,double sequence);
    void RemovePrepareEvent(PrepareTransitionEvent pte);
    void AddCommitEvent(CommitTransitionEvent cte,double sequence);
    void RemoveCommitEvent(CommitTransitionEvent cte);
    void AddRollbackEvent(RollbackTransitionEvent rte,double sequence);
    void RemoveRollbackEvent(RollbackTransitionEvent rte);
}

Classes


  Class Description
Public class BaseModelObject
Public class CausalityException
A CausalityException is raised if the executive encounters a request to fire an event at a time earlier than the current time whose events are being served.
Public class CompileFailedException
An exception that encapsulates the errors encountered in trying to compile an expression.
Public class DefaultValueAttribute
Used as a marker in enum declarations to indicate to the Sage initialization mechanism, which is to be the default initial value.
Public class DetachableEventSynchronizer
Synchronizes a series of threads that are all running on DetachableEvent handlers. The clients will call Synchronize on DetachableEvent threads, and the threads will pause until all open channels contain paused threads. Then, in the specified sequence, all clients will be resumed.
Public class EnumStateMachine<(Of <(<'TEnum>)>)>
The EnumStateMachine represents a simple state machine whose states are the values of the enum, whose transitions are all allowable, and which tracks the amount of run-time spent in each state. A developer can wrap this class in another to limit the permissible transitions, add handlers, etc.
Public class EvaluatorFactory
The Evaluator Factory creates objects that can evaluate expressions provided by the caller. First an expression is provided and compiled into an object that can evaluate it - that object is passed back as an Evaluator delegate. Then later the Evaluator delegate is called with the values appropriate to the variables that are a part of the pre-provided expression. The result of this evaluation is the (double) value that is computed.
The body of the evaluator can be any compilable statement. If the evaluator is to return a value, the body must assign that value to the (predefined) variable "Result".
The ArgNames array is an array of strings that contain the names of the arguments to the evaluation of the expression. The defaults of those argNames is:

{"PA","PB","PC","PD","PE","PF","PG","PH","PJ","PK","RA","RB","RC","RD","RE","RF","RG","RH","RJ","RK"};

An example of using this class might be as follows:

C#
Evaluator eval = EvaluatorFactory.CreateEvaluator("Result = RA+(RB/RC);",new string[]{"RA","RB","RC"});
...and this eval could later be called with:
C#
_Debug.WriteLine(eval(3.0,4.0,5.0));
which would result in 3.8 being written to the Trace.
Public class ExecController
This object will govern the real-time frequency at which the Render event fires, and will also govern the simulation time that is allowed to pass between Render events. So with a frame rate of 20, there will be 20 Render events fired per second. With a scale of 2, 10^2, or 100 times that 1/20th of a second (therefore 2 seconds of simulation time) will be allowed to transpire between render events.
Public class ExecFactory
ExecFactory produces instances of objects that implement IExecutive.
Public class ExecutiveException
A marker class that indicates that a given exception was thrown by the executive, rather than the application code.
Public class GenericModelError
A basic implementation of IModelError.
Public class GenericModelWarning
A basic implementation of IModelWarning.
Public class HasNameComparer
A Comparer that is used to sort implementers of IHasIdentity on their names.
Public class HasNameComparer<(Of <(<'T>)>)>
A Comparer that is used to sort implementers of IHasIdentity on their names.
Public class IMOHelper
A helper class that contains logic for initializing and registering ModelObjects.
Public class InitializationException
InitializationException summary
Public class InitializationManager
The InitializationManager provides methods and mechanisms for running the initialization of a model.
Public class InitializerArgAttribute
An InitializerArgAttribute is an attribute that is attached to an argument to an IModelObject Initialize(...) method. The method argument list must always begin with the Model, Name, Guid and Description arguments, and then the specific arguments necessary to initialize the object. These specific arguments are the ones that are decorated with this attribute type.
Public class InitializerAttribute
Class InitializerAttribute decorates any method intended to be called by an initializationManager. It declares whether the method is to be called during model setup, or during the model's run.
Public class Metronome_Simple
Simple Metronome class is an object that uses a model's executive to create a series of 'tick' events with a consistent period - Simulation Objects that are written to expect a uniform discrete time notification can use a metronome to achieve that. Multiple metronomes may be defined within a model, with different periods, start times and/or finish times.
Public class MetronomeBase
Abstract base class from which concrete Metronomes derive. Provides basic services and event handlers for a Metronome, which is an object that uses a model's executive to create a series of 'tick' events with a consistent period - Simulation Objects that are written to expect a uniform discrete time notification can use a metronome to achieve that. Multiple metronomes may be defined within a model, with different periods, start times and/or finish times.
Public class Model
The base class from which models are built or derived. Models provide a state machine, error and warning management, task processor management (for Task Graphs) and access and control functions to the Executive that is running the simulation embodied in this model.
Public class ModelConfig
Class ModelConfig is a collection of initialization parameters that is intended to be available to the model in the app.config file.
Public class ModelExceptionError
An error that is registered as a result of an exception having been thrown, unhandled, by the model.
Public class ModelObjectDictionary
A ModelObjectDictionary is a passive directory of objects owned by this model. It not intended to be the primary holder of references, but rather to be a navigation aid among objects that already "belong" to the model, and that are removed once the model no longer wants/needs them. As long as someone, somewhere (presumably a hierarchy owned somehow & somewhere in the model) has a reference to all useful IModelObjects, they will be available in this dictionary. However, in order to clean out this dictionary automatically as objects are no longer in use in the model, it uses a WeakReference to track the object. Thus, as soon as no one else has a reference to the object, it will be cleaned out of this dictionary as soon as the next Garbage Collection sweep.
Public class RuntimeException
MissingParameterException is thrown when a required parameter is missing. Typically used in a late bound, read-from-name/value pair collection scenario.
Public class SimpleTransitionFailureReason
A simple class that implements ITransitionFailureReason
Public class SmartPropertyBag
NOTE: This is an older class whose utility may have been subsumed into other, newer .NET classes such as tuples and the mechanisms for lambda expressions. However, it is used in various places in the library, so it is retained.

A SmartPropertyBag (SPB) is at its basic level, a collection of name/value pairs. The power of a smart property bag lies in the fact that entries in the bag can be any of a number of specialized types -

Simple data (Value) : Any primitive that is convertible to a double, string or boolean.

Expression : An expression is a string such as "X + Y" that, when queried (assuming that X and Y are entries in the bag) is evaluated and returns the result of the evaluation.

Alias : A name value pair that points to an entry in another SPB.

Delegate : A delegate to a method that returns a double. When this entry is requested, the delegate is called and the resulting value is returned.

SPB : An entry in a SPB may be another SPB, which effectively becomes a child of this SPB. Thus, a SPB representing a truck may contain several other SPBs representing each load placed on that truck, and thereafter, the key "TruckA.LoadB.Customer" will retrieve, for example, a string containing the name or ID of the customer for whom load B is destined.

ISnapShottable : Any arbitrary object can be stored in a SPB if it implements the ISnapshottable interface. The SPB enables storage of booleans, doubles, and strings through the use of internal classes SPBBooleanWrapper, SPBDoubleValueWrapper, and SPBStringWrapper, respectively - each of which implements ISnapshottable.


A SmartPropertyBag can also be write-locked, allowing it temporarily or permanently to be read but not written.

A SmartPropertyBag also maintains a memento, an object that records the SPB's internal state and can restore that state at any time. This is useful for a model element that may need to be "rolled back" to a prior state. This memento is only recalculated when it is requested, and only the portions that have changed are re-recorded into the memento.

A SmartPropertyBag is useful when an application is required to support significant configurability at run time. An example might be a modeling tool that incorporates the concept of a vessel for chemical manufacturing, but does not know at the time of app design, all of the characteristics that will be of interest in that vessel, and all of the attachments that will be made available on that vessel at a later time or by the designer using the application.

Public class SmartPropertyBagContentsException
An exception that is fired when the SPB is asked to add/remove/retrieve a key that is inappropriate for some reason. The message will provide an explanation of the error.
Public class SmartPropertyBagException
A general exception that is fired by a SPB for reasons specific to the SPB. The message will provide an explanation of the error.
Public class SPBInitializer
An SPBInitializer is an object that can be used to automatically initialize a SmartPropertyBag. For example, if the need was to add some user-defined fields to each piece of equipment (modeled as a SPB) as it was created, the following code would be useful:
C#
// Presume that m_initializers was a hashtable of initializers...
public void InitializeEquipment(SOMEquipment equipment){
    foreach (SPBInitializer initializer in m_initializers.Values){
        initializer.Initialize(equipment);
    }
}
This class is typically derived-from, with serial number incrementation, driver or operator name assignment, etc, provided in a custom method.

Note : The initializer, once created, is configured to initialize only one way, e.g. creating an entry called 'Mixer' that is set to "Off".

Public class SPBInitializerComparer
Public class StateMachine
A table-driven, two-phase-transaction state machine. The user configures the state machine with a number of states, and the state machine creates handlers for transition out of and into each state, as well as handlers for transitions between two specific states, and one universal transition handler. Each handler provides events that are fired when the state machine attempts and then either completes or rolls back a transition. When a transition is requested, the state machine collects all of the outbound transition handlers from the current state, all of the handlers into the destination state, all handlers specified for both the current and destination states, and the universal handler. These handlers' 'Prepare' events are called in the order implied by their sequence numbers (if no sequence number was specified, it is assumed to be 0.0.) If all 'Prepare' handlers' event targets are called with none returning a TransitionFailureReason, then the State Machine calls all of the Commit events. If there was at least one TransitionFailureReason, then the 'Rollback' event handlers are called.
Public class TaskGraphVolatileAttribute
Used to decorate the key or the value for anything that is going to be put into the task graph that must be cleared out for each new run.
Public class TransitionFailureException
An exception that is fired if and when a transition fails for a reason internal to the state machine - currently, this is only in the case of a request to perform an illegal state transition.
Public class VolatileKey
This class can be used as a key for an object into a Task Graph's graphContext, where the contents of the key are intended to be cleared out of the GC after each run of the model.
Public class WriteLock
A class that manages the details of nestable write locking - that is, a parent that is write-locked implies that its children are thereby also write-locked.
Public class WriteProtectionViolationException
Thrown when someone tries to change a value that is write-locked.

Structures


  Structure Description
Public structure EnumStateMachine<(Of <(<'TEnum>)>)>..::..TransitionRecord
Records data on Transitions
Public structure HierarchicalDictionaryEntry
A structure that is used in the creation of a hierarchical dictionary. Such a dictionary structure can contain smart property bags and other dictionaries as leaf nodes, as well as having IDictionaries implementing the tree-like structure of the root dictionary. This is used so that a node in a SmartPropertyBag can have an atomic meaning in a real-world sense (such as a temperature controller on a piece of equipment, but still be implemented as an IDictionary or even a SmartPropertyBag.

Interfaces


  Interface Description
Public interface ICloneable
ICloneable is implemented by an object that is capable of being cloned.
Public interface IDetachableEventController
This interface is implemented by a DetachableEventController - a DEC is associated with an event that is fired as a detachable event, and in that event's thread, can be obtained from the executive.
Public interface IErrorHandler
Implemented by an object that is able to handle (and perhaps resolve) an error.
Public interface IExecEvent
Interface IExecEvent is implemented by an internal class that keeps track of all of the key data about an event that is to be served by the Executive.
Public interface IExecEventSelector
Implemented by an object that can select events, typically for removal from the event queue. It is, effectively, a filter. It is able to discern whether an event meets some criteria.
Public interface IExecutive
Interface that is implemented by an executive.
Public interface IHasIdentity
Implemented by any object that is likely to be tracked by the core, or perhaps a user, framework.
Public interface IHasName
An interface implemented by anything that is known by a name. The name is not necessarily required to be unique.
Public interface IHasParameters
Implemented by any object that has a dictionary of parameters.
Public interface IHasWriteLock
Implemented by an object that can be set to read-only.
Public interface IInitializationManager
Public interface IModel
The base class from which models are built or derived. Models provide a state machine, error and warning management, task processor management (for Task Graphs) and access and control functions to the Executive that is running the simulation embodied in this model.
Public interface IModelError
This interface is implemented by an object that serves to indicate that an error has occurred in the model.
Public interface IModelObject
Implemented by an object that 'belongs' to a model, or that needs to know its model in order to function properly.
Public interface IModelService
Interface IModelService is implemented by anything that can act as a service that has been injected into a model.
Public interface IModelWarning
This interface is implemented by an object that serves to indicate that a warning has occurred in the model.
Public interface INotification
This interface is implemented by an object that provides notification of some event.
Public interface IResettable
Interface IResettable is implemented by any IModelObject that can be reset.
Public interface ISPBTreeNode
An interface that, when implemented by an element in a smart property bag, provides a hint to diagnostic routines, particularly with respect to generating output.
Public interface ISynchChannel
Implemented by a synch channel. A synch channel is obtained from a Synchronizer, and is a one-use, one-client mechanism for gating execution. Once all clients that have acquired synch channels have called 'Synchronize' on those channels, they are all allowed to proceed, in the order implied by the Sequencer IComparable.
Public interface ISynchronizer
Interface implemented by all synchronizers. A Synchronizer is an object that is capable of making sure that things that could otherwise take place at differing times, occur at the same time.
Public interface ITransitionFailureReason
Encapsulates the reason for a transition failure, including what went wrong, and where.
Public interface ITransitionHandler
Implemented by a transition handler. A transition handler embodies the actions to be performed when the state machine is asked to make a transition from one state to another. The transition is performed via a two-phase protocol, first preparing to make the transition, and then if no handler that was involved in the preparation phase registered a failure reason, a commit operation is begun. Otherwise, if objections were registered, a rollback operation is begun.
Public interface IVisitable
An interface that is implemented by any object that can be visited. It typically does very little more than call iv.Visit(this);
Public interface IVisitable<(Of <(<'T>)>)>
An interface that is implemented by any object that can be visited. It typically does very little more than call iv.Visit(this);
Public interface IVisitor
Implemented by an object that can visit.

The purpose of the Visitor Pattern is to encapsulate an operation that you want to perform on the elements of a data structure. In this way, you can change the operation being performed on a structure without the need of changing the classes of the elements that you are operating on. Using a Visitor pattern allows you to decouple the classes for the data structure and the algorithms used upon them.

Each node in the data structure "accepts" a Visitor, which sends a message to the Visitor which includes the node's class. The visitor will then execute its algorithm for that element. This process is known as "Double Dispatching." The node makes a call to the Visitor, passing itself in, and the Visitor executes its algorithm on the node. In Double Dispatching, the call made depends upon the type of the Visitor and of the Host (data structure node), not just of one component.

Public interface IVisitor<(Of <(<'T>)>)>
Implemented by an object that can visit.

The purpose of the Visitor Pattern is to encapsulate an operation that you want to perform on the elements of a data structure. In this way, you can change the operation being performed on a structure without the need of changing the classes of the elements that you are operating on. Using a Visitor pattern allows you to decouple the classes for the data structure and the algorithms used upon them.

Each node in the data structure "accepts" a Visitor, which sends a message to the Visitor which includes the node's class. The visitor will then execute its algorithm for that element. This process is known as "Double Dispatching." The node makes a call to the Visitor, passing itself in, and the Visitor executes its algorithm on the node. In Double Dispatching, the call made depends upon the type of the Visitor and of the Host (data structure node), not just of one component.

Public interface SmartPropertyBag..::..IHasValue
Any item added to a SPB must implement this interface.

Delegates


  Delegate Description
Public delegate CloneHandler
Implemented in a method that is to be called after a cloning operation occurs.
Public delegate CommitTransitionEvent
This delegate is implemented by a method that is intended to be notified of the successful attempt to perform a transition, and to take part in the commitment of that transition attempt.
Public delegate DetachableEventAbortHandler
Delegate DetachableEventAbortHandler is the signature implemented by a method intended to respond to the aborting of a detachable event.
Public delegate EnumStateMachine<(Of <(<'TEnum>)>)>..::..StateMachineEvent
Public delegate ErrorEvent
Implemented by a method that is to be called when an error is added to, or removed from the model.
Public delegate Evaluator
A delegate returned by the evaluator factory, which will evaluate a precompiled expression with the the supplied argument values. Important to remember that the arguments passed in to an evaluator are treated as objects, so if it is expecting a double, and you pass in '3', it gets converted to an instance of System.Int32, and cannot be converted (implicitly) to a double.

This means that if it's expecting a double, pass in 3.0, not 3, or you'll get an invalid cast exception.

Public delegate EventMonitor
Implemented by any object that wishes to be notified as an event is firing.
Public delegate ExceptionHandler
Delegate ExceptionHandler is implemented by anything that can handle an exception. If [true] is returned, the exception is not propagated any further.
Public delegate ExecEventReceiver
This delegate is implemented by any method that is to receive a time-based callback from the executive.
Public delegate ExecutiveEvent
Implemented by any method that wants to receive notification of an executive event such as ExecutiveStarted, ExecutiveStopped, ExecutiveReset, ExecutiveFinished.
Public delegate GuidEvent
An event that notifies listeners of something happening related to a specified Guid.
Public delegate InitializationAction
Public delegate InitializationEvent
Public delegate Initializer
Delegate Initializer is implemented by any method that wishes to be called for initialization by an InitializationManager.
Public delegate ModelEvent
This delegate is implemented by any method that wishes to be called back when a model is, for example, starting or stopping.
Public delegate ModelObjectEvent
An event that notifies listeners of something happening to an IModelObject.
Public delegate PrepareTransitionEvent
This delegate is implemented by a method that is intended to perform part of the preparation for a transition. It accepts the model, and returns a reason for failing the transition, or null if the implementer of the delegate condones the completion of the transition.
Public delegate RollbackTransitionEvent
This delegate is implemented by a method that is intended to be notified of the unsuccessful attempt to perform a transition, and to take part in the rollback of that transition attempt.
Public delegate SmartPropertyBag..::..SPBDoubleDelegate
Delegate that is implemented by a delegate that is being added to the SPB, returning a double.
Public delegate StateMethod
Implemented by a method that is to be called once the state machine completes transition to a specified state.
Public delegate TaskProcessorListener
This delegate is implemented by any method that wishes to be called back when a task processor event, such as 'TaskProcessorAdded' and 'TaskProcessorRemoved' is fired.
Public delegate WarningEvent
Implemented by a method that is to be called when an warning is added to, or removed from the model.
Public delegate WritabilityChangeEvent
Fires when an object that can be made read-only, changes its writability status.

Enumerations


  Enumeration Description
Public enumeration DefaultModelStates
The two default states for a model. The Model's state machine can be replaced with a custom one, but these are the states of the default state machine.
Public enumeration ExecEventType
Used to select the way the Executive dispatches an event once its time has arrived. These mechanisms are as follows: Synchronous – the callback is called on the dispatch thread, and upon completion, the next callback is selected based upon scheduled time and priority. Detachable – the callback is called on a thread from the .Net thread pool, and the dispatch thread then suspends awaiting the completion or suspension of that thread. If the event thread is suspended, an event controller is made available to other entities which can be used to resume or abort that thread. This is useful for modeling “intelligent entities” and situations where the developer wants to easily represent a delay or interruption of a process. Batched – all events at the current time and priority are called, each on separate threads, and the executive, except for servicing any new events registered for that time and priority, awaits completion of all running events. This may bring about higher performance in cases such as battlefield and transportation simulations where multiple entities may sense current conditions, plan and execute against that plan. Asynchronous - This mechanism is not yet supported.
Public enumeration ExecState
Describes the state of the executive.
Public enumeration InitializerAttribute..::..InitializationType
This enumeration describes when in the lifecycle of a model, the initializer is called.
Public enumeration RefType
An enum that is used to describe the nature of a dependency relationship. It always refers to one object in context of another, such as in an InitializerArgAttribute, where it describes the relationship of the object being referred to in the argument to the object that owns the Initialize call. The documentation below will refer to the object that owns the initializer as the 'owner', and the object being referred to in the argument as the 'subject'.
Public enumeration SPBInitializer..::..InitType
Public enumeration StateMachine..::..GenericStates
Generic states are states that all state machines should support, and in declaring their states, set equality from appropriate states to these states. This will support interoperability of many libraries into state machines declared differently for different solutions, but with some of the same states defined in their lifecycles.