Home
Toward a Distributed and Deterministic
Contents
1. Unpublish HLA attributes for Object obj _hlaAttributesToPublish values try rtia unpublishObjectClass Integer obj 3 catch ObjectClassNotDefined e throw new IllegalActionException this e ObjectClassNotDefined catch ObjectClassNotPublished e throw new IllegalActionException this e ObjectClassNotPublished catch OwnershipAcquisitionPending e throw new IllegalActionException this e OwnershipAcquisitionPending catch FederateNotExecutionMember e throw new IllegalActionException this e FederateNotExecutionMember catch SavelnProgress e throw new IllegalActionException this e SavelnProgress catch RestoreInProgress e throw new IllegalActionException this e RestoreInProgress catch RTIinternalError e hrow new IllegalActionException this e RTIinternalError catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted if _debugging _debug this getDisplayName wrapup Unpublish TypedIOPort ob3 0 getContainer getName g e to HLA attributes 83 wrapup so termination classHandle obj 3 Resign HLA CERTI Federation execution try rtia resignFederationExecution ResignAction DELETE OBJECTS AND RELEASE ATTRIBUTES catch Federat
2. CertiLogicalTime ct new CertiLogicalTime currentTime getDoubleValue myEpsilon try _rtia updateAttributeValues Integer tObj 5 suppAttributes tag ct catch ObjectNotKnown e throw new IllegalActionException this e ObjectNotKnown catch AttributeNotDefined e throw new IllegalActionException this e AttributeNotDefined catch AttributeNotOwned e throw new IllegalActionException this e AttributeNotOwned catch FederateNotExecutionMember e throw new IllegalActionException this e FederateNotExecutionMember catch SavelnProgress e throw new IllegalActionException this e SavelnProgress catch RestoreInProgress e throw new IllegalActionException this e RestoreInProgress catch RTIinternalError e throw new IllegalActionException this e RTlinternalError catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch InvalidFederationTime e throw new llegalActionException this e InvalidFederationTime if _debugging _debug this getDisplayName publish send UAV updateAttributeValues current Ptolemy Time currentTime getDoubleValue HLA attribute TypedIOPort tObj 0 getContainer getName NV timestamp ct getTime value in toString Manage the correct termination of the link HlaManager Call t
3. _hlaManager getDisplayName To simplify the design of these new actors we volontary choose to implement the data communication logic in the HlaManager attribute This attribute provides the updateHlaAttribute method to a HlaPublisher actor to realize the sent operation 38 Mapping HlaPublisher to HLA attribute A HlaPublisher actoris mapped to one HLA attribute A Ptolemy token received in the input port of this actor is interpreted as an updated value of the HLA attribute The updated value is published to the whole HLA Federation using a mecanism provided by the HlaManager attribute deployed in a Ptolemy model The name of this HlaPublisher actor is mapped to the name of the HLA attribute in the federation This name needs to match the Federate Object Model FOM specified for the Federation see Table 5 1 The data type specified for the actor s input port actor has to be the same type of the one specified for the HLA attribute Finally the parameter classObjectHandle links the publisher to the attribute object class describes in the FOM FOM HlaPublisher actor object class parameter Name of object class in FOM attribute name of the actor Table 5 1 Mapping HlaPublisher to the FOM 5 4 2 HlaSubscriber to introduce HLA events in a Ptolemy model The HlaSubscriber actor implements the mecanisms required to inject a HLA event coming from a federate convert ing it in a Ptolemy event in
4. c CoSimu fed file FOM d Configuring HlaManager Figure A 2 FOM Now your Producer federate is ready and you can create the federates consumer and prodcons similar The steps are e Do step 2 duplicate the centralized model removing all composite actors excete the one you want to simulate For prodcons federate add a HlaPublisher for va12 and a HlaSubscriber for va11 Follow setp 4 for HlaPub lisher actor For the HlaSubscriber the procedure is the same Add also a HlaManager step 5 Pay attention to name the federate as prodcons in the configuration window of HlaManager figure A 2 d For consumer federate add two HlaSubscriber and a HlaManager Proceed as in steps 4 and 5 respectively Check if all your federates but one have the field Is synchronization point creator unticked Only one of them must have this field ticked and it must be the last one to be launched Remark if your composite actor has a DE director you can use directly the composite actor as in figure A 1 c or you can have a flat model as in figure A 1 d If the composite actor has a Continuous model then you need to use the composite actor 46 2 Running the federation 1 Open a terminal and run cfgCerti as said in the beginning of this manual or execute the SCERTI HOME share scripts myCERTI env sh shell 2 Go to the folder where the 3 federate models are or give the absolute address and open the models SPTII bin vergil consumer
5. received HLA Federation Management services callbacks Synchronization point services Callback delivered by the RTI CERTI to notify if the synchronization point registration has failed e public void synchronizationPointRegistrationFailed String synchronizationPointLabel throws FederateInternalError synchronizationFailed true if _debugging _debug HlaManager this getDisplayName INNER synchronizationPointRegistrationFailed synchronizationFailed synchronizationFailed Callback delivered by the RTI CERTI to notify if the synchronization point registration has succeed xf public void synchronizationPointRegistrationSucceeded String synchronizationPointLabel throws FederateInternalError synchronizationSuccess true if _debugging _debug HlaManager this getDisplayName INNER synchronizationPointRegistrationSucceeded synchronizationSuccess synchronizationSuccess 98 Callback delivered by the RTI CERTI to notify the announcement of a synchronization point in the HLA Federation T public void announceSynchronizationPoint String synchronizationPointLabel byte userSuppliedTag throws FederateInternalError inPause true if _debugging _debug HlaManager this getDisplayName INNER announceSynchronizationPoint inPause inPause Callback delivered by the RTI CERTI to notify that the Federate i
6. _hlaTimeStep value else if attribute hlaLookAHead Double value DoubleToken hlaLookAHead getToken 1 doubleValue if value lt 0 throw new IllegalActionException this Cannot have negative value _hlaLookAHead value else if attribute requireSynchronization _requireSynchronization BooleanToken requireSynchronization getToken booleanValue else if attribute synchronizationPointName String value StringToken synchronizationPointName getToken StringValue if value compareTo 0 throw new IllegalActionException this Cannot have empty name _synchronizationPointName value else if attribute isCreator _isCreator BooleanToken isCreator getToken booleanValue else super attributeChanged attribute Clone the actor into the specified workspace param workspace The workspace for the new object Qreturn A new actor exception CloneNotSupportedException If a derived class contains an attribute that cannot be cloned public Object clone Workspace workspace throws CloneNotSupportedException HlaManager newObject HlaManager super clone workspace newObject hlaAttributesToPublish new HashMap lt String Object gt newObject hlaAttributesSubscribedTo new HashMap lt String Object gt newObject fromFederationEvents new HashMap lt String LinkedList TimedEvent newObject objectIdToCl
7. try CertiRtiAmbassador rtia tick2 catch SpecifiedSaveLabelDoesNotExist e throw new IllegalActionException this e SpecifiedSaveLabelDoesNotExist catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch RTIinternalError e throw new IllegalActionException this e RTIinternalError if _debugging _debug this getDisplayName initialize Time Management policies is Constrained _federateAmbassador timeConstrained and is Regulator federateAmbassador timeRegulator The following service is required to allow the reception of callbacks from the RTI when a Federate used the Time management try rtia enableAsynchronousDelivery catch AsynchronousDeliveryAlreadyEnabled e throw new IllegalActionException this e AsynchronousDeliveryAlreadyEnabled catch FederateNotExecutionMember e throw new IllegalActionException this e FederateNotExecutionMember catch SaveInProgress e throw new IllegalActionException this e SaveInProgress catch RestoreInProgress e throw new IllegalActionException this e RestoreInProgress catch RTIinternalError e throw new IllegalActionException this e RTlinternalError 75 catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted i
8. else if type equals BaseType FLOAT return EncodingHelpers decodeFloat buffer else if type equals BaseType INT return EncodingHelpers decodeInt buffer else if type equals BaseType LONG return EncodingHelpers decodeLong buffer else if type equals BaseType SHORT return EncodingHelpers decodeShort buffer else if type equals BaseType STRING return EncodingHelpers decodeString buffer else throw new IllegalActionException this The current type received by the HLA CERTI Federation is not handled by this getDisplayName This generic method should call the link EncodingHelpers API provided by CERTI to handle type encoding operation for HLA value attribute that will be published param tok The token to encode return The encoded value as an array of byte throws IllegalActionException If the token is not handled or the encoding had failed private byte _encodeHlaValue Token tok Boolean asHLAPtidesEvent throws IllegalActionException byte encodedValue null Token t null double recordTimestamp 1 int recordMicrostep 1 double sourceTimestamp 1 GL FIXME PTIDES This first case handle events from a PtidesPlatform to PtidesPlatform only network port are supported if asHLAPtidesEvent RecordToken rt RecordToken tok recordTimestamp DoubleToken rt get timestamp doubleValue recor
9. EnableTimeConstrainedPending catch FederateNotExecutionMember e this e Qm yg throw new IllegalActionException FederateNotExecutionMemb catch SavelnProgress e throw new IllegalActionException this e SavelnProgress catch RestorelnProgress e throw new IllegalActionException this e RestoreInProgress catch RTIinternalError e throw new IllegalActionException this e RTIinternalError catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch NoSuchElementException e GL FIXME to investigate if _debugging _debug this getDisplayName proposeTime NoSuchElementException for rtia return proposedTime Wait the grant from the HLA CERTI Federation from the RTI _federateAmbassador timeAdvanceGrant false while _federateAmbassador timeAdvanceGrant if _debugging _debug this getDisplayName proposeTime wait CERTI TAG timeAdvanceGrant certiProposedTime getTime by calling tick2 try rtiastick2 3 catch SpecifiedSaveLabelDoesNotExist e throw new IllegalActionException this e SpecifiedSaveLabelDoesNotExist catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch RTIinternalError e throw new IllegalActionException this e RTIinternalErro
10. for HlaPublisher hp _hlaPublishers if _hlaAttributesToPublish get hp getName null throw new IllegalActionException this A HLA value with the same name is already registered for publication Only one input port is allowed per HlaPublisher actor TypedIOPort tiop hp inputPortlist get 0 _hlaAttributesToPublish put hp getName new Object tiop tiop getType StringToken Parameter hp getAttribute classObjectHandle getToken stringValue _hlaSubscribers ca entityList HlaSubscriber class for HlaSubscriber hs _hlaSubscribers if hlaAttributesSubscribedTo get hs getName null throw new IllegalActionException this A HLA value with the same name is already registered for subscription Only one output port is allowed per HlaSubscriber actor TypedIOPort tiop hs outputPortlist get 0 _hlaAttributesSubscribedTo put hs getName new Object tiop tiop getType StringToken Parameter hs getAttribute classObjectHandle getToken stringValue The events list to store HLA updated values received by callbacks from the RTI is indexed by the HLA Subscriber actors present in the model _fromFederationEvents put hs getName new LinkedList TimedEvent 88 This method is called when a time advancement phase is performed Every updated HLA attributes received by callbacks from the RTI
11. is set by callback by the RTI public LogicalTime logicalTimeHLA Federate time step public LogicalTime timeStepHLA Indicates if the request of synchronization by the Federate is validated by the HLA CERTI Federation This value is set by callback by the RTI y public Boolean synchronizationSuccess Indicates if the request of synchronization by the Federate has failed This value is set by callback by the RTI public Boolean synchronizationFailed Indicates if the Federate is currently synchronize to others This value is set by callback by the RTI K public Boolean inPause The lookahead value set by the user and used by CERTI to handle time management and to order TSO events public LogicalTimeInterval lookAHeadHLA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA 1111 public methods 1111 Initialize the link PtolemyFederateAmbassador which handles the communication from RTI gt to RTIA gt to FEDERATE The i rtia i manages the interaction with the external communicant process RTIA This method called the Declaration Management services provide by HLA CERTI to publish subscribe to HLA attributes in a HLA Federation param rtia throws NameNotFound hrows ObjectClassNotDefined hrows FederateNotExecutionMember hrows RTIinternalError hrows AttributeNotDefined hrows SavelnProgress hrows RestorelnProgress throws Concurre
12. to validate that the Federate is declared as time regulator in the HLA Federation public void timeRegulationEnabled LogicalTime theFederateTime throws InvalidFederationTime EnableTimeRegulationWasNotPending timeRegulator true if _debugging _debug HlaManager this getDisplayName timeRegulationEnabled timeRegulator 97 timeRegulator FederateInternalError INNER Callback delivered by the RTI CERTI to validate that the Federate is declared as time constrained in the HLA Federation x public void timeConstrainedEnabled LogicalTime theFederateTime throws InvalidFederationTime EnableTimeConstrainedWasNotPending FederateInternalError timeConstrained true if debugging _debug HlaManager this getDisplayName INNER timeConstrainedEnabled timeConstrained timeConstrained Callback TAG delivered by the RTI CERTI to notify that the Federate is authorized to advance its time to lt i gt theTime lt i gt This time is the same or smaller than the time specified when calling the nextEventRequest or the timeAdvanceRequest services x public void timeAdvanceGrant LogicalTime theTime throws InvalidFederationTime TimeAdvanceWasNotInProgress FederateInternalError logicalTimeHLA theTime timeAdvanceGrant true if _debugging _debug HlaManager this getDisplayName INNER timeAdvanceGrant TAG logicalTimeHLA toString
13. entrySet iterator while it5 hasNext Map Entry lt String LinkedList lt String gt gt elt Map Entry it5 next LinkedList lt String gt hlaSubList elt getValue int classHandle rtia getObjectClassHandle elt getKey The attribute handle set to declare all subscribed attributes for one object class AttributeHandleSet attributesLocal RtiFactoryFactory 94 getRtiFactory createAttributeHandleSet for String s hlaSubList attributesLocal add Integer _hlaAttributesSubscribedTo get s 41 _rtia subscribeObjectClassAttributes classHandle _attributesLocal Initialize Federate s timing properties provided by the user param startTime The start time of the Federate logical clock param timeStep The time step of the Federate param lookAHead The contract value used by HLA CERTI to synchronize the Federates and to order TSO events public void initializeTimeValues Double startTime Double timeStep Double lookAHead logicalTimeHLA new CertiLogicalTime startTime lookAHeadHLA new CertiLogicalTimeInterval lookAHead timeStepHLA new CertiLogicalTime timeStep timeAdvanceGrant false HLA Object Management services callbacks Callback to receive updated value of a HLA attribute from the whole Federation delivered by the RTI CERTI XI public void reflectAttributeValues int theObject ReflectedAttributes theAttributes byte userSuppli
14. n PDFRenderer jar ptll lib SEE D gt oa ptCal jar ptll lib l Migrate JAR File gt oa ptcolt jar ptll lib gt os ptjacl jar ptll lib Vu E gt OjavaProblems 1000f13388item b Java Task 100 of 2058 items Figure B 9 Resolve JCERTI interface dependencies in ptlII 3 58 Its Project Explorer 23 ve t 5 ptorermy actur ptarori test duto gt EH ptolemy actor ptalon test junit gt ptolemy actor sched gt E ptolemy actor sched test gt EH ptolemy actor sched test junit K iB ptolemy actor test gt EY ptolemy actor test junit gt ptolemy actor util gt Ei ptolemy actor util test gt Bi ptolemy actor util test junit gt B ptolemy apps gt B ptolemy apps hlacerti gt B ptolemy apps hlacerti demo gt B ptolemy apps hlacerti demo CoSimulation gt B ptolemy apps hlacerti demo CoSimulation cpp gt B ptolemy apps hlacerti demo CoSimulationFun gt B ptolemy apps hlacerti demo CoSimulationNetv gt B ptolemy apps hlacerti demo MultiDataTypes gt B ptolemy apps hlacerti demo MultiProducerCor gt 3 ptolemy apps hlacerti demo SimpleProducerC gt 3 ptolemy apps hlacerti demo SynchronizeToRe V ptolemy apps hlacerti lib gt J CertiRtig java Y jJ HlaManager java K 9 HlaManager gt LD HlaPtidesEvent java gt J HlaPublisher java gt J HlaSubscriber java hlaentities xml X HlaManagericon xml IX HlaPublisherlcon xml IX HlaS
15. 18 co simulation supports the 4 semantics of time management services TAR NER TARA and NERA proposed by HLA VAL1 204L Ptolemy DE Ptolemy DE VAL2 11 L Federate 1 HLA RTI Federate 2 TAR 2 Federate2 Cal Queue TAR 2 TAG 2 TAG 2 process a adt 2i m m m A r e G n an process u at 2 Federate1 Cal Queue TAR 11 process bat 5MK TAG 11 process VAL2 at 11 UAV VAL2 1141 UAV VAL2 114L TAR 20 receive RAV VAL2 11 L K process VAL2 at 20i llr process t at 20 UAV VAL1 20 L VAL1 will be processed at next TAR TAG iteration a Ra la O B H SL process c at 20 gt Request to advance time to TAG granted time by the RTI t E UAV RAV TAR lookahead gt 0 Wi Event processed by the sim L Lookahead t Logicaltime Figure 4 1 Synchronization model using TAR and lookahead 0 Scenario For each synchronization model we propose the following scenario Two Ptolemy DE federates Federatel and Federate2 have to process local events a 2 b 5 and c 20 for Federate1 and u 2 t 20 for Federate2 Federate2 publishes an updated value of event VAL2 at timestamp 11 and susbcribes to VAL1 Federatel sus bcribes to event VAL2 and at the reception of the event VAL2 publishes an updated value of event VAL1 Based on this simple
16. Eventbasedfederates 22e 5 3 5 3 Time stepped federates N RR ER KERE R R N 3 3 0 Federate Ambassador i sira dra oo EC a aaa 5 3 7 UAV and updateHlaAttribute e HlaPublisher and HlaSubscriber actors es 5 4 1 HlaPublisher send Ptolemy events to the HLA CERTI Federation 5 4 2 HlaSubscriber to introduce HLA events in a Ptolemy model Interaction between TimeRegulator HlaManager and HLA actors o o 5 5 Interaction with HlaPublisher a 5 5 2 Interaction with HlaSubscriber les 6 Conclusion and perspectives Bibliography Appendix A User Manual for HLA PTII federates 1 2 Building a model with HLA PTII co simulation framework llle Running the federation sis a a AA et R CR acne ted a Appendix B Installation guide user guide and known issues 1 2 3 Installation Guide introduction ee Installing Ptolemy and vergil 22s Installation of the CERTI environment les 3 1 Requirements roana ceteros dur Ta d It oe oo BRE BRE Bole ae TIR a UR 3 2 Installation process 9 Ta TE S R E ee 3 3 Deployment and execution 3 4 Enable the Debug mode oes Installation of the JCERTT interface a 4 1 Installation process 4s Ba A A A T BA e e uy 4 2 Deployment in Eclipse p iria as dear ee eee E Me Pe d R RE dius Installation of the Ptolemyll project e 5 1 Shortcut to launch
17. HLA Object Model Template omt Specification IEEE Std 1516 21 M 2010 pages 1 110 2010 G Lasnier J Cardoso P Siron and Pagetti Environnement de cooperation de simulation pour la conception de systemes cyber physiques Journal europeen des systemes automatises 47 2013 G Lasnier J Cardoso P Siron C Pagetti and P Derler Distributed simulation of heterogeneous and real time systems In Distributed Simulation and Real Time Applications DS RT 2013 IEEE ACM 17th International Symposium on page 20 2013 Edward A Lee Modeling concurrent real time processes using discrete events Ann Software Eng 7 25 45 1999 Edward A Lee Heterogeneous actor modeling In Proceedings of the 11th International Conference on Embedded Software EMSOFT 2011 pages 3 12 2011 43 16 17 18 19 20 21 MathWorks MATLAB Simulink 2013 Modelica Association Modelica A unified object oriented language for physical systems modeling language specification version 3 3 2012 Modelisar Functional mock up interface for model exchange and co simulation Version 2 0 beta 4 Technical report Information Tech for European Advancement Aug 2012 Eric Noulard Jean Yves Rousselot and Pierre Siron CERTI an open source RTI why and how Spring Simulation Interoperability Workshop 2009 ONERA The Open Source middleware CERTI 2013 Claudius Ptolemaeus editor System Design Modeling and Simulation us
18. In this guide we assume that all sources binaries scripts etc will be located in the user folder HOME pthla Make sure to create this folder before running the installation process 2 Installing Ptolemy and vergil If you want only to use the co simulation framework for running the demo and create new distributed models you need just to install the graphical vergil editor of Ptolemy and CERTI section 3 We recommend to create the SHOME pthla workspace folder and to download using svn the pt II project in this folder You need e SVN 1 6 17 or later an open source version control used by Ptolemy e A Java compiler Java JDK 6 0 or later used to compile Ptolemy This chapter was partially update on March 2015 This framework was tested for Ptolemy up to revision 171806 and CERTI 3 5 After revision r71518 Ptolemy comes with jcerti jar so section 4 would be no longer needed http ptolemy eecs berkeley edu 3http savannah nongnu org projects certi 48 O Pa Ro go to SHOM E pthla workspace svn co https repo eecs berkeley edu svn anon projects eal ptII trunk ptII export PTII SHOME pthla workspace ptII cd PTII 4 configure there is a build xml in PTIT C1 ant 6 cd SPTII bin 7 make You can run now SPTII bin vergil amp For running Ptolemy HLA federates you need just to install CERTI see sections 3 1 to 3 4 3 Installation of the CERTI environment This section desc
19. Let us consider el ti ni and e2 t n2 The calendar queue is sorted 1 by timestamp if ti lt t2 or if t t and n lt m then el is executed before e2 2 by actor s ranking if t t and n m the director selects the actor that has the lowest rank The actor ranking is defined by a topological sort of the actors in the model in data precedence order 14 The time advancement phase in a DE model is observed when the DE director selects the earliest event in the calendar queue making its timestamp the current model time and firing the destination actor of the event This algorithm is performed at the director level and during this phase no actor is fired 16 Chapter 4 Co Simulation for Heterogeneous and Distributed Simulation The design of cyber physical system model for simulation is a rigorous task where various models of the system at different abstraction level cooperate These models can also be executed on different embedded platforms to hence the simulation performances or to produce relevant results with a deployment close to the real distributed architecture of the application Distributed simulation is useful for network modeling and simulation exhibit non determinism and complex behavior and large scale simulation It enables the abstraction by separation of simulation tasks into different simulations using standard interfaces and increases the processing power of a simulation by scheduling tasks
20. Synchronization error End block for synchronization point creation case Wait synchronization point announcement while _federateAmbassador inPause try CertiRtiAmbassador rtia tick2 catch SpecifiedSaveLabelDoesNotExist e throw new IllegalActionException this e SpecifiedSaveLabelDoesNotExist catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch RTIinternalError e 76 throw new IllegalActionException this e RTIinternalError Satisfied synchronization point try rtia synchronizationPointAchieved synchronizationPointName if debugging debug this getDisplayName initialize Synchronisation point _synchronizationPointName satisfied catch SynchronizationLabelNotAnnounced e throw new IllegalActionException this e SynchronizationLabelNotAnnounced catch FederateNotExecutionMember e throw new IllegalActionException this e FederateNotExecutionMember catch SavelnProgress e throw new IllegalActionException this e SavelnProgress catch RestorelnProgress e throw new IllegalActionException this e RestorelnProgress catch RTIinternalError e throw new IllegalActionException this e RTlinternalError catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentA
21. currentTime granted time to advance to given by the RTI to the DE director select next event e t dest in queue if event Based and L gt O then call NER t else if event Based and L 0 then call NERA t else if timeStepped and L gt 0 then call TAR t else if timeStepped and L 0 then call TARA t else raise HLA service configuration error while not TAG tg do if RAV val t then store val t and merge in queue end if event Based and L 0 then for number of NERA needed do call NERA tg while not TAG tg do if RAV val tg then store val tg and merge in queue end end call NER tg while not TAG tg do if RAV val tg then store val tg and merge in queue end set current Time tg end if timeStepped and L 0 then for number of TARA needed do call TARA tg while not TAG tg do if RAV val tg then store val tg and merge in queue 5 end end call NER tg while not TAG tg do if RAV val tg then store val tg and merge in queue Q end set currentTime lt tg end if L gt 0 then set currentTime lt tg return currentTime Algorithm 4 DE time management algorithm for co simulation 25 Chapter 5 Architecture design and implementation 5 1 Framework architecture This section gives technical and implementation details about the architecture and the choices made to design and to implement our co simulation framework The fram
22. during the time advancement phase is saved as link TimedEvent and stored in a queue Then every link TimedEvent s are moved from this queue to the output port of their corresponding link HLASubscriber actors throws IllegalActionException If the parent class throws it El private void putReflectedAttributesOnHlaSubscribers throws IllegalActionException Reflected HLA attributes e g update of HLA attributes received by callbacks from the RTI from the whole HLA CERTI Federation are store in the _subscribedValues queue see reflectAttributeValues in PtolemyFederateAmbassadorInner class TimedEvent event for int i 0 i lt _hlaAttributesSubscribedTo size 1 Iterator lt Entry lt String LinkedList lt TimedEvent gt gt gt it _fromFederationEvents entrySet iterator while it hasNext Map Entry lt String LinkedList lt TimedEvent gt gt elt Map Entry it next GL FIXME Check if multiple events here with same timestamp make sense and can occur 1f true we need to update the following code to handle this case if elt getValue size gt 0 event elt getValue getFirst TypedIOPort tiop TypedIOPort Object _hlaAttributesSubscribedTo get elt getKey 0 HlaSubscriber hs HlaSubscriber tiop getContainer hs putReflectedHlaAttribute event if debugging _debug this getDisplayName _putReflectedAttributesOnHlaSubscri
23. his his his his e yg e ng e i e e e ro e e e T SavelnProgress RestoreInProgress RTIinternalError if true e his e bled e His e ing e his e ess his e ae his e his e his e his e InvalidLookahead SaveInProgress RestoreInProgress RTIinternalError _hlaTimeStep ys leTimeRegulation _federateAmbassador logicalTimeHLA _federateAmbassador lookAHeadHLA T n if catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted Wait the response of the RTI towards Federate time policies that has been declared The only way to get a response is to invoke the tick method to receive callbacks from the RTI We use here the tick2 method which is blocking and saves more CPU than the tick method _isTimeRegulator amp amp isTimeConstrained while _federateAmbassador timeConstrained try ctas Lick y catch SpecifiedSaveLabelDoesNotExist e throw new IllegalActionException this e SpecifiedSaveLabelDoesNotExist catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch RTIinternalError e throw new IllegalActionException this e RTIinternalError while _federateAmbassador timeRegulator
24. 2 Included All Javadoc Location ENTERA O Link Source Puch xi Native library location None Project References 2 a R Run Debug Settings E Ignore optional compile problems No rre Server Task Repository Task Tags EH gt Validation WikiText C Allow output folders for source folders Default output folder pul Browse Cori E P vog gt amp Java Problems 100 of 13285 items b Java Task 100 of 2039 items 2 pul Figure B 2 Build path gt Source tab of ptIT gt difficult to track all the bugs Nevertheless if you find some bugs or bad behaviors you re welcome to contact our team In this section we present a list of bugs or bad utilization of our framework that may cause some problems to run a Ptolemy HLA CERTI distributed simulation 8 1 Specification of Ptolemy federate This subsection concerns bad behavior that may happen if something is wrong with the specification of a Ptolemy federate Typed port of HLA actors We have seen in chapter 77 that an HLA actor is mapped to an HLA attribute de scribed in the FOM The type of the input or output port of the HLA actor must match the type of its corresponding HLA attribute Ptolemy provides a feature to the modeler called Backward type inference that simplifies the type specification of ports involved in a Ptolemy model Such mechanism is based on the analysis of the actors and their ports involved in the model This mechanism may cause
25. But distributed simulation also comes with complexities Developing a distributed simulation architecture is more complex than a serial one and two majors issues are timing synchronization of nodes and control how to maintain the control of simulation The co simulation framework for heterogeneous and distributed simulation leverages two open source simulators Ptolemy and HLA CERTI In chapter 2 and chapter 3 we have presented the time management semantics and the data communication operated by each simuation tools In particular both present the same characteristic to separate the time advancement phase and the data communication In our case data communication means the events timestamp value exchanged between nodes Considering the DE model in Ptolemy event interaction between I O ports are based on a token receivers mecanism and actor are fired at specific point in time to process the event i e the token HLA is based on the publish subscribe paradigm and two services UAV and RAV are provided for emission and reception of updated HLA attribute values DE event semantics is based on the implementation of a calendar queue where events are stored and sorted following a specific order see chapter 3 The time advancement phase in DE correspond to take the earliest event from the queue and process it The DE Director behavior is responsible of the queue management The next sections describe the strategy chosen for the co simulatio
26. CERTI USE NULL PRIME MESSAGE PROTOCOL param proposedTime The proposed time return The proposed time or a smaller time exception IllegalActionException If this attribute is not contained by an Actor public Time proposeTime Time proposedTime throws IllegalActionException Time breakpoint null This test is used to avoid exception when the RTIG subprocess is shutdown before the last call of this method GL FIXME see Ptolemy team why this is called again after STOPTIME 7 if rtia null if _debugging _debug this getDisplayName proposeTime called but _rtia is null return proposedTime 78 If the proposedTime has already been asked to the HLA CERTI Federation then return it GL FIXME Comment this until the clarification with NERA and TARA and the use of TICK is made if lastProposedTime null if lastProposedTime compareTo proposedTime 0 Even if we avoid the multiple calls of the HLA Time management service for optimization it could be possible to have events from the Federation in the Federate s priority timestamp queue so we tick to get these events if they exist try _rtia tick catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch RTIinternalError e throw new IllegalActionException this e RTIinternalError return _
27. Connection to RTIA failed Exception in clockDisplayer HlaManager Because hla rti RTlinternalError serial 0 Go To Actor Display Stack Trace Dismiss Figure B 12 RTlinternalError hla rti RTlinternalError serial 0 59 Appendix C Code snippets Listing C 1 ptolemy actor TimeRegulator java Interface for attributes that regulate the passage of time Copyright c 2007 2013 The Regents of the University of California All rights reserved Permission is hereby granted without written agreement and without license or royalty fees to use copy modify and distribute this software and its documentation for any purpose provided that the above copyright notice and the following two paragraphs appear in all copies of this software IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT INDIRECT SPECIAL INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES I DING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE THE SOFTWARE P D C 0 E ED HEREUNDER IS ON AN AS IS BASIS AND THE UNIVERSITY OF RNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE SUPPORT UPDATES HANCEMENTS OR MODIFICATIONS PT COPY
28. Ptolemy model A public void initialize throws IllegalActionException super initialize CompositeActor ca CompositeActor this getContainer List lt HlaManager gt hlaManagers ca attributeList HlaManager class if hlaManagers size gt 1 throw new IllegalActionException this Only one HlaManager attribute is allowed per model else if hlaManagers size 1 throw new IllegalActionException this A HlaManager attribute is required to use this actor Here we are sure that there is one and only one instance of the HlaManager in the Ptolemy model _hlaManager hlaManagers get 0 Each tokens received in the input port are transmitted to the link HlaManager for a publication to the HLA CERTI Federation public void fire throws IllegalActionException if inputPortlist get 0 hasToken 0 Token in inputPortList get 0 get 0 hlaManager updateHlaAttribute this getName in asHLAPtidesEvent if _debugging debug this getDisplayName Called fire the update value in toString 1 of the HLA Attribute this getName has been sent to hlaManager getDisplayName HUMUM MB AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA 1111 private variables 111 A reference to the associated link HlaManager private HlaManager _hlaManager Indicate if the event is for a Ptides platform private boo
29. a Ptolemy federate model that will exchanges data with a federation The semantics attached to those services and given in chapter 2 is well suited for an integration in the Ptolemy framework Thanks to the time management service described above events received from the other federates of the federation are injected at timestamp in the Ptolemy federate model see NER and NERA semantics in chapter 4 5 3 5 3 Time stepped federates The user may select time stepped time advancement mecanisms TAR and TARA for a specific purpose One reason could be to force a Ptolemy federate model to produce outputs resp to receive inputs to the federation only at periodic time This could be usefull for predictable computations as required for schedulability analysis As we deal with the strong semantics of TAR and TARA defined by the HLA standard the user have to assume the following restriction Restriction 2 The use of Ptolemy time stepped federates implies that each RAV received during the time advance ment phase will have its timestamp set to the proposeTime value used for the time advance request By this restriction the user assumes that a Ptolemy federate may receive HLA events with timestamp less than the proposeTime value that will be injected in the Ptolemy simulation with a different timestamp proposeTime value This restriction avoids to introduce HLA events in a Ptolemy simulation with a timestamp less than the currentTime of the Dire
30. a Ptolemy model from Eclipse 2 000 Compile the PtolemylI HLA CERTI co simulation framework with Ptolemy Running a quick example a Known issues 20x a Bae eR a A a Ea oi Ret ab CORE os 8 1 Specification of Ptolemy federate 2000000020000 8 2 Running Ptolemyll HLA CERTI simulation lee Appendix C Code snippets 42 42 45 45 47 48 48 48 49 49 49 50 50 51 51 51 51 52 52 53 53 54 55 60 Acknowledgement I would like to thank my advisors Janette Cardoso Claire Pagetti and Pierre Siron for their valuable collaboration during this one year Oct 2013 gt Sept 2014 post doctoral research in Toulouse I would like to thank ISAE Foundation that provided the funding to stay 6 weeks at the CHESS team at Berkeley Univ I would like also to thank Edward Lee from Berkeley Univ for receiving me so nicely in his team I truly enjoyed the fruitful discussions and the collaboration to create a new interface to perform this co simulation framework During this stay I had the support from Christopher Brooks Patricia Derler and Marten Loshstroh many thanks to them Thanks also to Stavros Tripakis for useful discussions Chapter 1 Introduction 1 1 Context A Cyber Physical System CPS is a system composed of computational units networks and physical processes Embedded controllers and networks monitor and control the physical processes Feedback loops a
31. advancement algorithm implemented in a proposeTime method is given in the next section 5 3 5 2 3 Usage of multiple time regulator attributes Whenever a director has to advance its current time if one or more time regulators attributes are attached to the top level model then the proposeTime method of thoses attributes are executed before the time is advanced by the director Only the smallest time returned by those attributes is returned to the director If there is no such attribute the initial time advancement algorithm in Director java is performed An example of the use of different attributes attached to the same Ptolemy model is given in the ptolemy apps hlacerti dem demo This demo shows the behavior of the SynchronizeToRealTime attribute which implements real time syn chronization with the execution platform and the HlaManager attribute which implements the time management according to the HLA semantics Both fime regulator attributes are executed during the simulation 5 3 HlaManager attribute The HlaManager is the main entity of our framework which handles the time management and data communication mecanisms required between a Ptolemy federate and a HLA federation This entity is implemented as a Time Regulator Ptolemy attribute describes above and provides a set of mecanisms and methods to realize the followng operations 1 initialize a federation 2 initialize a Ptolemy federate model as a regulator and or contrain
32. allow to send updated values of VAL1 and VAL2 without advancing the time of the simulation This behavior is the same as the one specified by HLA 4 3 Co simulation requirements In the previous sections of this chapter we have defined the synchronization models and proposed a time advance ment algorithm for our co cosimulation framework This section summarizes the different requirements needed to make effective the interface between a DE Ptolemy federate and an HLA CERTI These requirements are defined in three categories interoperability repeatability and determinism HLA TM services Events Federatel Federate2 TAR L gt 0 i pe a L peers nen iteration TAR TAG with t gt 20 eo DUI TARA L 0 a S next iteration TAR TAG with t gt 20 mana Ro URS T Figure 4 2 Co simulation behavior VAL1 and VAL2 events processing L lookahead In the next subsection we give the algorithm to adapt the time advancement mecanism of a DE director to handle these 4 time advancement algorithms 4 3 1 Time management algorithm for the co simulation In the previous subsection we have discussed the four time advancement algorithms which represent the different behaviors expected by the co simulation Ptolemy HLA CERTI To allow these behaviors it is necessary to adapt the DE director time management algorithm and to interface the Ptolemy model with an HLA CERTI federation To do so we pr
33. and director 22s Co Simulation for Heterogeneous and Distributed Simulation 4 1 Co simulation Strategy eV oi is Be bee WU a S AR 4 2 Time Management s a ach dy EE eb ph pe d a Ee TA K EET aa h ia 4 2 1 Synchronization models ee 42 2 Main behavior ce Ree NEUE b ea ae an Pu ud 4 3 Co simulation requirements 4 3 1 Time management algorithm fortheco simulation leen 4 9 2 nt roperability ss oh eee 2 ae oben mec x maet doce eae e eet 4 33 Repeatability E 2 6 R R A es YR C UV med 4 3 4 Deterinimitsm c une obe I av UU kk a eae BA cda 4 4 Proposition of a co simulation architecture eA Architecture design and implementation 5 1 Framework architecture ees 5 2 IxmeRegulator unterace dh id headed o a a a Oo ek ee vx e 5 2 1 Ptolemy core modification es 5 22 proposelzme method TTT 5 2 3 Usage of multiple time regulator attributes o 5 3 HlaManager attribute RE e R R R ae R es 2 394L A e Sag DE RP ai RA Mace ee ed ae ev RTE R dde bero ahs 5 3 2 AnitialtzatiOn i su a Rom T a ada eR ha 5 9 9 WLAPUD ace wee wher des A a A foe AA AA AAA e GO DA 10 12 12 12 12 13 14 14 15 15 15 15 16 17 17 18 18 19 20 20 20 22 23 23 5 4 5 5 5 9 4 Data C E nose Met p dx e oe x qo perdo cde ae a Bee URN 5 3 5 Time management ee 5 3 9 propose Ime ave weg Ro a A EU E rS EI RAS E 5 3 5 2
34. case 1 and CERTI has to be compiled with the option N CERTI USE NULL PRIME MESSAGE PROTOCOL param proposedTime The proposed time return The proposed time or a smaller time exception IllegalActionException If this attribute is not contained by an Actor a Override public Time proposeTime Time proposedTime throws IllegalActionException Time breakpoint null This test is used to avoid exception when the RTIG subprocess is shutdown before the last call of this method GL FIXME see Ptolemy team why this is called again after STOPTIME 7 if _rtia null if _debugging _debug this getDisplayName proposeTime called but rtia is null return proposedTime If the proposedTime has already been asked to the HLA CERTI Federation then return it GL FIXME Comment this until the clarification with NERA and TARA and the use of TICK is made if lastProposedTime null 32 if lastProposedTime compareTo proposedTime 0 Even if we avoid the multiple calls of the HLA Time management service for optimization it could be possible to have events from the Federation in the Federate s priority timestamp queue so we tick to get these events if they exist try rtia tieoki catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch RTIinternalError e throw
35. for in Cyber Physical Systems a Concept Map http CyberPhysicalSystems org POSSIBLY WITH Humans in the Loop POSSIBLY Wireless Networked and or Distributed ul sensing Actuation EE e Adaptive and Predictive Intelligent Resilience Tae gt ca Figure 1 1 Concept map of cyber physical systems http cyberphysicalsystems org stance a flight control composed of two sub functions distributed on two calculators communicating via an Ethernet network To observe the real behavior on the platform it is necessary to describe the functional behavior of each component as well as the timing requirements of the platform and the network that communicates the data between the two sub functions 1 2 Contribution The purpose of this research work is to provide an integrated methodology for distributed and heterogeneous simula tion of realtime CPS where simulation components may be designed at different levels in the developments process Components may be models with different abstraction levels software functionnalities e g controllers or hard ware materials e g embedded computers sensors or actuators Gather multiple simulation components evolving at different abstraction level to build a complex simulation tackles the complexity of the heterogenous aspect and the interoperability aspect of CPS design describes in the previous subsection Distributed simulation is required here to
36. hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla ti ArrayIndexOutOfBounds ti AsynchronousDeliveryAlreadyEnabled ti AttributeHandleSet ti AttributeNotDefined ti AttributeNotKnown ti AttributeNotOwned ti ConcurrentAccessAttempted ti CouldNotDiscover ti CouldNotOpenFED ti EnableTimeConstrainedPending ti EnableTimeConstrainedWasNotPending ti EnableTimeRegulationPending ti EnableTimeRegulationWasNotPending ti ErrorReadingFED ti EventRetractionHandle ti FederateAlreadyExecutionMember ti FederateAmbassador ti FederateInternalError ti FederateNotExecutionMember ti FederateOwnsAttributes ti FederatesCurrentlyJoined ti FederationExecutionAlreadyExists ti FederationExecutionDoesNotExist ti FederationTimeAlreadyPassed ti InvalidFederationTime ti InvalidLookahead ti InvalidResignAction ti LogicalTime ti LogicalTimeInterval ti NameNotFound ti ObjectAlreadyRegistered ti ObjectClassNotDefined ti ObjectClassNotKnown ti ObjectClassNotPublished Be ORE Re gt A I RS O NL E RS T E SRR OR PES Be o ys EY 3 64 impor impor import import impor impor impor import impor impor impor import import impor impor impor import im
37. java util List AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA AAA HlaPublisher lt p gt This actor implements a publisher in a HLA CERTI federation This publisher is associated to one HLA attribute Ptolemy s tokens received in the input port of this actor are interpreted as an updated value of the LA attribute The updated value is published to the whole HLA Federation y the link HlaManager attribute deployed in a Ptolemy model p gt lt p gt he name of this actor is mapped to the name of the HLA attribute in the ederation and need to match the Federate Object Model FOM specified for he Federation The data type of the input port has to be the same type of he HLA attribute The parameter lt i gt classObjectHandle lt i gt needs to match the attribute object class describes in the FOM The parameter lt i gt asHlaPtidesEvent lt i gt indicates if we need to handle PTIDES events as RecordToken in HLA events lt p gt ct ct Fh KM A O m author Gilles Lasnier Contributors Patricia Derler version Id HlaPublisher java 423 2013 09 05 16 38 462 g lasnier since Ptolemy II 10 0 Pt ProposedRating Yellow glasnier Pt AcceptedRating Red glasnier L 0 0X 0X 0 00 0 0X 0X 00 00 00 0X 0X 0X 00 00 0X X X X X public class HlaPublisher extends TypedAtomicActor Construct the HlaPublisher actor param container The container param name The name of this actor ex
38. new IllegalActionException this e RTIinternalError return lastProposedTime el If the HLA Time Management is required ask to the HLA CERTI Federation the RTI the authorization to advance its time if isTimeRegulator amp amp _isTimeConstrained synchronized this Build a representation of the proposedTime in HLA CERTI CertiLogicalTime certiProposedTime new CertiLogicalTime proposedTime getDoubleValue Call the corresponding HLA Time Management service try if eventBased if hlaLookAHead gt 0 Event based lookahead gt 0 gt NER if debugging _rtia nextEventRequest certiProposedTime else Event based lookahead 0 gt NERA NER Start the time advancement loop with one NERA call if _debugging _rtia nextEventRequestAvailable certiProposedTime Wait the grant from the HLA CERTI Federation from the RTI _federateAmbassador timeAdvanceGrant false while _federateAmbassador timeAdvanceGrant if _debugging try _rtia tick2 catch Exception e throw new Exception reason End the loop with one NER call if debugging _rtia nextEventRequest certiProposedTime else if _hlaLookAHead gt 0 Time stepped lookahead gt 0 gt TAR if debugging _rtia timeAdvanceRequest certiProposedTime 33 else Time stepped lookahead 0 gt TARA TAR S
39. not exists allows the Federate to join the Federation set the Federate time management policies regulator and or contrained creates a synchronisation point if required and synchronizes the Federate with a synchronization point if declared exception IllegalActionException If the container of the class is not an Actor or If a CERTI exception is raised and has to be displayed to the user public void initialize throws IllegalActionException super initialize NamedObj container getContainer if container instanceof Actor throw new IllegalActionException this HlaManager has to be contained by an Actor Get the corresponding director associate to the HlaManager attribute _director DEDirector CompositeActor this getContainer getDirector Initialize HLA attribute tables for publication subscription _populateHlaAttributeTables Get a link to the RTI RtiFactory factory null try factory RtiFactoryFactory getRtiFactory catch RTIinternalError e throw new IllegalActionException this e RTlinternalError try _rtia CertiRtiAmbassador factory createRtiAmbassador catch RTIinternalError e throw new IllegalActionException this e RTIinternalError 72 Create the Federation or raise a warning it the Federation already exits try rtia createFederationExecution federationName fedFile asFile toURI toURL catch Federa
40. requirement is satisfied in our co simulation framework by the strict respect of the contracts defined in section 2 and section3 A proof to ensure repeatibility is also given there Based on the study of the HLA standard the requirements for a Ptolemy federate to ensure repeatability are e R6 Ptolemy federate must process event in timestamp ordering e R7 Ptolemy federate must handle simulateneous event ordering debut de preuve Assuming that a federate handles simultaneous events the repeatability is sastified in HLA for the following cases e Lookahead gt 0 C1 C3 or C2 C3 e Lookahead 0 C4 1 C4 2 22 4 3 4 Determinism The last requirement is about deterministic simulation Determinism in the simulation of CPS is an important property For our co simulation framework we give the following definition Definition 3 A distributed simulation is said to be deterministic if successive executions process the same inputs in the same order and produce exactly the same outputs The main requirement for a Ptolemy federate to handle determinism is e R Ptolemy federate must process input events in order 4 4 Proposition of a co simulation architecture In the previous section we have studied the different behaviors and requirements needed for the co simulation frame work Ptolemy HLA CERTI We have also proposed a time advancement algorithm that allows the use of the time management services provided by HLA Thus the
41. some troubles in the specification of HLA actors particularly with the HlaSubscriber actor As this actor allows to introduce updated value of an HLA attribute received from the federation sometimes the Backward type inference mechanisms can not resolved the type of its output port due to a lack of information from the model It is recommended to the user to specify manually the type of the output port of the HlaSubscriber to avoid such troubles 54 Eclipse M2AC a O 7 60 11 lun 30 sept 22 33 Gilles LASNIER Q Jay 600 Inclusion and Exclusion Patterns jae rm 35 0 x o gt y F Inclusion and Exclusion Patterns Q Quick Access ES 9 Java EE E E Add or remove inclusion and exclusion patterns to source folder E pe filter te T L Project Explorer 53 BS type filter ce Y Outline 3 ask List O rj P Resource gt gt pul Builders Inclusion patterns 1 outline is not available Java Build Path da l gt Java Code Style gt Java Compiler gt b Java Editor Add Multiple Javadoc Location Project Facets Edit Project Referen Run Debug Server Remove gt Task Repository Bv Tags Exclusion patterns alidation b 7 pt modules WikiText 5 ptdb Add 25 ptolemy actor lib excel Add Multiple 25 ptolemy actor lib fmi 35 ptolemy actor lib io comm Es 25 ptolemy actor lib jai 35 ptolemy actor lib jmf 25 ptolemy actor lib joystick Remove 25 ptolemy ac
42. the Ptolemy event in the internal event queue and program the re firing of the actor using fireAt at the event timestamp Listing 5 6 Code snippets of ptolemy apps hlacerti HlaSubscriber java Store each updated value of the HLA attribute mapped to this actor in the tokens queue Then program the next firing time of this actor to send the token at its expected time This method is called by the link HlaManager attribute param event The event containing the updated value of the HLA attribute and its time stamp exception IllegalActionException Not thrown here public void putReflectedHlaAttribute TimedEvent event throws IllegalActionException Add the update value to the queue _reflectedAttributeValues add event 39 Director HlaSubscriber HlaManager RTI proposeTime t2 TAR t2 Director HlaPublisher HlaManager RTI tick fire at t1 RAV t 1 inputPortList get 0 putReflectedHlaAttribute nlad J fireAt t2 J TAGt t2 updateHlaAttribute TR leer acad UAV t1 gt freta gt normal invocation lt return value lt callbacks a Updating of a HLA Attribute b Handling reflected HLA Attribute Figure 5 4 Execution flow Program the next firing time for the update value received _fireAt event timeStamp 5 5 Interaction between TimeRegulator HlaManager and HLA actors This section presents the interaction between the T
43. time constrained and regulated e for the time managment only NER service was fully tested e only one synchronization point is allowed e only one instance of a same class can be used in a Ptolemy HLA federate Several demos are available at the Ptolemy tree Among then there is the case study of a distributed simulation of an hierarchical Ptolemy model based on the F 14 Longitudinal Flight Control demo model from Matlab This federation has 3 federates the physical model Continuous director the AutoPilot DE director and the Pilot Stick The Pilot Stick federate was successfully replaced by a real joystick controlling the elevator This framework is an on going work and some points will be improved mainly e have a fully tested environnment for TAR TARA and NERA services e allow for multiple instances of a class e formalize the algorithms for the time management in Ptolemy HLA e improve the test suite allowing the verification of good behavior of this co simulation framework 42 Bibliography 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 M U Awais P Palensky A Elsheikh E Widl and S Matthias The HLA RTI as a master to the functional mock up interface components In Computing Networking and Communications ICNC 2013 International Conference on pages 315 320 2013 IEEE SA Standards Board Ieee standard for modeling and simulation high level
44. user has the possibility to configure the framework according to the Ptolemy federate behavior that he wants to design From the analysis of the requirements and the strategy chosen to implement the co simulation framework we can describe the following new elements for having a Ptolemy federate model e asimulation interface in Ptolemy to adapt the time advancement algorithm of the DE director e an entity actor or attribute to encapsulate the high level logic of HLA initilialization creation join decla ration time management etc e aconfiguration interface to tune the HLA time management services e a ptolemy entity to send Ptolemy events to the HLA federation e a ptolemy entity to introduce events from the HLA federation in the Ptolemy model DE Director Manager e stopTime 10 I Ber Actor1 Monitor UAV RAV Bio E Figure 4 4 Proposition of the Co Simulation architecture These elements are defined and implemented as actors or attributes in ptolemy Based on these needs we pro posed the architecture presented in figure 4 4 for the co simulation framework A general simulation interface was designed that allows a director to modify its time advancement algorithm This interface may be enabled by the deployment of a specific ptolemy entities in the model The new framework has the following components 23 HLA Manager This manager handles all the high level logic of HLA and enables the interopoe
45. xml producer xml prod cons xml amp 3 Check there is no rtig process running the first model to be run will automatically launch this process If there is a rt ig running kill the process 4 Check there is only one model that has the field Is synchronization point creator ticked Run the other models in any order but the last to be run is the one that has the cited field ticked 47 Appendix B Installation guide user guide and known issues 1 Installation Guide introduction The current co simulation framework has been deployed and tested under the following architectures MacOSX 32 bits MacOSX 64 bits Linux Ubuntu 13 04 The Raring Ringtail 32 and 64 bits This guide could also be used at entrypoint to install the framework on different Linux based distributions or even under Windows platforms according to the different versions supported by PtolemyII and CERTI As our co simulation is fully integrated in the Ptolemy framework the execution of a simulation using the Ptole myll HLA CERTI co simulation framework is driven by Ptolemy This guide does not intent to duplicate the original documentation provided by Ptolemy and CERTI Thus it is highly recommended to consult the Ptolemy and the CERTI websites for their installation process However as we use the CERTI environment in a specific configuration you must be sure to set the correct options to the CMAKE build system for CERTI see subsection 3 for instruction
46. 0 is a standard for distributed discrete event simulations generally used to support analysis engineering and training The approach promotes reusability and interoperability In HLA terminology the entire system to be simulated is represented by a federation which is a collection of federates i e simulation entities performing a sequence of computations Federates are connected via the Run Time Infrastructure RTL the underlying middleware functioning as the simulation kernel Figure 2 1 describes the global architecture ofa HLA simulation HLA Federation is Federate 1 Federate 2 Federate 3 Run Time Infrastructure RTI Figure 2 1 HLA Federation The HLA specification defines 10 1 An interface specification for a set of services required to manage the federates and their interactions For instance it describes how a federate can join or create a federation 2 An object model template based on the OMT standard 11 which provides a common framework for the communication between HLA simulations For each federation a Federation Object Model FOM describes the shared objects interaction classes and their attribute 3 A set of rules describing the responsibilities of federations and the federates An example is the rule that all data exchange among federates shall occur via the RTI Areas Services Description non formal createFederationExecution create a federation joinFederationExecution join a f
47. 1 lun 30 sept 22 32 Gilles LASNIER Q eoo Java EE Eclipse Users gil Work eclipse kepler isae MacOSX 64bits workspace isae w LU HS OrQis PU ENA 2RiG BADIA gt gt Q Quick Access Kl m s8 Java ee Its Project Explorer 23 E SAD gt m BE Outline 23 Task List pia MET y x An outline is not available Go Into Show In KEW gt B Copy C amp Copy Qualified Name Paste sv X Delete Remove from Context Build Path K Z Configure Build Path Refactor XET gt 2 Import 24 Export Refresh FS Close Project Close Unrelated Projects Validate Show in Remote Systems view Profile As K Debug As K Run As gt Team gt i Markers 23 Properties 4 Servers Data Source Explorer Snippets vog Compare With K Derrors 13 285 warnings 2 039 others Filter matched 200 of 15324 items Restore from Local History Description Resource Path Location Type Configure gt amp Java Problems 100 of 13285 items Source b Java Task 100 of 2039 items Properties sel 2 pul Figure B 1 Build path interface of ptlII At this step if you have not configure the JCERTI interface for the ptII java project following the instructions given in section 4 you ll see that the class HlaManager java located in the ptII ptolemy apps hlacerti java package doest no compile see figure B 6 These errors are caused by the dependencies to the JCERTI interface which are
48. 3 Time advancement services a TAR b NER Let us now consider Figure 2 3 b FederateNER also produces the event UAV at time t and asks for a time advance to h in that case with a NER tz The reception of RAV v t is followed by a TAG t FederateNER moves its logical time to r and then can realize a computation with the received value Let us point out that a federate using the NER service is a more reactive federate since it can produce new events from time n In a nutshell if a TAR 2 has been sent the time granted by the TAG service is tg t2 If a NER 2 has been sent the granted time is tg tj with 1 lt t X f In the case of NER if t lt to the current federate have received one or more events from the federation with timestamp t FederateNER RTI UAV V 1 t1 t1 tick RAV V 2 t1 UAV V 1 t1 2 4 CERTI an RTI implementation HLA compliant CERTI is a HLA compliant open source RTI 19 20 More information about CERTI can be found here https savannah nongnu org projects certi 13 Chapter 3 The Ptolemyll project 3 1 Overview of Ptolemy II Ptolemy II 21 4 is an open source modeling and simulation framework for heterogeneous systems Ptolemy models are actor oriented Actors are executable and concurrent components that communicate via ports Actors can be atomic or composite where a composite actor contains an entire model inside but behaves like an atomic a
49. 3 Simulation do 0 OF 6 Federation Ae ri xp hlaStartTime Parameter gt EB ptolemy apps hlacerti demo MultiDataTypes The High Level Architecture HLA 1 2 is a standard for distributed o o hlaTimeStep Parameter gt B ptolemy apps hlacerti demo MultiProducerCor discrete event simulations A complex simulation in HLA is called a HLA o hlaLookAHead Parameter gt EB ptolemy apps hlacerti demo SimpleProducerCt Federation A Federation is a collection of Federates e g simpler simula requireSynchronization Parameter gt B ptolemy apps hlacerti demo SynchronizeToRe tors each performing a sequence of computations interconnected by a Run B o synchronizationPointName Parameter Y GB ptolemy apps hlacerti lib ires Infrastructure RTI isCreator Parameter lt p gt lt p gt a h E el CERTI is an Open Source middleware RTI compliant with HLA NRS09 which B e aithue hange Aiari lt vold Y pe manages every part of federation It also ensures a real time behavior of 19 clone Workspace Object a federation execution CERTI is implemented in C and bindings are A initializeQ void gt LD HlaPtidesEvent java provided as JCERTI for Java and PyHLA for Python For more information see 0 a preinitialize void KUD HlaPublisher java lt br gt lt a href http savannah nongnu org projects certi target top http savanrB EP 4 proposeTime Time Time gt 5 HlaSubscriber java lt p gt l
50. HLA CERTI at the director level and by preserving the MoC semantics 15 3 2 4 Model and director The director is responsible for the progress of the simulation by firing the actors in a specific order In timed actors the model time i e logical time is advanced as part of this process In a hierarchical model only the top level director advances time The rules of time advancement depend of the timed MoC implemented by the director Ptolemy II uses the same model of time for all MoC known as superdense time Superdense time is represented by a pair t n called a timestamp where is a model time and n is a micro step The model time represents the time at which some event occurs and the microstep represents the sequence of events that occur at the same model time The superdense time semantics is defined in 14 and only an overview is given here In the case of a CT director at time rv all actors are fired following a precise order and the next timestamp t 1 is computed by the solver In the case of a DE director an actor is only fired at the timestamp t if either it has an event in one of its input ports or it has explicitly asked to be fired at using the fireAt method To ensure determinism the order in which actors are fired is important The DE director maintains a calendar queue of DE events and a global ordering between these events A DE event is a tuple value timestamp where the timestamp is a superdense time 1 n
51. HLA services are grouped into six management areas which could be related to the federate life cycle Figure 2 2 describes the subset of HLA services used for our approach An informal description of each service role and a user documentation is available The reader is referred to 10 9 for a complete description of all HLA services The services in Figure 2 2 deal with the following areas 1 Federation management also includes a Federa tion Execution Data FED file used by the RTI to manage the whole federation 2 Declaration management i e which objects or object attributes each federate will publish or subscribe to 3 Object management i e the way federates produce attribute updates or receive updated attributes from the federation 4 Time management i e the mechanisms required to implement time management policies and to negotiate time advances 11 2 2 FOM and data management The federation object model is usually specified in a Federeration Execution Data FED file 2 3 Time Management HLA time management services enable deterministic and reproducible distributed simulations Each federate man ages its own logical time and communicates this time to the RTI The RTI ensures correct coordination of federates by advancing time coherently Logical time is roughly equivalent to simulation time in the classical discrete event simulation literature and is used to ensure that federates observe events in the same order 6 Logi
52. I where Vergil is executed or as a parameter of the Ptolemy model or as a parameter of the link HlaManager lt p gt lt pre gt CERTI_HOME absolute path to certi lt pre gt lt p gt Otherwise the current implementation is not able to find the CERTI environment the RTIG binary and to perform its execution See also the link CertiRtig class lt p gt lt p gt NOTE For a correct behavior CERTI has to be compiled with the option CERTI USE NULL PRIME MESSAGE PROTOCOL lt p gt lt b gt References lt b gt lt br gt 1 pt of Defense DoD Specifications High Level Architecture Interface pecification Version 1 3 DOD DMSO HLA IF 1 3 Tech Rep Apr 1998 D S 2 IEEE IEEE standard for modeling and simulation High Level Architecture D HLA IEEE Std 1516 2010 vol 18 pp 1 38 2010 of Defense DoD Specifications High Level Architecture Object Model Template Version 1 3 DOD DMSO OMT 1 3 Tech Rep Feb 1998 4 E Noulard J Y Rousselot and P Siron CERTI an open source RTI why and how Spring Simulation Interoperability Workshop pp 23 27 Mar 2009 author Gilles Lasnier Contributors Patricia Derler Edward A Lee version Id HlaManager java 429 2013 09 09 23 23 25Z g lasnier since Ptolemy II 10 0 Pt ProposedRating Yellow glasnier Pt AcceptedRating Red glasnier public class HlaManager extends AbstractInitializableAttribute implements TimeRegula
53. Institute for Space and Aeronautics Engineering ISAE SUPAERO RTRA STAE Foundation POSTDOCTORAL RESEARCH REPORT Advisor Janette Cardoso ISAE DMIA Co Advisor Claire Pagetti ONERA DTIM Scientific referent Pierre Siron ONERA DTIM amp ISAE DMIA Toward a Distributed and Deterministic Framework to Design Cyber PhysicalSystems Gilles LASNIER Institute for Space and Aeronautics Engineering ISAE DMIA 10 avenue douard Belin BP 54032 31055 Toulouse Cedex 4 Toulouse France October 2013 Contents Introduction Context AS A TT 1 2 Contribution a A ta de wea A le AA A mde eed 1 3 Related Work cunda a A Wan EGE a ferie R ats The High Level Architecture Standard and the CERTI framework 2 1 Overview O HLA n ee rl e Be ee e A dl hie e es 2 0 FOM and data management 2 3 Time Management lr 9 ka tender eoe BE e karten ee ar dera E 2 3 Federate stime policies r dirt iles qo a vep ge gebe s m E 2 3 2 Ime progress 4 s p borse equo que ds UR PSI e p er ved d Ung dele qus ga 2 4 CERTI an RTI implementation HLA compliant en The Ptolemyll project 3 1 Overview of Ptolemy IL es 52 54 zoe parta Xo G4 wee 3 Rm duce pacem pare eu A 3 2 Ptolemy sentities semantics ns 3 2 O a ook oe Iur ee mot see RU a ato amodo EOS peu dee e d 3 2 2 Attrib te isnt e sa de Pedo dA T docu NR dre ai dot depo m deiade pad ark s 3 2 3 Decorators uos dope dub eh m Rogo Y doge ek et ded Mo Mew boda ok ia 3 2 4 Model
54. Java etc and hardware equipments The key benefits of HLA are interoperability and reuse Our experiments and framework have been developed upon the HLA compliant Open Source RTI named CERTI 19 20 The co simulation environment described here enable a Ptolemy simulation model to be executed as federate in a HLA federation A Ptolemy federate exchange data with other federates that can be other Ptolemy simulations i e only for a distributed purpose or even C or Java federates i e for heterogenous aspects The choosen strategy to enable the co simulation is to provide a methodology to ease the development of ptolemy federate model by the user that could be directly integrated in a HLA federation Main complexities such as time management data communication and simulation execution all discussed in this report are handled at the framework level Therefore a strong HLA expertise is not required for the user According to this strategy and in order to facilitate the interaction between HLA and Ptolemy we extend Ptolemy with dedicated components that enable the connection to HLA the data exchange and which automatize the exe cution of a HLA Federation The HlaManager centrally manages the advancement of time in HLA and Ptolemy Two Ptolemy actors an HlaPublisher and an HlaSubscriber are in charge of the data communication Combining these two frameworks allows experimenting with heterogeneity provided by Ptolemy i e the possibility to m
55. Name federationName new Parameter this federationName federationName setDisplayName Federation s name federationName setTypeEquals BaseType STRING federationName setExpression HLAFederation attributeChanged federationName fedFile new FileParameter this fedFile fedFile setDisplayName Federate Object Model fed file path new Parameter fedFile allowFiles BooleanToken TRUE new Parameter fedFile allowDirectories BooleanToken FALSE fedFile setExpression CWD HLAFederation fed HLA Time management parameters useNextEventRequest new Parameter this useNextEventRequest useNextEventRequest setTypeEquals BaseType BOOLEAN useNextEventRequest setExpression true useNextEventRequest setDisplayName useNextEventRequest NER attributeChanged useNextEventRequest useTimeAdvancedRequest new Parameter this useTimeAdvancedRequest useTimeAdvancedRequest setTypeEquals BaseType BOOLEAN useTimeAdvancedRequest setExpression false useTimeAdvancedRequest setDisplayName useTimeAdvancedRequest TAR attributeChanged useTimeAdvancedRequest isTimeConstrained new Parameter this isTimeConstrained isTimeConstrained setTypeEquals BaseType BOOLEAN isTimeConstrained setExpression true isTimeConstrained setDisplayName isTimeConstrained attributeChanged isTimeConstrained isTimeRegulator new Parameter this isTimeRegula
56. RIGHT VERSION 2 COPYRIGHTENDKEY package ptolemy actor import ptolemy actor util Time import ptolemy kernel util IllegalActionException LLLI LIATIA AALALA LAAI ALCL TimeRegulator This interface is implemented by attributes that wish to be consulted when a director advances time In particular the director will call the one method in this interface passing it a proposed time to advance to and the method will return either the same proposed time or a smaller time The method may not return immediately For example it might wait for real time to advance to the proposed time and then simply return the proposed time author Edward A Lee Gilles Lasnier Patricia Derler 60 version Id TimeRegulator java 422 2013 09 05 13 43 092 g lasnier since Ptolemy II 10 0 Pt ProposedRating Yellow eal Pt AcceptedRating Red cxh xy public interface TimeRegulator LM MEME B GgMM M PL MM P P T ETA P Gg UL P Cg OLPC AAA AAA TTT public methods Propose a time to advance to param proposedTime The proposed time return The proposed time or a smaller time exception IllegalActionException If the time regulator is being misused public Time proposeTime Time proposedTime throws IllegalActionException Listing C 2 ptolemy apps hlacerti lib HlaPublisher java This actor implements a publisher in a HLA CERTI federation package ptolemy apps hlacerti lib import
57. a certi build certi Run the command remark put the whole command in a unique line 49 cmake DCMAKE INSTALL PREFIX HOME pthla certi tools DCERTI USE NULL PRIME MESSAGE PROTOCOL ON 8 Run make 9 Run make install The command executes in step 7 enables the use of the NULL PRIME MESSAGE PROTOCOL algorithm in CERTI for the time management services After the step 9 CERTI has been compiled and installed in the HOME pthla certi tools folder CERTI provides a script to set the environment global variables binaries etc to allow the correct launch of RTIG process RTIA process and federates To set the CERTI environment properly in a terminal run the command source SHOME pthla certi tools share scripts myCERTI_env sh 3 3 Deployment and execution For the deployment and the exeuction of an HLA simulation in C you need one terminal to launch the rtig process and one terminal per federate if you need to display outputs To execute the rtig do this procedure 1 Open a new terminal 2 Source the CERTI environment script source SHOME pthla certi tools share scripts myCERTI env sh 3 Run rtig for the RTI For testing the execution of a federate you can run the demo Billard from CERTI Make sure you executed myCERTI env sh Check if your SCERTI HOME is SHOME pthla certi tools Open a new terminal source the CERTI environment sc
58. all federates of your distributed simulation Remark only the last federate to be launched must have the field Is synchronization point creator ticked 000 Rename HlaPublisher eoo Edit parameters for HlaPublisher aus vall E Display name HlaPublisher Object class in FOM myObjectClass M use HLA PTIDES event use CERTI message buffer Cancel Help Preferences Defaults Remove Add Commit a Renaming with attribute b Naming the object class in HlaPublisher eoo Edit parameters for la Mara c Federate s name producer Tm cobdmalot ion k Federation s name prodCons e E Federation prodCons Federate Object Model fed file path Cosimu fed Browse _ Configure Fedversion v1 3 event based federate M Federate prodcons Public 7 Federate consumer Public time stepped federate Federate producer Public isTimeConstrained nee isTimeRegulator Class ObjectRoot logical start time in ms 0 0 Attribute privilegeToDelete reliable timestamp time step in ms 0 0 Class RTIprivate lookahead in ms 0 1 Class myObjectClass Require synchronization M Attribute val RELIABLE TIMESTAMP Sch m Attribute vall RELIABLE TIMESTAMP A EO ie Simulating Attribute val2 RELIABLE TIMESTAMP isyuchmuization point creator Interactions Class InteractionRoot BEST_EFFORT RECEIVE Cancel Help Preferences Defaults Remove Add Commit Class RTIprivate BEST EFFORT RECEIVE
59. approach targets distributed realtime and embedded systems simulation where memory are limited resources and data needs to be as simple as possible The provided API is enough to match data types between Ptolemy and HLA CERTI The data wrapper service implements two methods encodeHlaValue to encode a data to send to the federation and _decodeHlaValue to decode a data received from the federation to introduce in Ptolemy These methods are detailed below Encode data to HLA CERTI The encodeHlaValue converts a Ptolemy token as a HLA attribute value ac cording to its type specification encodingHelpers are used to ensure the correct wrapping of a token in a data representation recognizable and handled by HLA CERTI federates The Ptolemy type specification mecanism us ing the Ptolemy inference type mecanism is used here with a HlaPublisher actor that is mapped to a HLA attribute value Most of the time the user does not to set the type of the input port of a HlaPublisher thanks to the type inference mecanism provided by Ptolemy Decode data from HLA CERTI The decodeHlaValue converts a HLA attribute value in a Ptolemy token To be able to detect the correct data representation of a HLA attribute value in a Ptolemy a user specification is required here The user needs to set the type of the output port of the HlaSubscriber actor mapped to a HLA attribute value This information allows to to retrieve the correct type of the token to produce T
60. architecture hla federate interface specification Technical report IEEE Sept 2000 P Derler E A Lee and A Sangiovanni Vincentelli Modeling cyber physical systems Proceedings of the IEEE special issue on CPS 100 13 28 Jan 2012 J Eker J Janneck E A Lee J Liu X Liu J Ludvig S Sachs Y Xiong and S Neuendorffer Taming heterogeneity the Ptolemy approach Proceedings of the IEEE 91 1 127 144 2003 ForwardSim Inc Simulation and Technologies HLA Toolbox for MATLAB HLA Blockset for Simulink 2013 R M Fujimoto HLA time management Design document Technical report Georgia Tech College of Computing Aug 1996 Lasnier Gilles Toward a Distributed and Deterministic Framework to Design Cyber PhysicalSystems Tech nical report Institut Superieur de l Aeronautique et de l Espace ISAE Oct 2013 Hassen Hadj Amor and Thierry Soriano A contribution for virtual prototyping of mechatronic systems based on real time distributed high level architecture Journal of computing and information science in engineering 12 1 2012 IEEE IEEE Standard for Modeling and Simulation High Level Architecture HLA Federate Interface Specification IEEE Std 1516 1 TM 2010 pages 1 378 2010 IEEE IEEE Standard for Modeling and Simulation High Level Architecture HLA Framework and Rules IEEE Std 1516TM 2010 pages 1 38 2010 IEEE IEEE Standard for Modeling and Simulation High Level Architecture
61. arent Check if the user as set the object class of the HLA attribute to subscribe to param attribute The attribute that changed exception IllegalActionException If the object class parameter is empty public void attributeChanged Attribute attribute throws IllegalActionException if attribute classObjectHandle String value StringToken classObjectHandle getToken StringValue if value compareTo 0 throw new IllegalActionException this Cannot have empty name else if attribute asHLAPtidesEvent _asHLAPtidesEvent BooleanToken asHLAPtidesEvent getToken booleanValue super attributeChanged attribute Clone the actor into the specified workspace param workspace The workspace for the new object return A new actor exception CloneNotSupportedException If a derived class contains an attribute that cannot be cloned xf public Object clone Workspace workspace throws CloneNotSupportedException 62 HlaPublisher newObject HlaPublisher super clone workspace newObject hlaManager hlaManager return newObject Retrieve and check if there is one and only one link HlaManager deployed in the Ptolemy model The link HlaManager provides the method to publish an updated value of a HLA attribute to the HLA CERTI Federation exception IllegalActionException If there is zero or more than one link HlaManager per
62. assHandle new HashMap lt Integer Integer gt newObject rtia null newObject federateAmbassador null newObject federateName federateName newObject federationName federationName newObject isTimeConstrained isTimeConstrained 71 af newObject _isTimeRegulator _isTimeRegulator try newObject hlaStartTime DoubleToken hlaStartTime getToken doubleValue newObject hlaTimeStep DoubleToken hlaTimeStep getToken doubleValue newObject hlaLookAHead DoubleToken hlaLookAHead getToken doubleValue catch IllegalActionException ex CloneNotSupportedException ex2 new CloneNotSupportedException Failed to get a token ex2 initCause ex throw ex2 newObject requireSynchronization requireSynchronization newObject synchronizationPointName synchronizationPointName newObject isCreator isCreator newObject useNextEventRequest useNextEventRequest newObject useTimeAdvancedRequest useTimeAdvancedRequest return newObject Initializes the link HlaManager attribute This method calls the _populateHlaAttributeTables to initialize HLA attributes to publish or subscribe to instantiates and initializes the link RTIambassador and link FederateAmbassador which handle the communication Federate lt gt RTIA lt gt RTIG RTIA and RTIG are both external communicant processes see JCERTI create the HLA CERTI Federation if
63. ation Name of the synchronization point to create or to reach private String synchronizationPointName Indicates if the Ptolemy Federate is the creator point private Boolean _isCreator of the synchronization Records the last proposed time to avoid multiple HLA time advancement requests at the same time Kf private Time lastProposedTime A reference to the enclosing director private DEDirector director The RTIG subprocess private CertiRtig _certiRtig T EEE PA E EAA LET ER A A TAT AAA dE inner class 111 This class extends the link NullFederateAmbassador class which implements the basics HLA services provided by the JCERTI bindings author Gilles Lasnier A private class PtolemyFederateAmbassadorInner extends NullFederateAmbassador J public variables Indicates if the Federate is declared as time regulator in the HLA CERTI Federation This value is set by callback by the RTI x public Boolean timeRegulator Indicates if the Federate is declared as time constrained in the HLA CERTI Federation This value is set by callback by the RTI Xi public Boolean timeConstrained 90 Indicates if the Federate has received the time advance grant from the HLA CERTI Federation This value is set by callback by the RTI k public Boolean timeAdvanceGrant Indicates the current HLA logical time of the Federate This value
64. ation execution no fail canDestroyRtig true Terminate RTIG subprocess if certiRtig null certiRtig terminateProcess if _debugging _debug this getDisplayName wrapup T Destroy RTIG process 84 Clean HLA attribute tables _hlaAttributesToPublish clear _hlaAttributesSubscribedTo clear _fromFederationEvents clear _objectldToClassHandle clear E AAA AAA AAA AAA AAA AAA AAA AAA AAA TTT 1111 protected variables 1111 Table of HLA attributes and their HLA information that are published by the current link HlaManager to the HLA CERTI Federation This table is indexed by the link HlaPublisher actors present in the model X protected HashMap lt String Object gt _hlaAttributesToPublish Table of HLA attributes and their HLA information that the current link HlaManager is subscribed to This table is indexed by the link HlaSubscriber actors present in the model protected HashMap lt String Object gt _hlaAttributesSubscribedTo List of events received from the HLA CERTI Federation and indexed by the link HlaSubscriber actors present in the model ay protected HashMap lt String LinkedList lt TimedEvent gt gt _fromFederationEvents Table of object class handles associate to object ids received by discoverObjectInstance and reflectAttributesValues services e g from the RTI protected HashMap lt Inte
65. bers put Event event toString in hs getDisplayName elt getValue remove event HUM MB MIEL BG BG GM LT E T Go illl T LL P P P AAA AAA AAA FILA private variables Name of the current Ptolemy federate link HlaManager private String _federateName Name of the HLA CERTI federation to create or to join private String _federationName RTI Ambassador for the Ptolemy Federate private CertiRtiAmbassador _rtia Federate Ambassador for the Ptolemy Federate private PtolemyFederateAmbassadorInner _federateAmbassador 89 priva priva priva ndicates t te Boolean ndicates t te Boolean ndicates t te Boolean ndicates t he use of t _useNextEv he use of t _useTimeAd he use of t _isTimeCon he use of t enc Request strained he nextEventRequest he timeAdvanceRequest vancedRequest service he enableTimeConstrained he enableTimeRegulation service service service private Boolean isTimeRegulator Start time of the Ptolemy Federate HLA logical clock private Double _hlaStartTime Time step of the Ptolemy Federate private Double _hlaTimeStep The lookahead value of the Ptolemy Federate private Double _hlaLookAHead Indicates 1f the Ptolemy Federate will use a synchronization point private Boolean _requireSynchroniz
66. cal time is not necessarily mapped to real time 2 3 1 Federate s time policies HLA time policies describe the involvement of each federate in the progress of time It may be necessary to map the progress of one federate to the progress of another A regulating federate participates actively in the decisions for the progress of time A constrained federate follows the time progress imposed by other federates A combination of both policies is possible As our approach deals with the synchronization of logical time from different simulation tools only regulating and constrained federates are allowed To properly handle time progress and ensure causality HLA defines Time Stamp Ordered TSO events which are supposed to occur at specific points in time Regulating federates generate TSO events possibly out of time stamp order that must occur no earlier than the current local time plus the lookahead The lookahead acts as a contract value which guarantees that the federate will not produce a TSO event earlier than its current local time plus lookahead The RTI handles the ordering of the TSO events generated by the federation Each federate implements a priority time stamp queue for TSO events Events stored in the ordered queue are only delivered to the federate in a time advancement phase if their timestamps are between the current and the next federate local time the granted time see later 2 3 2 Time progress Time advancement requests by
67. ccessAttempted Wait federation synchronization while PtolemyFederateAmbassadorInner federateAmbassador inPause if debugging _debug this getDisplayNanme initialize Waiting for simulation phase try CertiRtiAmbassador rtia tick2 catch SpecifiedSaveLabelDoesNotExist e throw new IllegalActionException this e SpecifiedSaveLabelDoesNotExist catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch RTIinternalError e throw new IllegalActionException this e RTIinternalError End block for synchronization point GL FIXME need to test deeper then remove this call tick one time to avoid missing callbacks before the start of the simulation try CertiRtiAmbassador rtia tick catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch RTIinternalError e throw new IllegalActionException this e RTlinternalError T Launch the HLA CERTI RTIG process as subprocess The RTIG has to be launched before the initialization of a Federate NOTE if another HlaManager e g Federate has already launched a RTIG the subprocess creates here is no longer required then we destroy it exception IllegalActionException If the initialization of the CertiRtig or the execution of the RTIG as subprocess has fai
68. ception IllegalActionException If the entity cannot be contained by the proposed container exception NameDuplicationException If the container already has an actor with this name xf public HlaPublisher CompositeEntity container String name throws NameDuplicationException IllegalActionException 61 super container name The single output port of the actor input new TypedIOPort this input true false classObjectHandle new Parameter this classObjectHandle classObjectHandle setDisplayName Object class in FOM classObjectHandle setTypeEquals BaseType STRING classObjectHandle setExpression myObjectClass attributeChanged classObjectHandle asHLAPtidesEvent new Parameter this asHLAPtidesEvent asHLAPtidesEvent setTypeEquals BaseType BOOLEAN asHLAPtidesEvent setExpression false asHLAPtidesEvent setDisplayName asHLAPtidesEvent 2 attributeChanged asHLAPtidesEvent _hlaManager null _asHLAPtidesEvent false AAA AAA AAA AAA AAA AAA AAA AAA UU IE P P AAT TT CMM Tg gg 0 MI 4 public variables LLIS The object class of the HLA attribute to publish public Parameter classObjectHandle Indicate if the event is for a Ptides platform public Parameter asHLAPtidesEvent The input port public TypedIOPort input null F M AAA AAA AAA AAA AAA AAA AAA AAA AAA TAA TT 1111 public methods 111 Call the attributeChanged method of the p
69. ctor Therefore modeling Ptolemy time stepped federate behavior is less flexible than event based federates and re quired specific knowledges of the HLA standard 35 5 3 6 FederateAmbassador The Federate Ambassador service contains the implementation of the callbacks required by a Ptolemy federate These callbacks defines a subset of HLA callback services proposed by the HLA standard The table 5 3 resumes the callbacks supported by a Ptolemy federate HLA Areas HLA callback services Description non formal synchronizationPointRegisterSucceeded register synchro point succeeded Federation announceSynchronizationPoint wait a synchronization point federationSynchronized announce synchronization Object discoverObjectInstance for object instances discovering reflectAttributeValues RAV receive updated value timeRegulationEnabled federate as regulator succeeded Time timeConstrainedEnabled federate as contrained succeeded timeAdvanceGrant TAG notify time advancement granted Figure 5 3 HLA CERTI callbacks implemented in the FederateAmbassador serivce Particularly the reflectAttribute Values RAV callback is the one responsible to the conversion of a HLA event to Ptolemy event DE Event token It uses the data wrapper service and the Ptolemy framework The code of this method is given in the listing C 3 Appendix C 5 3 7 UAV and updateHlaAttribute The UAV service is responsible for se
70. ctor to the outside A special model component the director describes the semantics of a model Ptolemy supports a wide variety of models of computations including discrete event DE continuous time CT synchronous reactive SR or synchronous data flow SDF The operational rules for executing a model are given by the MoC defining the meaning of execution concurrency and communication These rules determine when actors perform internal computation update their internal state and perform external communication Models in different MoCs can be composed hierarchically with a clearly defined semantics DE Director PilotStick AutoPilotDE ElevCom eTs 0 1 esamplePeriod Ts 10 Figure 3 1 A hierarchical Ptolemy model of a CPS The ability to model heterogeneous systems in Ptolemy is interesting for CPS design as those typically comprise heterogeneous components expressed naturally in different MoCs An example of a hierarchical Ptolemy model of a CPS based on the F 14 Longitudinal Flight Control demo model from Matlab is shown in Figure 3 1 Aircraft and Stick are composite actors modeled in the continuous MoC and the AutoPilot composite actor controller contains is a DE system The top level director is also a DE director Heterogeneous composition of different MoCs sometimes requires special actors For instance signals in the continuous domain need to be sampled in order to be used in the DE domain In Ptolemy a Sampler acto
71. cture of the Federation HLA version name of Federates which belong to shared HLA attributes and the interaction between Federates and shared attributes Data exchanged in a HLA Federation are called HLA attributes and their interaction mechanism is based on the publish subscribe paradigm The FOM is specified in a fed file used by the RTI e g by the RTIG process when using CERTI More information in 3 lt br gt lt a href http savannah nongnu org projects certi target _top gt http savannah nongnu org projects certi lt a gt lt br gt lt p gt lt p gt To enable a Ptolemy model as a Federate the link HlaManager has to be deployed and configured by double clicking on the attribute Parameters lt i gt federateName lt i gt lt i gt federationName lt i gt have to match the declaration in the FOM fed file lt i gt fedFile lt i gt specifies the FOM file and its path lt p gt lt p gt Parameters lt i gt useNextEventRequest lt i gt lt i gt UseTimeAdvanceRequest lt i gt lt i gt isTimeConstrained lt i gt and lt i gt isTimeRegulator lt i gt are used to configure the HLA time management services of the Federate A Federate can only specify the use of the lt i gt nextEventRequest service lt i gt or the lt i gt timeAdvanceRequest lt i gt service at a time lt i gt istimeConstrained lt i gt is used to specify time constrained Federate and lt i gt istimeRegulator lt i gt to specify tim
72. d Multiple 3 ptolemy apps actorsTutorial09 7 3 ptolemy apps classic 35 ptolemy apps eclipse 5 ptolemy apps graph 5 ptolemy apps hardrealtime Vu E O errors o t I d Do te Description Resource Path Location Type gt amp Java Problems 100 of 13285 items br Java Task 100 of 2039 items Figure B 5 Inclusion and Exclusion Patterns frame of ot 56 Its Project Explorer 33 7D g HlaManager java X CB Ez Outline X El Task List 20 gt 8 ptolemy actor test amp This attribute implements a HLA Manager to cooperate with a HLA CERTI Federation B a wewew Y gt amp i ptolemy actor test junit HB ptolemy apps hlacerti lib gt i ptolemy actor util package ptolemy apps hlacerti lib a M HlaManager Hi esca import 00 zP HlaManager CompositeEntity String gt amp i ptolemy actor util test junit o federateName Parameter gt EB ptolemy apps HMM MM AA ARA M M Gg 9 federationName Parameter gt B ptolemy apps hlacerti MlaManager B o fedFile FileParameter diesen biis mane PA useNextEventRequest Parameter lemy apps hlacerti demo CoSimulation e c dior cedida li a lt p gt This attribute implements a HLA Manager which allows a Ptolemy model to L ageri saine gt ES ptolemy apps hlacerti demo CoSimulationFunt cooperate with a HLA CERTI Federation The main is to allow a Ptolemy B gm ian me gt B ptolemy apps hlacerti demo CoSimulationNety
73. dMicrostep IntToken rt get microstep intValue SourceTimestamp DoubleToken rt get sourceTimestamp doubleValue t rt get payload else t c tok 86 BaseType type BaseType t getType if type equals BaseType BOOLEAN encodedValue EncodingHelpers encodeBoolean BooleanToken t booleanValue else if type equals BaseType UNSIGNED BYTE TODO Auto generated catch block encodedValue EncodingHelpers encodeByte UnsignedByteToken t byteValue else if type equals BaseType DOUBLE GL FIXME XXX This code only work with SDSE PRISE joystick federate BooleanToken isCreator getToken booleanValue boolean useMessageBuffer false if useMessageBuffer ByteArrayOutputStream bos new ByteArrayOutputStream MessageBuffer mb new MessageBuffer null bos mb write DoubleToken t doubleValue try mb send catch IOException el el printStackTrace encodedValue bos toByteArray else encodedValue EncodingHelpers encodeDouble DoubleToken t doubleValue else if type equals BaseType FLOAT encodedValue EncodingHelpers encodeFloat FloatToken t floatValue else if type equals BaseType INT encodedValue EncodingHelpers encodeInt IntToken t intValue else if type equals BaseType LONG encodedValue EncodingHelpers encodeLong LongToken t longVa
74. ds to the call of the updateAt tribute Values UAV service by the HlaManager with value v and time t The JCERTI API is used to build a correct representation of the timestamp t 40 5 5 2 Interaction with Elasubscriber Figure 5 4 b describes the execution flow to introduce a new update of a HLA attribute received from the HLA CERTI Federation This interaction involves the director the HlaSubscriber actor the HlaManager attribute and the RTI The HlaSubscriber contains a queue and provides the putReflectedAttribute method to the HlaManager to store every updated value in it When a Federate uses the HLA Time management the reception of these values e g reception of the reflectedAttributeValues RAV callbacks from the RTI is only possible during a time advancement phase through the call to the HLA tick see Figure 5 4 b At the end of this phase each RAV received by the HlaManager is stored as a Ptolemy event in a HlaSubscriber The manager is able to retrieve the corresponding HlaSubscriber and to invoke its putReflectedHlaAttribute The value of the event is the updated value and its timestamp is the HLA logical time specified by the RAV The treatment of the RAV is handled in the proposeTime method During the execution of the putReflectedHlaAttribute a call to the fireAt method is performed to program the next firing time of the HlaSubscriber i e the time when the director have to call its fire method This en
75. e String value StringToken federateName getToken 1 1 StringValue if value compareTo 0 throw new IllegalActionException this Cannot have empty name _federateName value setDisplayName value else if attribute federationName String value StringToken federationName getToken StringValue if value compareTo 0 throw new IllegalActionException this Cannot have empty name _federationName value else if attribute useNextEventRequest _useNextEventRequest BooleanToken useNextEventRequest getToken booleanValue else if attribute useTimeAdvancedRequest _useTimeAdvancedRequest BooleanToken useTimeAdvancedRequest getToken booleanValue else if attribute isTimeConstrained _isTimeConstrained BooleanToken isTimeConstrained getToken booleanValue else if attribute isTimeRegulator 70 Xy _isTimeRegulator BooleanToken isTimeRegulator getToken booleanValue else if attribute hlaStartTime Double value DoubleToken hlaStartTime getToken doubleValue if value lt 0 throw new IllegalActionException this Cannot have negative value _hlaStartTime value else if attribute hlaTimeStep Double value DoubleToken hlaTimeStep getToken doubleValue if value lt 0 throw new IllegalActionException this Cannot have negative value
76. e regulator Federate The combination of both parameters is possible and is recommended lt p gt lt p gt Parameters lt i gt hlaStartTime lt i gt lt i gt hlaStepTime lt i gt and lt i gt hlaLookAHead lt i gt are used to specify Hla Timing attributes of a Federate lt p gt lt p gt Parameters lt i gt requireSynchronization lt i gt lt i gt synchronizationPointName lt i gt and lt i gt isCreatorSyncPt lt i gt are used to configure HLA synchronization point This mechanism is usually used to synchronize the Federates during their initialization to avoid that Federates that only consume some HLA 66 E attributes finished their simulation before the other federates have started lt i gt isCreatorSyncPt lt i gt indicates if the Federate is the creator of the synchronization Only one Federate can create the named synchronization point for the whole HLA Federation lt p gt lt p gt link HlaPublisher and link HlaSubscriber actors are used to respectively publish and subscribe to HLA attributes The name of those actors and their lt i gt classObjectHandle lt i gt parameter have to match the identifier of the shared HLA attributes and their object class that they belong to specified in the FOM fed file lt p gt lt p gt For a correct execution the lt i gt CERTI_HOME lt i gt environment variable has to be set It could be set in the shell by running one of the scripts provided by CERT
77. e the current tag with the event tag Time currentTime int depth 0 try synchronized _eventQueue lastFoundEvent _eventQueue get currentTime consultTimeRegulators lastFoundEvent timeStamp n 27 5 2 2 proposeTime method Each attribute that implements a TimeRegulator interface needs to provide an unique public method with the signature proposeTime Time proposedTime This method implements the user time advancement algorithm The only user restriction to take care 1s Restriction 1 The time value returned by a call to proposeTime must be greater or equal to the director s current Time This constraint allows in most of the cases to preserve the semantics of the director s MoC The proposeTime method has a parameter proposedTime which indicates the time the director wants to advance to The semantic of this parameter is defined by the MoC of the director For example in the case of the DE director the proposedTime is the timestamp of the next DE event to be consumed from its calendar queue As this method is always executed at the director level during its execution no actor involved in the simulation model is fired This important property prevents that any event may be produced during a time advancement phase Assuming the correct implementation of the proposeTime method by the user this guarantees the preservation of the time advancement semantics of a particular MoC in Ptolemy An example of time
78. eOwnsAttributes e throw new IllegalActionException this e FederateOwnsAttributes catch FederateNotExecutionMember e hrow new IllegalActionException this e FederateNotExecutionMember catch InvalidResignAction e throw new IllegalActionException this e InvalidResignAction catch RTIinternalError e throw new IllegalActionException this e RTlinternalError catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted if _debugging _debug this getDisplayName wrapup Resign Federation execution boolean canDestroyRtig false while canDestroyRtig Destroy federation execution nofail try _rtia destroyFederationExecution _federationName catch FederatesCurrentlyJoined e if debugging _debug this getDisplayName wrapup WARNING FederatesCurrentlyJoined catch FederationExecutionDoesNotExist e GL FIXME This should be an IllegalActionExeception if debugging _debug this getDisplayNanme wrapup WARNING FederationExecutionDoesNotExist canDestroyRtig true catch RTIinternalError e throw new IllegalActionException this e RTIinternalError catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted if _debugging debug this getDisplayName wrapup Destroy Feder
79. eady installed Ptolemyll and configure the Vergil application in your Eclipse The following instructions maybe used to set a shortcut to launch a Ptolemy model a xml file directly from Eclipse Open Eclipse Right click on the ptII java project Select Run As gt Run Configurations In the new frame open in the right part select Java Application Right click on vergil then select Duplicate Now click on vergil 1 In the left part rename vergil 1 as vergil with file Cick on the Arguments tab Under the Program arguments block click on Variables 10 Select selected resource loc and click on Ok 11 Click on Close and save the new configuration WO 0 3 Ov OF CO PO RP After the step 11 you can now directly launch a Ptolemy model from the Eclipse explorer To do so click on the name of your model a xml file then select the configuration vergil with file A Vergil editor will be launched and the selected model will be opened directly This could be very helpful to save time in development or test phases 6 Compile the PtolemyII HLA CERTI co simulation framework with Ptolemy This section presents how to enable the PtolemylI HLA CERTI co simulation framework in the Ptolemy java project in Eclipse We assume that you have already succeeded the instructions given in sections 3 4 and 5 relative to the installation of the CERTI environment the JCERTI interface and the Ptolem
80. ecify the plant dynamics and the control Thus from the specification it is possible to simulate the behaviour and verify the robustness and stability of the functions by observing the functional traces This step occurs early in the development process The control functions are then translated into low level code automatically or manually that is then executed on the target architecture e g a distributed platform composed of several computing nodes connected with a real time operating system Analysis of the execution on the target occurs very late in the development process It is then of great importance to provide methods and tools to give ways to analyze at least partially and as early as possible the behaviors of the future implementation taking into account for instance the mapping on the target or the interaction with some physical devices e g sensors and actuators The process of integrating components and evaluating their interaction with the target architecture requires knowl edge of several domains e g hardware software that are typically described in heterogeneous models e g con tinuous models discrete models timed properties Analyzing worst case execution times is insufficient in order to validate the system Formal analysis cannot usually handle systems of that complexity As a result simulations are performed to analyze the functional behaviour of high level specifications mixed with more low level elements Imagine
81. ed federate 3 connect a Ptolemy federate model to a federation 4 publish or subscribe to a HLA attribute values specified by the HLA actors deployed in the Ptolemy model 5 synchonize the start of the Ptolemy federate execution according to other federates 28 10 11 12 launch a federation rtig and rtia processes quit and destroy properly a federation convert a Ptolemy token as HLA event data timestamp convert a HLA event data timestamp as Ptolemy token token DE Event send an UAV to the federation get a RAV from the federation manage and normalize event timestamp from both simulators according to the time management algorithm proposed in 4 5 3 1 Architecture The architecture of the HlaManager attribute is described in figure 5 1 5 services are defined All services im plement one or several methods to realize one or several operations The Initialization service refers to op erations 1 to 6 The Wrapup service refers to operation 7 The Data wrapper service refers to operations 8 and 9 The UAV service refers to operation 10 The Time management service refers to operations 11 and 12 Finally the FederateAmbassador service is a particular service that refers to all operations According to the CERTI ar chitecture all information from the RTI are delivered to the federate with the use of a standardized HLA services implemented as callbacks The FederateAmbassador service implements all the callback
82. edTag LogicalTime theTime EventRetractionHandle retractionHandle throws ObjectNotKnown AttributeNotKnown FederateOwnsAttributes InvalidFederationTime FederateInternalError try for int i 0 i lt theAttributes size itt Iterator lt Entry lt String Object gt gt ot _hlaAttributesSubscribedTo entrySet iterator while ot hasNext Map Entry lt String Object gt elt Map Entry ot next Object tObj 0Object elt getValue Time ts null TimedEvent te null Get the object class handle corresponding to received theObject id int classHandle objectIdToClassHandle get theObject The tuple attributeHandle classHandle allows to identify the the object attribute i e the HlaSubscriber where the updated value has to be stored if theAttributes getAttributeHandle i Integer t0b3 4 amp amp Integer tObj 3 classHandle try GL FIXME PTIDES This first case handle events from a PtidesPlatform to PtidesPlatform only network port are supported if tObj 1 instanceof RecordType HlaPtidesEvent he new HlaPtidesEvent 95 theAttributes getValue i GL FIXME PTIDES shoul ts new Time _director ts new Time _director CertiLogicalTime getTime new TimedEvent ts new RecordType tObj l _decodeHlaValue RecordType he getValue GL FIXM he getLo ts getDoubl he getMicro GL FIXM he getSourc
83. ederation resignFederationExecution quit a federation Federation destroyFederationExecution destroy a federation registerFederationSynchronizationPoint register a synchronization point synchronizationPointRegisterSucceeded x announceSynchronizationPoint synchronizationPointAchieved register synchro point succeeded wait a synchronization point release from a synchro point federationSynchronized x announce synchronization tick allow to get callbacks from RTI publishObjectClass declare publication of a class ias subscribeObjectClassAttributes subscribe to a class unsubscribeObjectClass unsubcribe to a class unpublishObjectClass unpublish a class registerObjectInstance register an object instance Object discoverObjectInstance for object instances discovering updateAttributeValues UAV send amp update value reflectAttribute Values RAV x receive updated value enableTimeRegulation declare federate is regulator timeRegulationEnabled x federate as regulator succeeded enable TimeConstrained declare federate constrained Time timeConstrainedEnabled x federate as contrained succeeded ask to advance federate s time notify time advancement granted ask to advance federate s time timeAdvanceRequest TAR timeAdvanceGrant TAG x nextEventRequest NER Figure 2 2 HLA services with a x are sent from RTI to Federates callbacks all other services are from Federates to RTI
84. eived from the federation that is not a CERTI Message Buffer then the exception RTIinternalError hla rti RTlinternalError serial 0 is raised and caught by Vergil see figure B 12 To resolve this problem the modeler needs to check the option selected using the HLA actor interface 55 QOO R Ss Or Qe ds D Q Quick Access LED Bune 8 E Task List B outline is not available te i A Project Explorer 2 v Come filter text P Resource Fen 3 Builders Java Build Path b Java Code Style b Java Compiler b Java Editor Javadoc Location Project Facets Project Referen Run Debug Server P Task Repository Task Tags gt Validation WikiText O Ex Jr m 0 errors 13 285 warnings 2 039 others Filter matched 200 of 15324 items Description Resource Path Location Type gt amp Java Problems 100 of 13285 items br Java Task 100 of 2039 items Figure B 4 Exclusion Pattern Sellection frame of ptIP Inclusion and Exclusion Patterns Add or remove inclusion and exclusion patterns to source folder Project Explorer 23 S 7 Outline X El Task List B gt Resource r gt pul 3 Builders Inclusion patterns outline is not available Task Tags Exclusion patterns gt Validation FO Op WikiText 2 ptolemy actor lib reactable 5 ptolemy actor lib x10 er nare Ad
85. enhance performance as weel as to design distributed models that we claim more close to the distributed architecture of the CPS Our framework is qualified as co simulation framework according to the following definition Definition 1 Co simulation Co simulation or co operation means a simulation methodology that allows individ ual components to be simulated by different simulators running simultaneously and exchanging data in a coordinate manner In this report all references to co simulation or co operation will refer to the definition 1 Our co simulation framework has been design around the two main aspects distributed and heterogenous simu lation To do so the simulation tool leverages two open source tools Ptolemy ll and HLA CERTI Ptolemy II 4 is an open source modeling and simulation tool for heterogeneous systems developed at the University of California Berkeley This tool is well suited for modeling CPS 3 by providing different models of computation MoC such as continuous time for describing physical properties or discrete events for describing software and control The IEEE High Level Architecture HLA standard 10 9 targets distributed simulation A CPS is seen as a federation grouping several federates which communicate via publish subscribe patterns This decomposition into federates allows to combine different types of components such as simulation models concrete functional codes in C
86. ent to a timestamp of HLA CERTI The Time class also provides constructor based on a double value We use this constructor to build a Time object in a Ptolemy simulation model from the timestamp of a HLA event Listing 5 4 ptolemy apps hlacerti lib HlaManager updateHlaAttribute Update the HLA attribute lt i gt attributeName lt i gt with the containment of the token lt i gt in lt i gt The updated attribute is sent to the HLA CERTI Federation param hp The HLA publisher actor HLA attribute to update param in The updated value of the HLA attribute to update throws IllegalActionException If a CERTI exception is raised then displayed it to the user void updateHlaAttribute HlaPublisher hp Token in throws IllegalActionException Time currentTime director getModelTime The following operations build the different arguments required to use the updateAttributeValues UAV service provided by HLA CERTI Retrieve information of the HLA attribute to publish Object tObj _hlaAttributesToPublish get hp getName Encode the value to be sent to the CERTI byte valAttribute _encodeHlaValue hp in SuppliedAttributes suppAttributes null try suppAttributes RtiFactoryFactory getRtiFactory createSuppliedAttributes catch RTIinternalError e throw new IllegalActionException this e RTIinternalError suppAttributes add Integer tObj 4 valAttribute b
87. ete systems This work is rather recent and still undergoing various changes a new version is currently being standardized 18 Even if part of our research is similar FMI does not answer all our objectives presented above The current standard presents limitations to manage discrete event simulation properly 1 and no information is provided to address distributed simulation challenges This report is organized as follows An overview of HLA and Ptolemy II are presented in Chapter 2 and chapter 3 see also 12 13 Chapter 4 describes the co simulation framework and shows how interoperability is obtained chapter 5 presents the architecture design and implementation A user manual is presented in chapter A The instal lation guide and user guide are presented in chapter B Finally chapter 6 presents concluding remarks and our future work Chapter 2 The High Level Architecture Standard and the CERTI framework This chapter presents the IEEE High Level Architecture standard HLA adressing distributed simulation complex ities We first give here a brief overview of the HLA standard and how an HLA simulation is implemented We describe then the subset of HLA services necessary to interface a Ptolemy model with an HLA federation This chapter focused on object management shared data and data representation and time management time advance ment semantics in an HLA simulation 2 1 Overview of HLA The High Level Architecture HLA 9 1
88. ework makes interoperable two open source simulation tools PtolemyII and HLA CERTI The strategy is focused on interfacing a Ptolemy simulation model with a HLA CERTI Federation e g integrate a Ptolemy simulation as a federate in a federation Our framework has been developped integrated and released di rectly with the Ptolemy core project More information on Ptolemy is provided at http chess eecs berkeley edu ptexternal The co simulation framework is not a simple binding of the HLA CERTI services for Ptolemy As detailed in section 4 it was designed for handling properly time management data communication and simulation execution between both simulators The JCERTI java bindings for CERTI is used to interface Ptolemy federates implemented in Java with HLA CERTI written in C The framework architecture is built in two parts The first part is the design and the implementation of a specific interface so called TimeRegulator This interface allows for a Ptolemy director in an elegant way to consult a specific time advancement algorithm when it advances its time The second part is the ptolemy apps hlacerti library that provides a set of classes wich realize the data exchanges the time management between both the Ptolemy simulation model and the HLA CERTI Federation Additionnal features have been implemented to ease the design of Ptolemy federates in Vergil and the to automatize the simulation execution of a HLA Federation from Ptole
89. f requireSynchronization If the current Federate is the creator then create the synchronization point if isCreator try byte rfspTag EncodingHelpers encodeString synchronizationPointName _rtia registerFederationSynchronizationPoint _synchronizationPointName rfspTag catch FederateNotExecutionMember e throw new IllegalActionException this e FederateNotExecutionMember catch SavelnProgress e throw new IllegalActionException this e SavelnProgress catch RestorelnProgress e throw new IllegalActionException this e RestorelnProgress catch RTIinternalError e throw new IllegalActionException this e RTIinternalError catch ConcurrentAccessAttempted e hrow new IllegalActionException this e ConcurrentAccessAttempted et Wait synchronization point callbacks while _federateAmbassador synchronizationSuccess amp amp federateAmbassador synchronizationFailed try CertiRtiAmbassador rtia tick2 catch SpecifiedSaveLabelDoesNotExist e throw new IllegalActionException this e SpecifiedSaveLabelDoesNotExist catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch RTIinternalError e throw new IllegalActionException this e RTIinternalError if federateAmbassador synchronizationFailed throw new IllegalActionException this CERTI
90. federates are made through two particular services see Figure 2 2 the timeAd vanceRequest service TAR is used to implement time stepped federates the nextEventRequest service NER is used to implement event based federates The granted time is provided by timeAdvanceGrant TAG The time advancement phase of a Federate F in HLA is a three step process 1 F sends a request using NER or TAR services 2 F can receive reflectAttribute Value RAV callbacks i e updated HLA attributes 3 F waits for the granted time tg TAG At the TAG tG reception the federate s local time will be advanced to tg according to the made request NER or TAR A part of the time advancement phase semantics is shown in Figure 2 3 FederateTAR see figure 2 3 a produces an event at time fj with updateAttribute Value UAV The current logical time is t let us consider that the next event is e with timestamp h t2 t A A gt 0 The federate asks the RTI for a time progress with the invocation of TAR t2 Until the reception of the TAG t2 callback the logical time of the federate is stalled at r and it can receive a RAV v t1 callback Timestamp 1 is in the interval t 1 FederateTAR can realise a computation with the values received with RAV The federate then receives TAG t2 and can increase its local time to fo 12 FederateTAR RTI UAV V 1 t1 t1 tick RAV V 2 t1 t2 oc UAV V 1 t2 Figure 2
91. ger Integer _objectIdToClassHandle J 111 private methods 111 This generic method should call the link EncodingHelpers API provided by CERTI to handle type decoding operations for HLA value attribute that has been reflected param type The type to decode the token param buffer The encoded value to decode return The decoded value as an object throws IllegalActionException If the token is not handled or the decoding has failed XL private Object _decodeHlaValue Type type byte buffer throws IllegalActionException GL FIXME PTIDES if type instanceof RecordType Double ret EncodingHelpers decodeDouble buffer return ret else if type equals BaseType BOOLEAN return EncodingHelpers decodeBoolean buffer else if type equals BaseType UNSIGNED BYTE return EncodingHelpers decodeByte buffer else if type equals BaseType DOUBLE GL FIXME XXX This code only work with SDSE PRISE joystick federate boolean useMessageBuffer false 85 if useMessageBuffer ByteArrayInputStream bis new ByteArrayInputStream buffer ByteArrayOutputStream bos new ByteArrayOutputStream MessageBuffer mb new MessageBuffer bis bos try mb receiveData catch IOException e e printStackTrace catch CertiException e e printStackTrace double ret mb readDouble return reti else return EncodingHelpers decodeDouble buffer
92. hat implement interfaces provided by al ee ee ee AA A 200000000 D 888 8 E Markers X ES Properties 4 Servers ME Data Source Explorer 5 Snippets BE Outline X El Task List B BARo Y HB ptolemy apps hlacerti lib MC HlaManager c HlaManager CompositeEntity String federateName Parameter federationName Parameter fedFile FileParameter useNextEventRequest Parameter useTimeAdvancedRequest Parameter isTimeConstrained Parameter isTimeRegulator Parameter hlaStartTime Parameter hlaTimeStep Parameter hlaLookAHead Parameter requireSynchronization Parameter synchronizationPointName Parameter isCreator Parameter 4 attributeChanged Attribute void 4 clone Workspace Object 0 a initialize void 0 4 preinitialize void 6 4 proposeTime Time Time A updateHlaAttribute String Token Bool wrapup void 9 hlaAttributesToPublish HashMap St Yor O errors 13 307 warnings 2 058 others Filter matched 200 of 15365 items Description Resource Path Location Type K amp Java Problems 100 of 13307 items b Java Task 100 of 2058 items Writable Smart insert 128 1 Figure B 10 Correct compilation of the HlaManager java class in ptII ay RTlinternalError in clockDisplayer HlaManager Because Connection to RTIA failed libRTI Network Read Error Go To Actor od Display Stack Trace Dismiss e Figure B 11 RTlinternalError
93. he HLA services to unsubscribe to HLA attributes unpublish HLA attributes resign a Federation and destroy a Federation if the current Federate is the last participant throws IllegalActionException If the parent class throws it of if a CERTI exception is raised then displayed it to the user public void wrapup throws IllegalActionException 82 super wrapup if _debuggin _debug this getDisplayName Unsubscrib for Object obj _hlaAttributesSubscribedTo values try _rtia unsubscribe0bjectClass Integer obj 3 catch ObjectClassNotDefined e throw new IllegalActionException this e ObjectClassNotDefined catch ObjectClassNotSubscribed e throw new IllegalActionException this e ObjectClassNotSubscribed catch FederateNotExecutionMember e throw new IllegalActionException this e FederateNotExecutionMember catch SavelnProgress e throw new IllegalActionException this e SavelnProgress catch RestorelnProgress e throw new IllegalActionException this e RestoreInProgress catch RTIinternalError e throw new IllegalActionException this e RTIinternalError catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted if _debugging _debug this getDisplayName wrapup Unsubscribe TypedIOPort obj 0 getContainer getName classHandle obj 3
94. he containment of the token lt i gt in lt i gt The updated attribute is sent to the HLA CERTI Federation Qparam attributeName Name of the HLA attribute to update param in The updated value of the HLA attribute to update param asHLAPtidesEvent Indicate if it will be send to a PtidesPlatform throws IllegalActionException If a CERTI exception is raised then displayed it to the user XI void updateHlaAttribute String attributeName Token in Boolean asHLAPtidesEvent throws IllegalActionException Time currentTime director getModelTime The following operations build the different arguments required to use the updateAttributeValues UAV service provided by HLA CERTI Retrieve information of the HLA attribute to publish Object tObj _hlaAttributesToPublish get attributeName 81 Ef Encode the value to be sent to the CERTI byte valAttribute _encodeHlaValue in asHLAPtidesEvent SuppliedAttributes suppAttributes null try suppAttributes RtiFactoryFactory getRtiFactory createSuppliedAttributes catch RTIinternalError e throw new IllegalActionException this e RTlinternalError suppAttributes add Integer tObj 4 valAttribute byte tag EncodingHelpers encodeString TypedIOPort tObj 0 getContainer getName Create a representation of the current director time for CERTI Double myEpsilon 0 000000 Double myEpsilon 0 0000000
95. hese methods are declared private as this mecanism to wrap the data to exhange between Ptolemy and HLA CERTI is opaque for the user 5 3 5 Time management Let us consider an event e v 1 with value v and timestamp t The HlaManager time management service should ensure that events exchanged between federates are delivered at timestamp 1 in a Ptolemy model as well as in a HLA Federation The complexity introduced by the co simulation comes from the different semantics attached to the sending operation of an event For Ptolemy an event is processed and sent at logical time t But the specification of HLA 2 says that the federate shall guarantee that it will not generate an event at any time in the future with a time stamp less than or equal to the local time last granted time or less than the local time plus the federate s lookahead if its lookahead is not zero Therefore the HLA standard provides two additionnal services TARA and NERA to deal with a null lookahead I 0 31 Let us recall that the HlaManager is a time regulator attribute It implements the proposeTime method sec tion 5 2 2 that realizes the time management service between both simulators The algorithm proposed in section 4 has been implemented in this method Under some restrictions we provide the use of the 4 HLA time advancement mecanisms TAR NER TARA and NERA to the user The next sub sections will describe how they are integrated in
96. ibutes return the proposedTime argument param proposedTime The time proposed return The smallest time returned by a TimeRegulator or the proposedTime if none exception IllegalActionException If a time regulator throws it protected Time _consultTimeRegulators Time proposedTime throws IllegalActionException Time returnValue proposedTime List lt TimeRegulator gt regulators getContainer attributeList TimeRegulator class i for TimeRegulator regulator regulators Time modifiedTime regulator proposeTime returnValue if modifiedTime compareTo returnValue lt 0 returnValue modifiedTime return returnValue The listing 5 1 shows the modification of the high level class ptolemy actor Director which implements a Director in Ptolemy The private method _consultTimeRegulators has been added and enables for a director to consult the time regulator Ptolemy attributes before they advance time The call of this private method must be explictly made by the domain specific director such as DE director CT director etc The listing 5 2 shows this mechanism added to the method _getNextActorToFire of the DE director Listing 5 2 Code snippets of ptolemy domains de kernel DEDirector java protected Actor _getNextActorToFire throws IllegalActionException if actorToFire null 1f the actorToFire is not set yet find the actor associated with the event just found and updat
97. ime regulator El Value of the start time of the Federate an DoubleToken public Parameter hlaStartTime This parameter must contain 69 Value of the time step of the Federate This parameter must contain an DoubleToken public Parameter hlaTimeStep Value of the lookahead of the HLA ptII federate This parameter must contain an DoubleToken public Parameter hlaLookAHead Boolean value true if the Federate is synchronised with other Federates using a HLA synchronization point false if not This parameter must contain an BooleanToken public Parameter requireSynchronization Name of the synchronization point if required This parameter must contain an StringToken public Parameter synchronizationPointName Boolean value true if the Federate is the creator of the synchronization point false if not This parameter must contain an BooleanToken public Parameter isCreator FLU MB MLB Bg M M LL ll HP PPP Pg E L T L LL EEE T EA public methods Checks constraints on the changed attribute when it is required and associates his value to its corresponding local variables param attribute The attribute that changed exception IllegalActionException If the attribute is empty or negative public void attributeChanged Attribute attribute throws IllegalActionException super attributeChanged attribute if attribute federateNam
98. imeRegulator interface section 5 2 HlaManager attribute sec tion 5 3 and the HlaSubscriber and HlaPublisher actors section 5 4 5 5 1 Interaction with HlaPublisher Let us consider now the methods updateHlaAttribute and proposeTime of the HlaManager attribute presented in Figure 5 1 and 5 2 Figure 5 4 a describes the interaction through its execution flow to publish an update of a HLA attribute between the director the HlaPublisher actor the HlaManager attribute and the RTI The methods proposed by the RTI are provided by the JCERTI API The updateHlaAttribute method is provided by the HlaManager to HlaPublisher actors This method en capsulates the operations to build an updated value of a HLA attribute from a Ptolemy event and calls the Object management services relative to the publication of the updated value only the call to the updateAttributeValues service is showed in the Figure 5 4 a The initialize method not showed in Figure 5 4 a of the HlaPublisher allows to retrieve the reference to the HlaManager deployed in the model Thus the actor can invoke the updateHlaAttributeValue method provided by the manager during the execution of its ire method triggered by the director A publication action is enabled by the connection of an output port of a Ptolemy source actor of the core library to the input port of the HlaPublisher To summarize each reception of an event e v on this input port at time lea
99. ing Ptolemy II Ptolemy org 2014 Appendix A User Manual for HLA PTII federates For more information about the HLA PTII co simulation framework read 13 12 7 Demos can be found in PTII ptolemy apps hlacerti demo The actors can be found in the library under MoreLibrairies gt Co Simulation gt HLA HlaManager HlaPublisher and HlaSubscriber The information here are up to revision 171806 it comes with jcerti jar and the rtig is launched automatically when running a co simulation You need also the HLA compliant RTI called CERTI tested with versions 3 4 2 3 4 3 and 3 5 http www nongnu org certi certi doc Install html index html Put in your bash profile un export for PTI and SCERTI HOME Or at least put aliases alias myPtII export PTII your path to ptII alias cfgCerti source your CERTI HOME share scripts myCERTI env sh Do not forget to execute these aliases in each terminal you open 1 Building a model with HLA PTII co simulation framework Let us suppose you have already a centralized Ptolemy model as the one of figure A 1 a You want to simulate this model in a distributed way using 3 simulators one for each composite actor Important remark The top level model must use a DE director but you can have a Continuous director in a composite actor inside i 5 5 DE Director producer p pregon DE Director HlaManager DE Director producer EA ES PC1 producer consumer MA ODO emm CERTI CERTI CERTI esto
100. insKey classHandleName classHandleHlaPublisherTable get classHandleName add elt getKey else LinkedList lt String gt list new LinkedList lt String gt list add elt getKey classHandleHlaPublisherTable put classHandleName list 92 3 Declare to the Federation the HLA attributes to publish If these attributes belongs to the same object class then only one registerObjectInstance call is performed Then update the HlaPublishers table with the new information Iterator lt Entry lt String LinkedList lt String gt gt gt it3 classHandleHlaPublisherTable entrySet iterator while it3 hasNext Map Entry lt String LinkedList lt String gt gt elt Map Entry it3 next LinkedList lt String gt hlaPublishers elt getValue int classHandle rtia getObjectClassHandle elt getKey The attribute handle set to declare all attributes to publish for one object class AttributeHandleSet attributesLocal RtiFactoryFactory getRtiFactory createAttributeHandleSet Fill the attribute handle set with all attibute to publish for String s hlaPublishers attributesLocal add Integer hlaAttributesToPublish get s 4 Declare to the Federation the HLA attribute s to publish try rtia publishObjectClass classHandle attributesLocal catch OwnershipAcquisitionPending e e printStackTrace int myObjectInstId 1 ROI is called only o
101. ionAlreadyEnabled jilc oJ LCs Jle JE EncodingHelpers NullFederateAmbassador RtiFactory RtiFactoryFactory java util logging Logger ByteArrayInputStream ByteArrayOutputStream IOException InputStream OutputStream util Li util util util acto acto acto acto acto acto acto kern kern kern kern kern kern data data data data data data data data data data data data data data data domains de kernel DEDirector net MalformedURLException HashMap erator LinkedList st Map Map Entry oSuchElementException r AbstractInitializableAttribute r Actor r CompositeActor r TimeRegulator r TypedIOPort r util Time r util TimedEvent BooleanToken DoubleToken FloatToken IntToken LongToken RecordToken ShortToken StringToken Token UnsignedByteToken expr FileParameter expr Parameter type Baselype type RecordType type Type el CompositeEntity el util Attribute el util IllegalActionException el util NameDuplicationException el util NamedObj el util Workspace 65 import certi communication CertiException import certi communication MessageBuffer impor impor certi rti impl CertiLogicalTime certi rti impl CertiLogicalTimeInterval import certi rti impl CertiRtiAmbassador FIM ML B E O E AAA O O O O O O CINA O TT ATT PP EAT TTT HlaManager lt p gt This attribute implements a HLA Manager
102. ix continuous discrete or other MoCs and interoperability provided by HLA i e the possibility to mix simulation models pieces of code and physical equipments 13 Related work Interoperability is a very important issue in distributed discrete event simulation as can be observed by several works targeting co simulation Closely related to our work are two particular cooperation tools that provide similar capabilities by providing HLA plugins In 8 the authors encode a connection between HLA and Modelica 17 for the virtual prototyping of mecha tronic systems In 5 the authors develop an HLA Blockset and an HLA Toolbox which provides a connection between HLA and MATLAB Simulink However these solutions are not open source and the synchronization time between the federates is not described in literature Our framework is open source using existing open source frame works and is intended for research teaching and industrial usage and several solutions for mixing the timing are explained in the current paper Related to this work in a broader context ins the work on Functional Mock up Interfaces FMI 18 which is lead by a consortium of industrials and academics The standard defines an interface standard for coupling different simulation tools in a co simulation environment e g by giving standardized access to simulation model equations In this case co simulation is a simulation technique for coupled time continuous and time discr
103. l Class Folder gt os jython jar ptll lib K os kieler jar ptll lib K fae mapss jar ptll lib K I nesc jar ptll ptolemy domains ptinyos lib gt ns PDFRenderer jar ptll lib gt s ptCal jar ptll lib K os ptcolt jar ptll lib gt os ptjacl jar ptll lib K 7 saxon8 dom jar ptll lib A F3 ET Vu B gt Java Problems 100 of 13388 items b Java Task 100 of 2058 items Figure B 8 Resolve JCERTI interface dependencies in ptlII 2 5 Project Explorer 23 type filter text Java Build Path utline 3 El Task List n P Resource Builders mm uis JARs and class folders on the build path b Java Compiler gt ns antir jar ptll ptolemy actor ptalon antir Add JARs eis f gt os bsh 2 0b4 jar ptll lib G on de i nisi ai L chic jar ptll lib Add External JARS Refunds guavajar ptil lib Run Debug Settings K 7 jasminclasses jar ptll lib Add Variable bande K os java_cup jar ptll lib b Task Repository Add Library Task Tags K oa jdom jar ptll ptolemy domains ptinyos lib b Validation K fag jini core jar ptll ptolemy distributed jini jar Add Class Folder WikiText gt os jini ext jar pul ptolemy distributed jini jar gt o3 junit 4 8 2 jar ptll lib Add External Class Folder gt a JUnitParams 0 3 0 jar ptll lib gt os jython jar ptll lib K os kieler jar ptll lib K I mapss jar ptll lib K I nesc jar ptll ptolemy domains ptinyos lib gt
104. lastProposedTime Hf If the HLA Time Management is required ask to the HLA CERTI Federation the RTI the authorization to advance its time if isTimeRegulator amp amp _isTimeConstrained synchronized this Build a representation of the proposedTime in HLA CERTI CertiLogicalTime certiProposedTime new CertiLogicalTime proposedTime getDoubleValue Call the corresponding HLA Time Management service try if useNextEventRequest if _debugging debug this getDisplayName proposeTime call CERTI NER nextEventRequest certiProposedTime getTime _rtia nextEventRequestAvailable certiProposedTime else if _debugging _debug this getDisplayNanme proposeTime Call CERTI TAR timeAdvanceRequest certiProposedTime getTime _rtia timeAdvanceRequestAvailable certiProposedTime catch InvalidFederationTime e throw new IllegalActionException this e InvalidFederationTime catch FederationTimeAlreadyPassed e throw new IllegalActionException this e FederationTimeAlreadyPassed catch TimeAdvanceAlreadyInProgress e throw new IllegalActionException this e 79 TimeAdvanceAlreadyInProgress catch EnableTimeRegulationPending e throw new IllegalActionException this e EnableTimeRegulationPending catch EnableTimeConstrainedPending e throw new IllegalActionException this e
105. ldNotDiscover ObjectClassNotKnown if debugging _debug HlaManager t discoverObjectInstance objectName theObject t n i i punt _objectIdToClassHandle put theObject GL FIXME XXX FederateInternalError his getDisplayName INNER the object class has been discovered theObject theObjectClass theObjectClass theObjectClass check with PS if this code could be remove also when using HLA v1516 try attributes if if _debugging _debug HlaManager this getDisplayName po po cate e pr catc e pr catc e pr catc e pr catc e pr catc e pr catc e prin f 87 intStackTrace h intStackTrace h intStackTrace h intStackTrace h tStackTrace RTIinternal tStackTrace in h in n tStackTrace discoverObjectInstance V has been discovered theObject theObjectClass null hlaAttributesSubscribedTo get objectName _rtia requestObjectAttributeValueUpdate theObject null attributes INNER objectName theObject theObjectClass ObjectNotKnown e di AttributeNotDefined e di FederateNotExecutionMember e di SavelnProgress e di RestoreInProgress e Error e i ConcurrentAccessAttempted e i HLA Time Management services callbacks Callback delivered by the RTI CERTI Ay
106. lean asHLAPtidesEvent Listing C 3 ptolemy apps hlacerti lib HlaManager java This attribute implements a HLA Manager to cooperate with a HLA CERTI Federation 63 Copyright c 2013 The Regents of the University of California All rights reserved Permission is hereby granted without written agreement and without license or royalty fees to use copy modify and distribute this software and its documentation for any purpose provided that the above copyright notice and the following two paragraphs appear in all copies of this software NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY OR DIRECT INDIRECT SPECIAL INCIDENTAL OR CONSEQUENTIAL DAMAGES RISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION EVEN IF HE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF UCH DAMAGE Qo Hr m Hj H THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE THE SOFTWARE PROVIDED HEREUNDER IS ON AN AS IS BASIS AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE SUPPORT UPDATES ENHANCEMENTS OR MODIFICATIONS PT COPYRIGHT VERSION 2 COPYRIGHTENDKEY package ptolemy apps hlacerti lib import hla import hla import hla import hla import hla import hla import hla import hla import hla import hla import
107. led public void preinitialize throws IllegalActionException super preinitialize Try to launch the HLA CERTI RTIG subprocess _certiRtig new CertiRtig this debugging certiRtig initialize fedFile asFile getAbsolutePath _certiRtig exec if _debugging _debug this getDisplayName preinitiliaze Launch RTIG process if _certiRtig isAlreadyLaunched certiRtig terminateProcess certiRtig null if _debugging debug this getDisplayName preinitiliaze Destroy RTIG process as another one is already launched Propose a time to advance to This method is the one implementing the TimeRegulator interface and using the HLA CERTI Time Management services Ed 1f required Following HLA and CERTI recommendations if the Time Management is required then we have the following behavior Case 1 If lookahead 0 N a if time stepped Federate then the timeAdvanceRequestAvailable TARA service is used b if event based Federate then the nextEventRequestAvailable NERA service is used Case 2 If lookahead gt 0 c if time stepped Federate then timeAdvanceRequest TAR is used d if event based Federate then the nextEventRequest NER is used Otherwise the proposedTime is returned NOTE For the Ptolemy II HLA CERTI cooperation the default and correct behavior is the case 1 and CERTI has to be compiled with the option
108. legalActionException t n row new IllegalActionException t n throw new IllegalActionException t TimeConstrainedAlreadyEnabled TimeConstrainedAlreadyEna EnableTimeConstrainedPending EnableTimeConstrainedPend TimeAdvanceAlreadyInProgress TimeAdvanceAlreadyInProgr FederateNotExecutionMember e FederateNotExecutionMembe SaveInProgress e RestoreInProgress e RTIinternalError e ConcurrentAccessAttempted e ConcurrentAccessAttempted Declare the Federate time regulator if if _isTimeRegulator try _rtia enabl cate n row new IllegalActionException t n row new IllegalActionException t n row new IllegalActionException t n row new IllegalActionException t n row new IllegalActionException t n row new IllegalActionException t n row new IllegalActionException t n row new IllegalActionException t n throw new IllegalActionException t TimeRegulationAlreadyEnabled TimeRegulationAlreadyEnab EnableTimeRegulationPending e EnableTimeRegulationPendi TimeAdvanceAlreadyInProgress TimeAdvanceAlreadyInProgr InvalidFederationTime e InvalidFederationTime InvalidLookahead e FederateNotExecutionMember e FederateNotExecutionMembe SaveInProgress e RestoreInProgress e RTIinternalError e 74 e true e his led his e his ess his his
109. lemy federate specified by the user The fourth task is the configuration of the HLA time advancement mecanism used by the federate e g con strained and regulator and specified by the user during the design of the Ptolemy federate model Finally the last task is the synchronization of the start of the execution of the Ptolemy federate if required by the user The HLA synchronization point services are used here to suspend the execution of the federate until the end of the initalization phase of the other federates Without this mecanism it is possible to have some federates that finish their execution before a federate joins the federation 30 5 3 3 Wrapup The wrapup service implements only the wrapup method of the Ptolemy attribute core specification see class diagram figure 5 2 This method is responsible to the unpublish and unsubscribe tasks of HLA attribute values to disconnect the federate to the federation and to destroy the federation if needed 5 3 4 Data wrapper A complex issue of co simulation involving simulation frameworks implemented in distinct execution platforms is data types representation Ptolemy handles a set of basic types e g byte double float etc as well as more complex types record etc Most of them are based on Java primitive data types Fortunately JCERTI provides the encodingHelpers API which interfaces Java primitive data types with several data types in C handled by CERTI In addition our
110. llow the physical processes affect computations and vice versa Today CPS can be found in various domains such as spatial avionics automotive transportation healthcare etc Systems involved in these domains are mainly referred to the distributed realtime and embedded system familly Designing real time and distributed cyber physical systems CPS is a complex task which typically entails the use of many different methodologies and tools in different areas and at different stages of development process The figure 1 1 extracts from the http cyberphysicalsystems org website summarizes in an elegant way the CPS design complexities through a concept map Typically different parts of the CPS are developed by different engineering teams or even external contractors Integrating these heterogeneous parts and evaluating the composite behavior is challenging and with today s tools a systematic composition is nearly impossible Over the last years model based tools have gained momentum in the design of CPS as they allow for modeling at higher levels of abstraction and they facilitate the communication between different teams of engineers Additionally many tools come with add ons such as formal verification and code generation However different parts of a CPS require different abstractions and tool support The lack of interoperability between the tools poses a major challenge For control command systems Matlab Simulink 16 is often used to sp
111. lue else if type equals BaseType SHORT encodedValue EncodingHelpers encodeShort ShortToken t shortValue else if type equals BaseType STRING encodedValue EncodingHelpers encodeString StringToken t StringValue else throw new IllegalActionException this The current type of the token t is not handled by this getDisplayName GL FIXME PTIDES if asHLAPtidesEvent Time currentTime director getModelTime if _debugging debug this getDisplayName encodeHlaValue Encoded as HlaPtidesEvent currentTime currentTime getDoubleValue recordTimestamp recordTimestamp HlaPtidesEvent he new HlaPtidesEvent recordTimestamp 87 recordMicrostep sourceTimestamp encodedValue return he getBuffer else return encodedValue The method link _populatedHlaValueTables populates the tables containing information of HLA attributes required to publish and to subscribe value attributes in a HLA Federation throws IllegalActionException If a HLA attribute is declared twice Ef private void populateHlaAttributeTables throws IllegalActionException CompositeActor ca CompositeActor this getContainer List lt HlaSubscriber gt hlaSubscribers null List lt HlaPublisher gt _hlaPublishers null _hlaAttributesToPublish clear _hlaAttributesSubscribedTo clear _hlaPublishers ca entityList HlaPublisher class
112. my Next sections describe this interface and the main entities implemented to realize the cooperation 5 2 TimeRegulator interface The TimeRegulator is a joint effort made during the visit of Dr G Lasnier ISAE to the Ptolemy team at the University of California Berkeley The Java source code of this interface is given in Annex A C 1 and is located in the ptolemy actor java package in the Ptolemy project Ptolemy attributes belong to the global notion of decorators provided by Ptolemy and have already been presented in chapter 4 The attribute s lifecycle is similar to the actor s one but contains only the setup pre initialize and initialize methods and wrapup wrapup method phases No iterate phase prefire fire or postfire methods is performed 26 5 2 1 Ptolemy core modification The TimeRegulator interface requires to be implemented by a Ptolemy attribute and allows to parameterize the time advancement algorithm of a director Due to the number of directors implemented in Ptolemy this interface has been designed to be introduced in a general and friendly way to each director behavior that may requires the use of those regulators Listing 5 1 Code snippets of ptolemy actor Director java Consult all attributes contained by the container of this director that implement the link TimeRegulator interface if any and return the smallest time returned by those regulators If there are no such attr
113. my On one hand the Ptolemy initial model will be deeply modified and complexified and in another hand the implementation work to enable HLA services as actors in Ptolemy is very important required ressources and time The other approach is to develop a limited number of actors or attributes and restrict the adaptation of a Ptolemy model as the simple interactions which allow the execution of time advance request the execution of UAV service to send event to the federation and a mecanism to get callbacks from the RTI to receive TAG and RAV services This requires to fix the behavior of a Ptolemy federate and to encapsulate the logic to execute HLA services in a high level Ptolemy entity The main advantage of this approach is to simplify the adaptation of a Ptolemy model to be integrate as a federate ina HLA feeration Ptolemy users with few knowledges of HLA may easily use the co simulation to make distributed simulation between Ptolemy models or another HLA compliant simulator A configuration interface is provided to the user that allows to tune some HLA services as the ones from the time management The initial Ptolemy model chosen to co operate with a HLA federation is a DE model We have seen that the DE semantics is based on the one from discrete event theory and shares similarities with the event based federates implemented in HLA CERTI The current version of framework considers only DE model as the top level model in Ptolemy A contin
114. my simulation model The next sub sections shows the implementation of the actor HlaPublisher resp HlaSubscriber which realizes the send resp receive operation 5 4 1 HlaPublisher send Ptolemy events to the HLA CERTI Federation According to the DE event semantics a DE event is consumed when the token attached to this event is taken from the receiver queue of its destination actor s input port Token are then processed at timestamp Our approach defines a specific actor so called HlaPublisher that implements a publisher in a HLA CERTI Federation Its algorithm is quite simple At each reception of a token on the actor s input port the actor is fired and the operation send has to be performed see listing C 2 in Appendix C The listing 5 5 shows only the fire method of the HlaPublisher triggered after the reception of an event on its input port Listing 5 5 ptolemy apps hlacerti lib HlaPublisher java Each tokens received in the input port are transmitted to the link HlaManager for a publication to the HLA CERTI Federation ay public void fire throws IllegalActionException if inputPortList get 0 hasToken 0 Token in inputPortList get 0 get 0 _hlaManager updateHlaAttribute this getName in _asHLAPtidesEvent if _debugging debug this getDisplayName Called fire the update value in toString 1 of the HLA Attribute this getName has been sent to
115. n Ptolemy HLA CERTI and discuss about how the time management and the data communication between both frameworks are handled in our approach 4 1 Co simulation strategy In HLA the RTI implements the simulation control An HLA Federate uses one of the 4 time advancement algo rithms defined TAR NER TARA or NERA to declare a time advance request that is granted or not by the RTI 17 according to the semantics given to the request as presented in section 2 Enabling distributed simulation using Ptolemy model requires the definition and the implemention of an entity distributed or not to maintain the control of the simulation As the RTI of HLA has been precisely implemented to achieve this task we choose to use the RTI as the simulation control authority for the co simulation This choice brings us to consider only one strategy to enable the co simulation between Ptolemy and HLA CERTI A Ptolemy model is slightly modified to become a Ptolemy federate participating in a HLA federation To adapt a Ptolemy model as a federate two approches have been considered The first one is to realize a binding of HLA services for Ptolemy as implemented in Forwardsim 5 Thus each HLA service is implemented as one or several actors or attributes The main advantage of this approach is to give a maximum of flexibility to the the user to model a Ptolemy federate The main drawbacks are that a user needs to have a strong expertise of HLA in addition to Ptole
116. nce time for one federate This means that only one instance of object class are allowed try myObjectInstId rtia registerObjectInstance classHandle elt getKey federateName catch ObjectClassNotPublished e e printStackTrace catch ObjectAlreadyRegistered e e printStackTrace for String s hlaPublishers Object tObj 0bject hlaAttributesToPublish get s _hlaAttributesToPublish put s new Object tObj 0 tObj 1 tObj 2 tobj 3 tObj 4 myObjectInstId For each HlaSubscriber actors deployed in the model we declare to the HLA CERTI Federation a HLA attribute to subscribe to Iterator lt Entry lt String Object gt gt ot _hlaAttributesSubscribedTo entrySet iterator while ot hasNext Map Entry lt String Object gt elt Map Entry ot next Object t0bj Object elt getValue 93 int classHandle rtia getObjectClassHandle String tObj 2 int objAttributeHandle rtia getAttributeHandle TypedIOPort tObj 0 getContainer getName classHandle Update HLA attribute information for subscription from HLA services In this case the tObj object as the following structure tObj 0 gt output port which will produce the event received as updated value of a HLA attribute tob3 1 gt type of the port e g of the attribute tObj 2 gt object class name of the attribute tobj 3 g
117. nding a Ptolemy event to the HLA federation This service is not directly executed by the HlaManager but it is provided to the HlaPublisher actor connected to the output port of the actor in the Ptolemy model that want to send an updated attribute value to the federation The listing 5 4 describes the updateHlaAttribute method that implements the UAV service We use the hlaAt tributesToPublish routing table of HlaPublisher actors to make the relation between the updated attribute value to send and its corresponding HLA attribute FOM specification According to the HLA standard these information are required to build the different parameters used by the updateAttributeValues UAV HLA service provided by JCERTI According to the HLA standard an updated attribute value must be sent with a timestamp greater than the current HLA logical time i e to the last TAG timestamp received by the federate if the TAR or NER time advancement mecanisms is used with a lookahead value 0 or greater or equal to the current HLA logical time in the case of TARA and NERA mecanisms with a lookahead 0 During the implementation of the co simulation framework we have not restricted this possibility to offer more flexibility during the development of a Ptolemy federate Unfortunately the case of TAR and NER with lookahead gt 0 requires an adaptation due to the Ptolemy DE semantics where an event e v f is processed and sent at timestamp ts Let us recall
118. ng attributeChanged synchronizationPointName isCreator isCreator isCreator isCreator setDisplayName Is synchronization point creator attributeChanged isCreator new Parameter this isCreator setTypeEquals BaseType BOOLEAN setExpression false 2 HUM MEME B BG LEE ET RELATE TT public variables Name of the Ptolemy Federate StringToken public Parameter federateName This parameter must contain an Name of the federation This parameter must contain an StringToken public Parameter federationName must contain an StringToken public FileParameter fedFile Path and name of the Federate Object Model ET FOM file This parameter Boolean value true nextEventRequest BooleanToken public Parameter useNextEventRequest if the Federate requires the use of the HLA service This parameter must contain an Boolean value true timeAdvanceRequest BooleanToken public Parameter useTimeAdvancedRequest if the Federate requires the use of the HLA service This parameter must contain an if the Federate is declared time constrained y Boolean value true false if not This parameter must contain an BooleanToken public Parameter isTimeConstrained Boolean value true false if not This parameter must contain an BooleanToken public Parameter isTimeRegulator if the Federate is declared t
119. not resolved yet Figures B 7 to B 9 shows the steps to do to resolve this problem the process is described in section 4 The figure B 10 shows the the correct compilation of the HlaManager java class Finally after all those steps you must have no errors in your ptII java project 7 Running a quick example This section describes a simple example of PRODUCER CONSUMER to test your environment This example is composed on two Ptolemy federates that exchange updated value of an HLA attribue 8 Known issues The current implementation of the co simumalion framework is an on going work provided as prototype Even if we have made several deep tests on our framework it may be possible to observe some strange behaviors or bugs running under different architectures Also as we make interoperable different open source tools it is sometimes 53 amp Eclipse WACS a O 3 0 7 Ew0 LI lun 30 sept 22 33 Gilles LASNIER Q Java EE Eclipse Users gil Work eclipse kepler isae MacOSX 64bits workspace isae a S TER Hr r o gt y eno Properties for ptll Quick Access ES 199 Java EE L pe filter te v T S I Project Explorer 2 as type filter text Java Build Path v Outline X Task List gt pt Resource outline is not available am Builders META 12 Projects Libraries 5 Order and Export Java Build Path y b Java Code Style Source folders on build path b Java Compiler Y 3 ptil Add Folder b Java Editor
120. ntAccessAttempted All those exceptions are from the HLA CERTI implementation public void initialize RTIambassador rtia throws NameNotFound ObjectClassNotDefined FederateNotExecutionMember RTIinternalError AttributeNotDefined SavelnProgress RestoreInProgress ConcurrentAccessAttempted this timeAdvanceGrant false this timeConstrained false this timeRegulator false this synchronizationSuccess false t t E a G t t t t t t his synchronizationFailed false his inPause false 91 GL FIXME XXX This method needs to be review and simplified For each HlaPublisher actors deployed in the model we declare to the HLA CERTI Federation a HLA attribute to publish 1 Set classHandle and objAttributeHandle ids for each attribute value to publish i e HlaPublisher Update the HlaPublishers table with the information Iterator lt Entry lt String Object gt gt it _hlaAttributesToPublish entrySet iterator while it hasNext Map Entry lt String Object gt elt Map Entry it next Object t0bj Object elt getValue Object class handle and object attribute handle are ids that allow to identify an HLA attribute int classHandle rtia getObjectClassHandle String t0b3 2 int objAttributeHandle rtia getAttributeHandle TypedIOPort tObj 0 getContainer getName classHandle Update HLA a
121. ntext 1 Build Path gt Z Configure Build Path Refactor XST K M ss Import r Export 3 Refresh F5 Close Project Close Unrelated Projects Validate Show in Remote Systems view Profile As K Debug As K s C E Markers X ES Properties 1 Servers WW Data Source Explorer 5 Snippets vocum Com pare With 100 errors 13 288 warnings 2 058 others Filter matched 200 of 15446 items Resource Path Location Type onde from Local History gt Java Problems 100 of 13388 items Pa igure E gt Java Task 100 of 2058 items urce Properties sel _ _ _ a Figure B 7 Resolve JCERTI interface dependencies in ptII 1 57 Its Project Explorer 23 amp Java Build Path line 33 El Task List a P Resource Builders Libraries as JARs and class folders on the build path b Java Compiler gt us antlr jar ptil ptolemy actor ptalon antlr L AddJAR eds f gt o bsh 2 0b4 jar ptll lib Pone rece K L Sre er Project References Run Debug Setings gt a jasminclasses ar ptio Ad variable K os java_cup jar ptll lib gt sud jdom jar ptll ptolemy domains ptinyos lib Add Library K fag jini core jar ptll ptolemy distributed jini jar b Validation og jini ext jar ptll ptolemy distributed jini jar Add Class Folder WikiText gt os junit 4 8 2 jar ptll lib ns JUnitParams 0 3 0 jar ptll lib Add Externa
122. o advance to Result currentTime granted time to advance to given by the RTI call NER t or TAR t while not TAG tg do if RAV val t then store val t Y lt tg lt t end Data t next time to advance to Result currentTime granted time to advance to given by the RTI call NERA t or TARA t while not TAG tg do if RAV val t then store val t t lt tg lt t end end end set currentTime lt tg for number of NERA or TARA needed do Algorithm 2 HLA time advancement TAR or NER call VERA tg or TARA tg services while not TAG tg do if RAV val tg then store val tg end end end call NER tg or TAR tg while not TAG tg do if RAV val tg then store val tg end end set current Time lt tg Algorithm 3 HLA time advancement NERA services TARA and 4 3 3 Repeatability The second category of requirements is about the repeatability in distributed simulation presented in section 2 We remind below the definition of repeatability in HLA Definition 2 A distributed simulation is said to be repeatable if successive executions utilizing the same inputs produce exactly the same outputs 6 According to HLA the RTI helps to support repeatability to the extent that it enables repeatable ordering of simultaneous events but random number floating point etc need to be handle by the user i e remains to the federate implementation A part of the repeatability
123. of the time advancement request to the proposeTime value the HlaManager waits the re sponse TAG condition of the federation by ticking the rtig The ticking operation is an active loop which is broken at the the TAG reception During this phase each event sent from another federate to the Ptolemy federate is delivered through the execution of a reflectedAttribute Values RAV callback implemented by the FederateAm bassador service At the reception of a RAV callback each HLA event e g an updated attribute value is converted to a Ptolemy event DE Event or token The DE Event is automatically merged to the DE Queue opaque operation from the Ptolemy framework and the token associated to this event needs to be stored in its HlaSubscriber destinatory When the TAG condition is validated the ticking loop is broken each token produced from RAV is stored in its corresponding HLASubscriber actor This mecanism is implemented in the _putReflectedAttributesOnHlaSUb scribers method Finally the timestamp associated to the TAG is returned to the director as the time to advance to 5 3 5 2 Event based federates Ptolemy DE model owns a logic of event based simulation execution Timestamped events are produced and deliv ered at a specific point in time modeling the progression of the simulation Most of the time it is quite natural for the user to choose the use of HLA event based time advancement mecanisms NER and NERA to design
124. oken boolean initialize PopulateHlaAttributeTables preInitialize putReflectedAttributesOnHlaSubscribers propose Time Time update HlaAttribute wrapup Figure 5 2 Simplified class diagram of the HlaManager attribute 5 3 2 Initialization The Initialization service is composed of two methods preinitialize and initialize that belongs to the Ptolemy attribute core specification see class diagram figure 5 2 The preinitialize method implements the calls to the ptolemy apps hlacerti lib CertiRtig API to initiate the launch of the rtig process related to operation 6 The initialize method is dedicated to the initialization of the Ptolemy federate and performes different tasks First it calls the _populateHlaAttributeTables method which configures and populates the routing tables for the HlaPublisher and HlaSubscriber actors These tables are used to allow a HlaManager attribute to interact with the different actors deployed in the Ptolemy model The second task is a set of calls to the JCERTI bindings i e HLA services for the creating and the initialization of the rtia This instantiated object provided by the FederateA mbassador service acts as proxy for the communication between the federate and the RTI and implements the different callbacks required by a Ptolemy federate The third task is the initialization of the different timing values as start time time step and lookahead for the Pto
125. opose the algorithm 4 Algorithms 1 2 and 3 are reminders of the initial time advancement algorithms for a Ptolemy DE model and an HLA federation using TAR NER NERA or TARA services 4 3 2 Interoperability Requirements that belong to the interoperability s category are relatives to the simulation interface between a Ptolemy DE federate and a HLA simulation The requirements presented below are a refinement of those presented in paper HLArequirements adapted for the needs of our co simulation framework Thus a Ptolemy federate DE model must have or provide e RI Ability to initialize the distributed simulation prior to simulation execution e R2 Ability to block the simulation execution e R3 Access to the time of the next event to be simulated e R4 Ability to introduce new events from an external source into the event list 20 VAL1 11 L L VAL2 11 L Ptolemy DE Federate 1 Federate1Cal Queue process a at 2 process b at 5 receive VAL2 at 114L process VAL2 at 11 L UAV VAL2 11 L L process c at 20 NER lookahead gt 0 NER 2 TAG 2 t20 Ptolemy DE VAL1 11 L L Federate 2 HLA RTI VAL2 11 L u 2 TAG 2 Federate2 process u at 2 Cal Queue NER 11 TAG 11 process VAL2 at 11 UAV VAL2 11 L UAV VAL2 11 L NER 20 11 L RA lo tae ape receive RAV VAL1 11 L L TAG 11 L L process VAL1 at 11 L L 11 L L NER 20 TAG 20 TAG 20 process t at 20 Req
126. pTime 4 a C2 consumer P3 producer P3 producer ay DiscreteClock 1 E fs Bo HlaPublisher gs a Centralized model b Hla actors c Naming the actors d flat federate Figure A 1 Building Ptolemy federates Consider that you want to create the producer federate The steps are the following 1 Create a FOM file with the classes and attributes used in the simulation as in figure A 2 c 2 Duplicate the model of figure A 1 a removing all the blocs except the composite actor P3 producer 45 Drag the actors HlaManager and HlaPublisher from MoreLibrairies gt Co Simulation gt HLA see figure A 1 b Configuring HlaPublisher Connect the output of the composite actor to the HlaPublisher actor then a right click on HlaPublisher Configure Rename and put val the name of the class attribute in the fed file as in figure A 2 a in the field name the name displayed will be the same figure A 1 c b double click HlaPublisher the window of figure A 2 b pops out and put MyOb jectClass the name of the class according to your fed file in figure A 2 c in the parameter Object class in FOM Configuring HlaManager Double click this actor the window in figure A 2 d appears Put the name of the federation and the federate as in the fed file figure A 2 c and browse the fed file You can change the lookahead value If you need a synchronization point tick the field Require synchronizationPoint and choose a same name for
127. por impor impor import impor impor import impor impor impor import import impor impor impor import impor impor impor import import impor impor impor import import impor impor impor import impor impor impor import import impor impor impor import impor impor impor import import impor impor hla hla hla hla hla hla hla hla hla hla hla hla hla hla hla hla hla hla hla hla ava ava ava Voce rp Ge npe CE de C sss Ceres ae E A ee ava ava ava ava ava util util It util ava ava ava ava ava ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy ptolemy rti ObjectClassNotSubscribed ObjectNotKnown OwnershipAcquisitionPending RTIambassador rbd rti rti rti rti pbi rti LT rti rti rti rt rti rti rti rti rti rbi rti io io io io io RTIi nternalError ReflectedAttributes Resi Rest gnAction orsinProgress SavelInProgress SpecifiedSaveLabelDoesNotExist SuppliedAttributes SynchronizationLabelNotAnnounced TimeAdvanceAlreadyInProgress TimeAdvanceWasNotInProgress TimeConstrainedAlreadyEnabled TimeRegulat
128. r At this step we are sure that the HLA logical time of the Federate has been updated by the reception of the TAG callback timeAdvanceGrant and its value is the proposedTime or less so we have a breakpoint time try breakpoint new Time _director CertiLogicalTime _federateAmbassador logicalTimeHLA getTime catch IllegalActionException e throw new IllegalActionException this e 80 The breakpoint time is not a valid Ptolemy time Stored reflected attributes as events on HLASubscriber actors putReflectedAttributesOnHlaSubscribers GL FIXME XXX if _useNextEventRequest if _debugging _debug this getDisplayName proposeTime call CERTI NER nextEventRequest breakpoint try _rtia nextEventRequest _federateAmbassador logicalTimeHLA catch Exception e throw new IllegalActionException this e CERTI Exception _federateAmbassador timeAdvanceGrant false while _federateAmbassador timeAdvanceGrant if _debugging _debug this getDisplayName proposeTime wait CERTI TAG tick2 is called try _rtia tick2 catch Exception e throw new IllegalActionException this e CERTI Exception _putReflectedAttributesOnHlaSubscribers end patch _lastProposedTime breakpoint return breakpoint Update the HLA attribute lt i gt attributeName lt i gt with t
129. r needs to be placed In order for continuous actors to read signals generated in the DE MoC a ZeroOrderHold actor is used 15 The next sub section presents the semantics of the Ptolemy entities involved in our approach 14 3 2 Ptolemy s entities semantics 3 2 1 Actor An actor executes in three phases a setup phase a sequence of iterations and a wrapup phase as represented in Figure 3 2 setup iterate wrapup f i i i i 1 i i y gt 1 i 1 i i e gt i Figure 3 2 Actor s lifecycle in Ptolemy H The setup phase of an actor is divided in two sub phases preinitialize and initialize The preinitialize sub phase is performed once at the beginning of a simulation It specifies actions that may modify or influence the actor architecture and consequently impact static analysis as well as resource deployment composite actors may require the instantiation of internal actors type resolution schedulability etc The initialization sub phase initializes parameters resets local state and sends initial messages on output ports An iteration is a sequence of operations that read input data produce output data and update the state It is divided in three sub phases prefire fire and postfire The prefire optionally allows the verification of preconditions to ensure that the actor will complete the iteration The fire sub phase typically performs the computation of the actor In this sub phase input data from ports i
130. rability between a Ptolemy federate model and the HLA federation This HLA Manager will also provide a configuration interface to tune the time management services required by the user This interface will also allow the specification of others HLA information such as the name of the federate the name of the federation etc This manager will also be responsible of the management of RAV callbacks received from the federation and leading to store a new event in the Ptolemy model and to inject this event in the DE queue Two specific actors UAV and RAV Asin HLA UAV and RAV are distinct services not executed at the same level UAV during the computation phase of the federate and RAV during the time advancement phase we propose to implement two actors that allow or trigger these operations The configuration of these actors will also specify the information relative to identify the HLA attribute to publish or to subscribe to name and type For example the event send to the input port of the UAV may trigger the UAV service implemented in the HLA manager A more complex mecanism is required for the RAV actors RAV needs to be handled by the HLA manager Ptolemy events produced from a RAV may be stored in its corresponding RAV actor and send through the output port of this actor at its timestamp This mecanism may be implemented using the fireAt method of an actor to program a re firing time of the actor 24 Data queue the DE calendar queue Result
131. ribes the different steps to configure install and deploy the CERTI environment for the co simulation PtolemyII HLA CERTI 3 1 Requirements We assume that you are already familliar with the use of basic UNIX commands such as cp mv pwd and the edition of path and global variables The following tools are required to set the environment for the co simulation framework e CMAKE 2 8 10 or later an cross platform open source build system used by CERTI 3 2 AYA OB CO Get the las CVS 1 12 13 or later or git open source version control used by CERTI Lex and Yacc GNU Bison 2 3 or later syntactic analyzer generator used by CERTI ANT 1 8 3 or later a pure java build tool used to compile the JCERTI jar Eclipse an open source IDE mostly provided in Java which aims to provide an universal toolset for develop ment The framework has been tested using Juno or Kepler version of this tool Ptolemy is built on the top of Eclipse A C compil er GCC 4 3 2 or later used to compile CERTI JCERTI Installation process Go to HOM Open a terminal and create a folder named pthla at your home directory E pthla cvs z3 d t CERTI cvs source pserver anonymous cvs savannah nongnu org sources certi co certi Create the folder SHOME pthla certi tools Go to the HOME pthla certi folder downloaded at step 2 Create the folder HOME pthla certi build certi Go to folder SHOME pthl
132. ript myCERTI env sh In a new terminal source myCERTI env sh Run the billard program billard n 1 fTest Ftest fed 5 You can run other instances of this federate in other windows just change the name from 1 to another number After run the last instance go back to the windows where you run billard 1 for starting the simulation 1 2 Run rtig 3 4 You can set the debug mode for the billard demo doing export BILLARD DI 3 4 Enable the Debug mode CERTI allows to display traces i e messages exhanged between RTIG RTIA and federate These traces are enabled by setting environment variables in the the terminal where the RTIG or the federate is launched To enable messages exchanged between RTIA lt gt RTIG run in the RTIG terminal 50 export RTIG_MSG D To enable messages exchanged between Federate lt gt RTIA run in a Federate terminal export RTIA MSG I 4 Installation of the JCERTI interface This section describes the procedure to install and deploy the JCERTI interface in Eclipse We remind that JCERTI is a Java bindings for CERTI Remark After revision r71518 Ptolemy comes with jcerti jar 4 1 Installation process 1 Open a terminal and go to S HOME pthla 2 Get the last JCERTI cvs source cvs z3 d pserver anonymous cvs savannah nongnu org sources certi co jcerti 3 Go to the SHOME pthla jcerti folder downloaded at step 2 4 Run ant After the step 4 the sources of
133. s synchronized to others Federates using the same synchronization point in the HLA Federation El public void federationSynchronized String synchronizationPointLabel throws FederateInternalError inPause false if _debugging _debug HlaManager this getDisplayName INNER federationSynchronized inPause inPause 99
134. s read data is processed and output data is produced on output ports An actor may have persistent state that evolves during execution Finally the wrapup phase performs the correct termination of the actor An actor comes with a set of primitive communication operations which allow to retrieve information from the communication channels get method or send information to the channels put method As the meaning of the communication is determined by the director the connection between the external port of a composite actor and some other port on the outside will obey the semantics of the director on the outside For example in figure 3 1 the three composite actors must send receive data obeying DE semantics imposed by the DE top level director 3 2 2 Attribute Attributes are used to store parameters and access them anywhere in the model The attribute s lifecycle is similar to the actor s one but contains only the setup and wrapup phases Thus an attribute can be used to statically or dynamically parameterize a model 3 2 3 Decorator Some actors and some attributes are implemented as so called decorators These entities can decorate other Ptolemy entities e g model actors etc with specific information in an aspect oriented way Any number of attributes can be attached to a Ptolemy entity The remainder of this paper explains how a specific attribute may be designed to enable the time synchronization between both Ptolemy and
135. s required for the different operations supported HlaManager architecture M n Initialization Ptolemy attribute JCERTI Wrapup TimeRegulator FederateAmbassador Ptolemy data CERTI TimeManagement Ptolemy Data wrapper UAV ptolemy apps hlacerti services Figure 5 1 Architecture of the HlaManager attribute The figure 5 2 describes a subset of those methods based on a class diagram For more information the reader may refer to the the ptolemy apps hlacerti javadoc or to the HlaManager java class given in Annex C 3 These services are detailed in the following lInttp sisyphus eecs berkeley edu 8079 hudson job pt11 javadoc ptolemy apps hlacerti lib package frame html 29 NameObj T Initializable Attribute A 1 i PtolemyFederateAmbassadorlnner I logicalTimeHla LogicalTime announceSynchronizationPoint discoverObjectInstance federationSynchronized TimeRegulator initialize initializeTimeValues reflectAttributesValues synchronizationPointRegistrationFailed synchronizationPointRegistrationSucceed proposeTime Time timeAdvanceGrant LogicalTime timeConstrainedEnabled LogicalTime timeRegulationEnabled LogicalTIme attributedChanged decodeHlaValue Type byte clone encodeHlaValue T
136. scenario the behavior of the co simumation is different according to the time management services TAR NER TARA or NERA used by a federate 4 2 2 Main behavior The entrypoint is a request of time advancement made by the DE director of a Ptolemy federate When the director consults its calendar queue and takes a new event to process i e select the next actor to be fired we perform a time advance request to the federation using one of the semantics NER TAR NERA or TARA provided by HLA The timestamp of the next DE event to process is used as the time to advance to i e the parameter of the HLA request During this phase the DE director execution is blocked because of the active waiting loop as described in section 2 implemented to wait the TAG callback from the RTI i e the granted time to advance to authorized by the RTI The RAV callbacks are received during the execution of the loop At the reception of a TAG callback the execution of the DE director is released and the timestamp of the TAG is returned to the director as the time to advance to 1A local event is an event that is neither published to the federation nor received from the federation 19 The table in fig 4 2 summarizes the results of the execution of the co simulation for the events VAL1 and VAL2 exchanged between both federates via the federation when using the different time advancement algorithms TAR NER TARA NERA The use of the NERA or TARA services
137. sures the delivery of the timed event at the correct time in the Ptolemy simulation A subscription operation is enabled by connecting the H1aSubscriber s output port to an input port of a Ptolemy sink actor of the core library 41 Chapter 0 Conclusion and perspectives In this work we propose a co simulation framework for complex heterogeneous systems such as encountered in Cyber Physical systems Topics addressed in this work are different notions of time across distributed components time coordination communication latencies co simulation of heterogeneous components and interoperability of different simulation environments This approach discusses the distributed simulation capabilities of HLA CERTI and describes how the simulation tool Ptolemy was extended in order to interact with HLA The extensions in Ptolemy although specific to the tool can be generalized for arbitrary simulation tools The framework presented here is a joint work between CHESS UCB and DISC ISAE and allows the design of complex simulations containing several different simulation models as well as simulation tools functional source code executed on specific embedded platforms and hardware Up to now the caractheristics of a Ptolemy HLA federate are the following e the top model of a Ptolemy HLA federate must have a DE director Models with a Continuous director can also be simulated provided they are encapsulated in a composite actor e aPtolemy HLA federate is
138. t id of the object class handle tObj 4 gt id of the attribute handle tObj 0 2 are extracted from the Ptolemy model tobj 3 4 are provided by the RTI CERTI All these information are required to subscribe to unsubscribe to a HLA attribute elt setValue new Object tObj 0 tObj 1 tob3 2 classHandle objAttributeHandle 2 Create a table of HlaSubscribers indexed by their corresponding object class handle no duplication HashMap lt String LinkedList lt String gt gt classHandleHlaSubscriberTable null classHandleHlaSubscriberTable new HashMap lt String LinkedList lt String gt gt Iterator lt Entry lt String Object gt gt it4 _hlaAttributesSubscribedTo entrySet iterator while it4 hasNext Map Entry lt String Object gt elt Map Entry it4 next Object t0bj Object elt getValue The object class name of the HLA attribute see FOM String classHandleName String t0b3 2 if classHandleHlaSubscriberTable containsKey classHandleName classHandleHlaSubscriberTable get classHandleName add elt getKey else LinkedList lt String gt list new LinkedList lt String gt list add elt getKey classHandleHlaSubscriberTable put classHandleName list 3 Declare to the Federation the HLA attributes to subscribe to Iterator lt Entry lt String LinkedList lt String gt gt gt it5 classHandleHlaSubscriberTable
139. t p gt l ol B gA updateHlaAttribute String Token Bool hlaentities xml The link HlaManager attribute handles the time synchronization between B 19 A wrapup void X HlaManagericon xml Ptolemy model time and HLA logical time by implementing the link TimeRegulator amp o hlaAttributesToPublish HashMap St X HlaPublisherlcon xml interface It also manages objects that implement interfaces provided by El H dosi Xj HlaSubscriberlcon xml B makefile Eli Markers X ES Properties 4 Servers W Data Source Explorer 5 Snippets Yong E package html 100 errors 13 288 warnings 2 058 others Filter matched 200 of 15446 items E README txt Resource Path Location Type gt EB ptolemy apps hlacerti lib test gt Java Problems 100 of 13388 items gt i ptolemy apps hlacerti lib test junit bJava Task 100 of 2058 items gt ES ptolemy backtrack gt E ptolemy backtrack automatic gt E ptolemy backtrack automatic ptolemy gt 8 ptolemy backtrack automatic ptolemy actor lit gt E ptolemy backtrack automatic ptolemy configs gt 8 ptolemy backtrack automatic ptolemy domain The import hla cannot be resolved Writable Smart Insert 128 1 Figure B 6 Compilation errors for the HlaManager java in pT 3 Project Explorer 23 NECI D GE Outline X E Task List B ee An outline is not available New K Go Into Show In xw gt Copy C Es Copy Qualified Name Paste BV X Delete Remove from Co
140. tart the loop with one TARA call if debugging _rtia timeAdvanceRequestAvailable certiProposedTime Wait the grant from the HLA CERTI Federation from the RTI _federateAmbassador timeAdvanceGrant false while _federateAmbassador timeAdvanceGrant if _debugging Ey d ftratrck2 y catch Exception e throw new Exception reason End the loop with one TAR call if _debugging _rtia timeAdvanceRequest certiProposedTime catch Exception e throw new Exception reason if _debugging return proposedTime Wait the grant from the HLA CERTI Federation from the RTI _federateAmbassador timeAdvanceGrant false while _federateAmbassador timeAdvanceGrant if _debugging try tias Picks hy catch Exception e throw new Exception reason At this step we are sure that the HLA logical time of the Federate has been updated by the reception of the TAG callback timeAdvanceGrant and its value is the proposedTime or less so we have a breakpoint time try breakpoint new Time _director CertiLogicalTime _federateAmbassador logicalTimeHLA getTime catch Exception e throw new Exception reason Stored reflected attributes as events on HLASubscriber actors putReflectedAttributesOnHlaSubscribers lastProposedTime breakpoint return breakpoint 34 After the execution
141. ted e throw new IllegalActionException this e ConcurrentAccessAttempted Initialize the Federate Ambassador try _federateAmbassador initialize _rtia catch NameNotFound e throw new IllegalActionException this e NameNotFound catch ObjectClassNotDefined e throw new IllegalActionException this e ObjectClassNotDefined catch FederateNotExecutionMember e throw new IllegalActionException this e FederateNotExecutionMember catch RTIinternalError e throw new IllegalActionException this e RTIinternalError catch AttributeNotDefined e throw new IllegalActionException this e AttributeNotDefined catch SavelnProgress e throw new IllegalActionException this e SavelnProgress catch RestorelnProgress e throw new IllegalActionException this e RestoreInProgress 73 catch ConcurrentAccessAttempted e throw new IllegalActionException this ConcurrentAccessAttempted Initialize Federate timing values _federateAmbassador initializeTimeValues _hlaStartTime hlaLookAHead Declare the Federate time constrained if isTimeConstrained try _rtia enableTimeConstrained cate n row new IllegalActionException t n row new IllegalActionException t n row new IllegalActionException t n row new IllegalActionException t n row new IllegalActionException t n row new Il
142. that HLA standard states that if the logical time of a federate is t then it only can send an UAV update attribute value with time t lookahead To avoid the federate at logical time f to send an event to the federation with timestamp and to get an exception from CERTI we choose to add an arbitrary e value to the timestamp f sending the value v at t with e lookahead The problem with this choice is that the event is sent with a delay instead of sending an event e v ts the federate will send e v t lookahead see listing 5 4 Time representation consistency In the framework the time representation consistency is simple JCERTI pro vides the CertiLogicalTime class to build a time representation value for HLA CERTI The CertiLogicalTime class is a rich encapsulation of a Java double The correct conversion of CertiLogicalTime java object to a CertiLogicalTime c object is ensured by JCERTI 36 In Ptolemy model time representation belongs to the ptolemy actor util Time object class This class is a rich encapsulation of a java math BigInteger which is very accurate to handle big time representation values The Time class provides converters such as the ptolemy actor util Time getDoubleValue with the limitation that the convertion may not preserve the time resolution because of the limited digits for double representation As the CertiLogicalTime supports only double we use this converter to convert a timestamp of a Ptolemy ev
143. the HlaManager 5 3 5 1 proposeTime The proposeTime method of the HlaManager time regulator attribute is given in listing 5 3 The time management is only effective if the Ptolemy federate is declared as constrained and regulator see our restrictions in chapter 4 The different steps described in the time advancement algorithm proposed in chapter 4 are easily distinguishable According to the configuration of the HlaManager set by the user the Ptolemy federate will execute one and only one of the four time advancement mecanisms during the simulation Listing 5 3 ptolemy apps hlacerti lib HlaManager proposeTime Propose a time to advance to This method is the one implementing the TimeRegulator interface and using the HLA CERTI Time Management services if required Following HLA and CERTI recommendations if the Time Management is required then we have the following behavior Case 1 If lookahead 0 a if time stepped Federate then the timeAdvanceRequestAvailable N TARA service is used b if event based Federate then the nextEventRequestAvailable NERA service is used Case 2 If lookahead gt 0 c if time stepped Federate then timeAdvanceRequest TAR is used d if event based Federate then the nextEventRequest NER is used Otherwise the proposedTime is returned NOTE For the Ptolemy II HLA CERTI cooperation the default and correct behavior is the
144. the JCERTI interface have been compiled and packaged in the java jar HOME pthla jcerti build jar jcerti jar 4 2 Deployment in Eclipse To import the jcerti jar in a Java project do Open Eclipse Right click on your java project Click on Build Path Configure Build Path In the new frame open select Libraries Click on Add External Archives Go to the HOME pthla jcerti build jar directory Select jcerti jar then Open Click on OK cO d C C1 4 WN RE After the step 8 if you have selected in the Eclipe s tab Project gt Build Automatically Eclipse will re compiled the source of your java project and resolved the dependencies with the JCERTI interface Otherwise you have to re compile your java project 5 Installation of the PtolemyII project More information for installing Ptolemy can be found at http chess eecs berkeley edu ptexternal 51 The Ptolemyll svn repository is now located at https repo eecs berkeley edu svn anon projects eal ptII trunkptII We recommend to create the HOME pthla workspace folder and to download using svn the pt II project in this folder 5 1 Shortcut to launch a Ptolemy model from Eclipse The Eclipse tool configured for the Ptolemy project and to run Vergil ptolemy s graphical editor needs to have access to the CERTI environment global variables binaries scripts etc At this step we assume that you have alr
145. the simulation model The actor s architecture is composed by e a set of parameters that allow to specify all the information required by HLA to subscribe to a HLA attribute value The mapping HlaSubscriber actor to HLA attribute is the same as the one describes for the HlaPublisher actor see section 5 4 1 e a set of internal variables The HlaSuscriber actor specifies a _reflectedAttribute Values data structure that implements an event queue This queue is used to store HLA events converted as Ptolemy events e a set of methods The public fire method is triggered by the director at a specific model time declared by the actor i e programmed through the call of the fireAt method executed by the actor The firing of a HlaSubscriber actor means that an event needs to be processed in its internal queue The processing of the event leads to the production of a token which is send through the output port of the actor The private build Token method is called by the fire method and is responsible of the construction of a typed token which matches the type of the corresponding HLA attribute specified by the user The public _putReflectedHlaAttribute method described in listing 5 6 is provided by the actor to the HlaManager This method is invoked during the time management phase to store all HLA events received from the federation converted as a Ptolemy event and which has the HlaSubscriber actor as destinatory This method stores
146. tionExecutionAlreadyExists e if _debugging _debug this getDisplayNanme initialize WARNING FederationExecutionAlreadyExists catch CouldNotOpenFED e throw new IllegalActionException this e CouldNotOpenFED catch ErrorReadingFED e throw new IllegalActionException this e ErrorReadingFED catch RTIinternalError e throw new IllegalActionException this e RTIinternalError catch ConcurrentAccessAttempted e throw new IllegalActionException this e ConcurrentAccessAttempted catch MalformedURLException e throw new IllegalActionException this e MalformedURLException _federateAmbassador new PtolemyFederateAmbassadorInner Join the Federation try rtia joinFederationExecution _federateName _federationName _federateAmbassador catch FederateAlreadyExecutionMember e throw new IllegalActionException this e FederateAlreadyExecutionMember catch FederationExecutionDoesNotExist e t o ct hrow new IllegalActionException FederationExecutionDoes his e EEXTSt 9 catch SavelnProgress e throw new IllegalActionException this e SavelnProgress catch RestoreInProgress e throw new IllegalActionException this e RestoreInProgress catch RTIinternalError e throw new IllegalActionException this e RTlinternalError catch ConcurrentAccessAttemp
147. tor Construct a HlaManager with a name and a container The container argument must not be null or a NullPointerException will be thrown This actor will use the workspace of the container for synchronization and version counts If the name argument is null then the name is set to the empty string Increment the version of the workspace param container Container of this attribute param name Name of this attribute exception IllegalActionException If the container is incompatible with this actor exception NameDuplicationException If the name coincides with an actor already in the container j public HlaManager CompositeEntity container String name throws IllegalActionException NameDuplicationException super container name _lastProposedTime null 67 _rtia null _federateAmbassador null _hlaAttributesToPublish new HashMap lt String Object gt _hlaAttributesSubscribedTo new HashMap lt String Object gt _fromFederationEvents new HashMap lt String LinkedList TimedEvent _objectIdToClassHandle new HashMap lt Integer Integer gt _hlaStartTime null _hlaTimeStep null _hlaLookAHead null HLA Federation management parameters federateName new Parameter this federateName federateName setDisplayName Federate s name federateName setTypeEquals BaseType STRING federateName setExpression HlaManager attributeChanged federate
148. tor isTimeRegulator setTypeEquals BaseType BOOLEAN isTimeRegulator setExpression true isTimeRegulator setDisplayName isTimeRegulator 2 attributeChanged isTimeRegulator hlaStartTime new Parameter this hlaStartTime hlaStartTime setDisplayName logical start time in ms hlaStartTime setExpression 0 0 hlaStartTime setTypeEquals BaseType DOUBLE attributeChanged hlaStartTime hlaTimeStep new Parameter this hlaTimeStep hlaTimeStep setDisplayName time step in ms hlaTimeStep setExpression 0 0 68 hlaTimeStep setTypeEquals BaseType DOUBLE attributeChanged hlaTimeStep hlaLookAHead hlaLookAHead new Parameter this hlaLookAHead setDisplayName lookahead in ms hlaLookAHead setExpression 0 0 hlaLookAHead setTypeEquals BaseType DOUBLE attributeChanged hlaLookAHead HLA Sync requireSync requireSync requireSync hronization hronization hronization hronization parameters new Parameter this requireSynchronization setTypeEquals BaseType BOOLEAN setExpression true requireSynchronization setDisplayName Require synchronization attributeChanged requireSynchronization EE synchronizationPointName new Parameter this synchronizationPointName synchronizationPointName setDisplayName Synchronization point name synchronizationPointName setTypeEquals BaseType STRING synchronizationPointName setExpression Simulati
149. tor lib jxta O L Cancel Finish 0 errors 13 285 warnings 2 039 others Filter matched 200 of 15324 items Description Resource Path Location Type K amp Java Problems 100 of 13285 items b Java Task 100 of 2039 items 2 pul Figure B 3 Inclusion and Exclusions Patterns of ptII 8 2 Running PtolemyII HLA CERTI simulation RTIA socket connection failed We have observed under some recent and powerful computers an issue involving Ptolemy federate and the RTIG process when launching a simulation the first time It appears that during the first launch the Ptolemy federate is not able to connect to the RTIG Our first investigation supposed that the Ptolemy federate running under Eclipse and using the JCERTI interface are not able to retrieve the RTIA socket It seems that the initialization and the creation of the RTIA process triggered by JCERTI interface used by the Ptolemy federate is slower than the execution of the federate The result of this issue is the RTIinternalError Connection to RTIA failed libRTI Network Read Error exception caught by Vergil see figure B 11 Due to the lack of time and resources we have not yet resolved this problem But a simple solution is to re launch the simulation Reflected HLA attribute value using CERTI Message Buffer When using the CERTI Message Buffer option with HLA actors if an HlaSubscriber actor tries to un wrapp an reflected value of HLA attribute rec
150. ts getDoubleValue te System out println RAV has to decode asHlaPtidesEvent System out println RAV logicalTime he getLogicalTime System out println RAV srcTimeStamp he getSourceTime System out println RAV time of RAV ts getDoubleValue else ts new Time _director CertiLogicalTime theTime getTime te new TimedEvent ts new Object BaseType tObj 1 _decodeHlaValue BaseType tObj 1 theAttributes getValue i catch IllegalActionException e e printStackTrace _fromFederationEvents get TypedIOPort getName add te if debugging d be he getSourceTime theTime Object l tObj 1 0 E PTIDES should be gicalTime eValue Step E PTIDES eTime should be tObj 0 getContainer _debug HlaManager this getDisplayName INNER HLA attribute timestamp n catch ArrayIndexOutOfBounds e e printStackTrace 96 reflectAttributeValues RAV TypedIOPort tObj 0 getContainer getName value te contents te timeStamp has been received Callback delivered by t of HLA attribute that t EY public void discoverObjectInstance int theObject String objectName he RTI CERTI to discover attribute instance he Federate is subscribed to int theObjectClass throws Cou
151. ttribute information for publication from HLA services In this case the tObj object as the following structure tObj 0 gt input port which receives the token to transform as an updated value of a HLA attribute tob3 1 gt type of the port e g of the attribute tObj 2 gt object class name of the attribute tobj 3 gt id of the object class to handle tObj 4 gt id of the attribute to handle tobj 5 gt id of the registered attribute s instance tob31 0 2 are extracted from the Ptolemy model tobj 3 5 are provided by the RTI CERTI All these information are required to publish unpublish updated value of a HLA attribute elt setValue new Object tObj 0 tObj 1 tob3 2 classHandle objAttributeHandle null 2 Create a table of HlaPublishers indexed by their corresponding classHandle no duplication HashMap lt String LinkedList lt String gt gt classHandleHlaPublisherTable null classHandleHlaPublisherTable new HashMap lt String LinkedList lt String gt gt j Iterator lt Entry lt String Object gt gt it2 _hlaAttributesToPublish entrySet iterator while it2 hasNext Map Entry lt String Object gt elt Map Entry it2 next Object t0bj Object elt getValue The classHandle where the HLA attribute belongs to see FOM String classHandleName String tObj 2 if classHandleHlaPublisherTable conta
152. ubscriberlcon xml E makefile package html README txt gt 3 ptolemy apps hlacerti lib test gt i ptolemy apps hlacerti lib test junit gt EH ptolemy backtrack D HlaManager java 2 jme amp This attribute implements a HLA Manager to cooperate with a HLA CERTI Federation package ptolemy apps hlacerti lib TODA ROA ARANA OA RDA AAA MM HMM RARAS WlaManager a a lt p gt This attribute implements a HLA Manager which allows a cooperate with a HLA CERTI Federation The main is to allow simulation as Federate of a Federation lt p gt lt p gt The High Level Architecture HLA 1 2 is a standard for distributed discrete event simulations A complex simulation in HLA is called a HLA t 79 5 g nmm kors each performing a sequence of computations interconnected by a Run Time Infrastructure RTI lt p gt lt p gt CERTI is an Open Source middleware RTI compliant with HLA NRS09 which manages every part of federation It also ensures a real time behavior of a federation execution CERTI is implemented in C and bindings are provided as JCERTI for Java and PyHLA for Python For more information see lt br gt lt a hrefe http savannah nongnu org projects certi target _top gt http savanr lt p gt lt p gt The link HlaManager attribute handles the time synchronization between my model time and HLA logical time by implementing the link TimeRegulator face It also manages objects t
153. uest to advance time to TAG granted time by the RTI UAV RAV Event processed by the sim L Lookahead t Logical time Figure 4 3 Synchronization model using NER and lookahead gt 0 e R5 Access to information of simulation object entities that are shared among federates Requirements R1 and R2 are defined because a federate needs to first join the simulation and then blocks its execution until all the other federates join before the simulation begins The requirement R3 is necessary to allow the utilisation of the NER service where the timestamp of the next event needs to be known Requirement R4 allows to handle new events received from other federates during the time advancement phase while the federate is blocked and waits the time grant These new events are merged into the DE calendar queue and handled as classical Ptolemy events When the control is returned to the federate i e when the DE director execution is released the events are simulated at their timestamp Finally the requirement R5 is about the access of the data structure of events exchanged between federates These information are required for building the correct representation of event s value in both simulators Data queue the calendar queue Result currentTime time to advance to select next event e t dest in queue set currentTime t process all events at t for actor dest Algorithm 1 Ptolemy DE time advancement 21 Data t next time t
154. uous model can be inserted as a composite actor in a DE top model using predefined actors that allow the interface between CT DE and vice versa see the demo 14 in the Ptolemy projec This is allowed by the hierarchical composition of Ptolemy models and specially between DE and CT domains presented in chapter 2 4 2 Time management As we pointed out in our motivation dealing with co simulation for distributed real time and embedded systems requires to make consistent the different notion of times logical time platform time and realtime involved in a simulation model a simulation implementation or the physical world In our case an event of the co simuation from Ptolemy as well as from HLA CERTI is a couple timestamp value where the timestamp represents a specific point in time of the logical time of the simulators The time management is a fundamental issue in our co simulation approach To make event s timestamp con sistent in both simulators i e in Ptolemy and HLA CERTI it is necessary to understand precisely when occurs a time advancement phase in both approaches These elements has already been presented in section 3 and section 2 and summarized in the introduction of this chapter 4 2 1 Synchronization models Figures 4 1 and 4 3 describe the synchronization models designed for the co simulation framework These syn chronization models respects stricly the semantics of time management proposed in Ptolemy and HLA CERTI The
155. which allows a Ptolemy model to cooperate with a HLA CERTI Federation The main is to allow a Ptolemy simulation as Federate of a Federation lt p gt lt p gt The High Level Architecture HLA 1 2 is a standard for distributed discrete event simulations A complex simulation in HLA is called a HLA Federation A Federation is a collection of Federates e g simpler simula tors each performing a sequence of computations interconnected by a Run Time Infrastructure RTI lt p gt lt p gt CERTI is an Open Source middleware RTI compliant with HLA NRS09 which manages every part of federation It also ensures a real time behavior of a federation execution CERTI is implemented in C and bindings are provided as JCERTI for Java and PyHLA for Python For more information see lt br gt lt a href http savannah nongnu org projects certi target _top gt http savannah nongnu org projects certi lt a gt lt br gt lt p gt lt p gt The link HlaManager attribute handles the time synchronization between Ptolemy model time and HLA logical time by implementing the link TimeRegulator interface It also manages objects that implement interfaces provided by JCERTI relatives to Federation Declaration Object and Time management areas in HLA each management areas provides a set of services lt p gt lt p gt To develop a HLA Federation it is required to specify a Federate Object Model FOM which describes the archite
156. y tool Even if our co simulation framework is integrated in Ptolemy the framework is not enabled by default because of the strong dependencies to the CERTI environment built on the user machine This means that the implementation files of the co simulation framework are not compiled with the Ptolemy project The implementation files are located in the ptII ptolemy apps hlacerti folder By default all files stored in this folder are excluded to the build of Ptolemy Figures B 1 to B 10 shows the steps to enable the compilation ptII ptolemy apps hlacerti sources in Ptolemy using Eclipse The first step is to remove the ptII ptolemy apps hlacerti folder in the exclusion rules of the build path of ptolemy Go to the Build Path interface of Ptolemy Configure Build Path in the Sources tab see figures B 1 and B 2 then select Excluded and click on Edit In the Exclusion patterns block select Add Multiple see figure B 3 In the Exclusion Pattern Selection frame select all folders in the ptII ptolemy apps folder except 52 the svn and the hlacerti folders click on Ok see figure B 4 In the same window in the Exclude frame see figure B 5 select ptII ptolemy apps and click on Remove Then click on Finish After this step Eclipse will try to re compile the ptII project Eclipse File Edit Navigate Search Project Run Window Help 142 A C 4 7 G90 1
157. yte tag EncodingHelpers encodeString TypedIOPort tObj 0 getContainer getName Create a representation of the current director time for CERTI HLA implies to send event in the future when using NER or TAR services with lookahead gt 0 To avoid CERTI exception when calling UAV service in the case of NER or TAR with lookahead gt 0 we add the lookahead value to the event s timestamp CertiLogicalTime ct new CertiLogicalTime currentTime getDoubleValue _hlaLookAHead try rtia updateAttributeValues Integer tObj 5 suppAttributes tag ct catch Exception e throw new IllegalActionException this e e getMessage if _debugging 37 5 4 HlaPublisher and HlaSubscriber actors Mecanisms and operations required to exchange data between a Ptolemy simulation models and a HLA CERTI Federation are realized across the development of two Ptolemy actors so called H1aPublisher and HlaSubscriber Both actors belongs to the ptolemy apps hlacerti library and are combined with the H1aManager to enable the co simulation PtolemyII HLA CERTI According to their semantics actors express all the behavior characteristics that are required to implement the followings operations e send send a Ptolemy event to a HLA CERTI Federation according to its timestamp and with respect to the Ptolemy event processing semantics e receive receive HLA CERTI events and process them at timestamp in a ptole
Download Pdf Manuals
Related Search
Related Contents
BoConcept Model 2930 Assembly Instruction Mobilis 14" Theone twice GX形ダクタイル鉄管用 管端防食キャップ Istruzioni ECCM42 TAFCO WINDOWS NU2-034S-I Installation Guide 資料7-1 (2)(PDF形式:57KB) 2015M-0 図面リスト Bedienungsanleitung Pro800 Samsung WM1255A Kullanıcı Klavuzu Copyright © All rights reserved.
Failed to retrieve file