Background: #fff
Foreground: #000
PrimaryPale: #8cf
PrimaryLight: #18f
PrimaryMid: #04b
PrimaryDark: #014
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88
<!--{{{-->
<div class='toolbar' macro='toolbar [[ToolbarCommands::EditToolbar]]'></div>
<div class='title' macro='view title'></div>
<div class='editor' macro='edit title'></div>
<div macro='annotations'></div>
<div class='editor' macro='edit text'></div>
<div class='editor' macro='edit tags'></div><div class='editorFooter'><span macro='message views.editor.tagPrompt'></span><span macro='tagChooser excludeLists'></span></div>
<!--}}}-->
To get started with this blank [[TiddlyWiki]], you'll need to modify the following tiddlers:
* [[SiteTitle]] & [[SiteSubtitle]]: The title and subtitle of the site, as shown above (after saving, they will also appear in the browser title bar)
* [[MainMenu]]: The menu (usually on the left)
* [[DefaultTiddlers]]: Contains the names of the tiddlers that you want to appear when the TiddlyWiki is opened
You'll also need to enter your username for signing your edits: <<option txtUserName>>
<<importTiddlers>>
<!--{{{-->
<link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml' />
<!--}}}-->
These [[InterfaceOptions]] for customising [[TiddlyWiki]] are saved in your browser

Your username for signing your edits. Write it as a [[WikiWord]] (eg [[JoeBloggs]])

<<option txtUserName>>
<<option chkSaveBackups>> [[SaveBackups]]
<<option chkAutoSave>> [[AutoSave]]
<<option chkRegExpSearch>> [[RegExpSearch]]
<<option chkCaseSensitiveSearch>> [[CaseSensitiveSearch]]
<<option chkAnimate>> [[EnableAnimations]]

----
Also see [[AdvancedOptions]]
<!--{{{-->
<div class='header' role='banner' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'>
<div class='headerShadow'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
<div class='headerForeground'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
</div>
<div id='mainMenu' role='navigation' refresh='content' tiddler='MainMenu'></div>
<div id='sidebar'>
<div id='sidebarOptions' role='navigation' refresh='content' tiddler='SideBarOptions'></div>
<div id='sidebarTabs' role='complementary' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea' role='main'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
/*{{{*/
body {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}

a {color:[[ColorPalette::PrimaryMid]];}
a:hover {background-color:[[ColorPalette::PrimaryMid]]; color:[[ColorPalette::Background]];}
a img {border:0;}

h1,h2,h3,h4,h5,h6 {color:[[ColorPalette::SecondaryDark]]; background:transparent;}
h1 {border-bottom:2px solid [[ColorPalette::TertiaryLight]];}
h2,h3 {border-bottom:1px solid [[ColorPalette::TertiaryLight]];}

.button {color:[[ColorPalette::PrimaryDark]]; border:1px solid [[ColorPalette::Background]];}
.button:hover {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::SecondaryLight]]; border-color:[[ColorPalette::SecondaryMid]];}
.button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::SecondaryDark]];}

.header {background:[[ColorPalette::PrimaryMid]];}
.headerShadow {color:[[ColorPalette::Foreground]];}
.headerShadow a {font-weight:normal; color:[[ColorPalette::Foreground]];}
.headerForeground {color:[[ColorPalette::Background]];}
.headerForeground a {font-weight:normal; color:[[ColorPalette::PrimaryPale]];}

.tabSelected {color:[[ColorPalette::PrimaryDark]];
	background:[[ColorPalette::TertiaryPale]];
	border-left:1px solid [[ColorPalette::TertiaryLight]];
	border-top:1px solid [[ColorPalette::TertiaryLight]];
	border-right:1px solid [[ColorPalette::TertiaryLight]];
}
.tabUnselected {color:[[ColorPalette::Background]]; background:[[ColorPalette::TertiaryMid]];}
.tabContents {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::TertiaryPale]]; border:1px solid [[ColorPalette::TertiaryLight]];}
.tabContents .button {border:0;}

#sidebar {}
#sidebarOptions input {border:1px solid [[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel {background:[[ColorPalette::PrimaryPale]];}
#sidebarOptions .sliderPanel a {border:none;color:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:hover {color:[[ColorPalette::Background]]; background:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:active {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::Background]];}

.wizard {background:[[ColorPalette::PrimaryPale]]; border:1px solid [[ColorPalette::PrimaryMid]];}
.wizard h1 {color:[[ColorPalette::PrimaryDark]]; border:none;}
.wizard h2 {color:[[ColorPalette::Foreground]]; border:none;}
.wizardStep {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];
	border:1px solid [[ColorPalette::PrimaryMid]];}
.wizardStep.wizardStepDone {background:[[ColorPalette::TertiaryLight]];}
.wizardFooter {background:[[ColorPalette::PrimaryPale]];}
.wizardFooter .status {background:[[ColorPalette::PrimaryDark]]; color:[[ColorPalette::Background]];}
.wizard .button {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryLight]]; border: 1px solid;
	border-color:[[ColorPalette::SecondaryPale]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryPale]];}
.wizard .button:hover {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Background]];}
.wizard .button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::Foreground]]; border: 1px solid;
	border-color:[[ColorPalette::PrimaryDark]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryDark]];}

.wizard .notChanged {background:transparent;}
.wizard .changedLocally {background:#80ff80;}
.wizard .changedServer {background:#8080ff;}
.wizard .changedBoth {background:#ff8080;}
.wizard .notFound {background:#ffff80;}
.wizard .putToServer {background:#ff80ff;}
.wizard .gotFromServer {background:#80ffff;}

#messageArea {border:1px solid [[ColorPalette::SecondaryMid]]; background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]];}
#messageArea .button {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::SecondaryPale]]; border:none;}

.popupTiddler {background:[[ColorPalette::TertiaryPale]]; border:2px solid [[ColorPalette::TertiaryMid]];}

.popup {background:[[ColorPalette::TertiaryPale]]; color:[[ColorPalette::TertiaryDark]]; border-left:1px solid [[ColorPalette::TertiaryMid]]; border-top:1px solid [[ColorPalette::TertiaryMid]]; border-right:2px solid [[ColorPalette::TertiaryDark]]; border-bottom:2px solid [[ColorPalette::TertiaryDark]];}
.popup hr {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::PrimaryDark]]; border-bottom:1px;}
.popup li.disabled {color:[[ColorPalette::TertiaryMid]];}
.popup li a, .popup li a:visited {color:[[ColorPalette::Foreground]]; border: none;}
.popup li a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border: none;}
.popup li a:active {background:[[ColorPalette::SecondaryPale]]; color:[[ColorPalette::Foreground]]; border: none;}
.popupHighlight {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
.listBreak div {border-bottom:1px solid [[ColorPalette::TertiaryDark]];}

.tiddler .defaultCommand {font-weight:bold;}

.shadow .title {color:[[ColorPalette::TertiaryDark]];}

.title {color:[[ColorPalette::SecondaryDark]];}
.subtitle {color:[[ColorPalette::TertiaryDark]];}

.toolbar {color:[[ColorPalette::PrimaryMid]];}
.toolbar a {color:[[ColorPalette::TertiaryLight]];}
.selected .toolbar a {color:[[ColorPalette::TertiaryMid]];}
.selected .toolbar a:hover {color:[[ColorPalette::Foreground]];}

.tagging, .tagged {border:1px solid [[ColorPalette::TertiaryPale]]; background-color:[[ColorPalette::TertiaryPale]];}
.selected .tagging, .selected .tagged {background-color:[[ColorPalette::TertiaryLight]]; border:1px solid [[ColorPalette::TertiaryMid]];}
.tagging .listTitle, .tagged .listTitle {color:[[ColorPalette::PrimaryDark]];}
.tagging .button, .tagged .button {border:none;}

.footer {color:[[ColorPalette::TertiaryLight]];}
.selected .footer {color:[[ColorPalette::TertiaryMid]];}

.error, .errorButton {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Error]];}
.warning {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryPale]];}
.lowlight {background:[[ColorPalette::TertiaryLight]];}

.zoomer {background:none; color:[[ColorPalette::TertiaryMid]]; border:3px solid [[ColorPalette::TertiaryMid]];}

.imageLink, #displayArea .imageLink {background:transparent;}

.annotation {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border:2px solid [[ColorPalette::SecondaryMid]];}

.viewer .listTitle {list-style-type:none; margin-left:-2em;}
.viewer .button {border:1px solid [[ColorPalette::SecondaryMid]];}
.viewer blockquote {border-left:3px solid [[ColorPalette::TertiaryDark]];}

.viewer table, table.twtable {border:2px solid [[ColorPalette::TertiaryDark]];}
.viewer th, .viewer thead td, .twtable th, .twtable thead td {background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::Background]];}
.viewer td, .viewer tr, .twtable td, .twtable tr {border:1px solid [[ColorPalette::TertiaryDark]];}

.viewer pre {border:1px solid [[ColorPalette::SecondaryLight]]; background:[[ColorPalette::SecondaryPale]];}
.viewer code {color:[[ColorPalette::SecondaryDark]];}
.viewer hr {border:0; border-top:dashed 1px [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::TertiaryDark]];}

.highlight, .marked {background:[[ColorPalette::SecondaryLight]];}

.editor input {border:1px solid [[ColorPalette::PrimaryMid]];}
.editor textarea {border:1px solid [[ColorPalette::PrimaryMid]]; width:100%;}
.editorFooter {color:[[ColorPalette::TertiaryMid]];}
.readOnly {background:[[ColorPalette::TertiaryPale]];}

#backstageArea {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::TertiaryMid]];}
#backstageArea a {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstageArea a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; }
#backstageArea a.backstageSelTab {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
#backstageButton a {background:none; color:[[ColorPalette::Background]]; border:none;}
#backstageButton a:hover {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstagePanel {background:[[ColorPalette::Background]]; border-color: [[ColorPalette::Background]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]];}
.backstagePanelFooter .button {border:none; color:[[ColorPalette::Background]];}
.backstagePanelFooter .button:hover {color:[[ColorPalette::Foreground]];}
#backstageCloak {background:[[ColorPalette::Foreground]]; opacity:0.6; filter:alpha(opacity=60);}
/*}}}*/
/*{{{*/
* html .tiddler {height:1%;}

body {font-size:.75em; font-family:arial,helvetica; margin:0; padding:0;}

h1,h2,h3,h4,h5,h6 {font-weight:bold; text-decoration:none;}
h1,h2,h3 {padding-bottom:1px; margin-top:1.2em;margin-bottom:0.3em;}
h4,h5,h6 {margin-top:1em;}
h1 {font-size:1.35em;}
h2 {font-size:1.25em;}
h3 {font-size:1.1em;}
h4 {font-size:1em;}
h5 {font-size:.9em;}

hr {height:1px;}

a {text-decoration:none;}

dt {font-weight:bold;}

ol {list-style-type:decimal;}
ol ol {list-style-type:lower-alpha;}
ol ol ol {list-style-type:lower-roman;}
ol ol ol ol {list-style-type:decimal;}
ol ol ol ol ol {list-style-type:lower-alpha;}
ol ol ol ol ol ol {list-style-type:lower-roman;}
ol ol ol ol ol ol ol {list-style-type:decimal;}

.txtOptionInput {width:11em;}

#contentWrapper .chkOptionInput {border:0;}

.externalLink {text-decoration:underline;}

.indent {margin-left:3em;}
.outdent {margin-left:3em; text-indent:-3em;}
code.escaped {white-space:nowrap;}

.tiddlyLinkExisting {font-weight:bold;}
.tiddlyLinkNonExisting {font-style:italic;}

/* the 'a' is required for IE, otherwise it renders the whole tiddler in bold */
a.tiddlyLinkNonExisting.shadow {font-weight:bold;}

#mainMenu .tiddlyLinkExisting,
	#mainMenu .tiddlyLinkNonExisting,
	#sidebarTabs .tiddlyLinkNonExisting {font-weight:normal; font-style:normal;}
#sidebarTabs .tiddlyLinkExisting {font-weight:bold; font-style:normal;}

.header {position:relative;}
.header a:hover {background:transparent;}
.headerShadow {position:relative; padding:4.5em 0 1em 1em; left:-1px; top:-1px;}
.headerForeground {position:absolute; padding:4.5em 0 1em 1em; left:0; top:0;}

.siteTitle {font-size:3em;}
.siteSubtitle {font-size:1.2em;}

#mainMenu {position:absolute; left:0; width:10em; text-align:right; line-height:1.6em; padding:1.5em 0.5em 0.5em 0.5em; font-size:1.1em;}

#sidebar {position:absolute; right:3px; width:16em; font-size:.9em;}
#sidebarOptions {padding-top:0.3em;}
#sidebarOptions a {margin:0 0.2em; padding:0.2em 0.3em; display:block;}
#sidebarOptions input {margin:0.4em 0.5em;}
#sidebarOptions .sliderPanel {margin-left:1em; padding:0.5em; font-size:.85em;}
#sidebarOptions .sliderPanel a {font-weight:bold; display:inline; padding:0;}
#sidebarOptions .sliderPanel input {margin:0 0 0.3em 0;}
#sidebarTabs .tabContents {width:15em; overflow:hidden;}

.wizard {padding:0.1em 1em 0 2em;}
.wizard h1 {font-size:2em; font-weight:bold; background:none; padding:0; margin:0.4em 0 0.2em;}
.wizard h2 {font-size:1.2em; font-weight:bold; background:none; padding:0; margin:0.4em 0 0.2em;}
.wizardStep {padding:1em 1em 1em 1em;}
.wizard .button {margin:0.5em 0 0; font-size:1.2em;}
.wizardFooter {padding:0.8em 0.4em 0.8em 0;}
.wizardFooter .status {padding:0 0.4em; margin-left:1em;}
.wizard .button {padding:0.1em 0.2em;}

#messageArea {position:fixed; top:2em; right:0; margin:0.5em; padding:0.5em; z-index:2000; _position:absolute;}
.messageToolbar {display:block; text-align:right; padding:0.2em;}
#messageArea a {text-decoration:underline;}

.tiddlerPopupButton {padding:0.2em;}
.popupTiddler {position: absolute; z-index:300; padding:1em; margin:0;}

.popup {position:absolute; z-index:300; font-size:.9em; padding:0; list-style:none; margin:0;}
.popup .popupMessage {padding:0.4em;}
.popup hr {display:block; height:1px; width:auto; padding:0; margin:0.2em 0;}
.popup li.disabled {padding:0.4em;}
.popup li a {display:block; padding:0.4em; font-weight:normal; cursor:pointer;}
.listBreak {font-size:1px; line-height:1px;}
.listBreak div {margin:2px 0;}

.tabset {padding:1em 0 0 0.5em;}
.tab {margin:0 0 0 0.25em; padding:2px;}
.tabContents {padding:0.5em;}
.tabContents ul, .tabContents ol {margin:0; padding:0;}
.txtMainTab .tabContents li {list-style:none;}
.tabContents li.listLink { margin-left:.75em;}

#contentWrapper {display:block;}
#splashScreen {display:none;}

#displayArea {margin:1em 17em 0 14em;}

.toolbar {text-align:right; font-size:.9em;}

.tiddler {padding:1em 1em 0;}

.missing .viewer,.missing .title {font-style:italic;}

.title {font-size:1.6em; font-weight:bold;}

.missing .subtitle {display:none;}
.subtitle {font-size:1.1em;}

.tiddler .button {padding:0.2em 0.4em;}

.tagging {margin:0.5em 0.5em 0.5em 0; float:left; display:none;}
.isTag .tagging {display:block;}
.tagged {margin:0.5em; float:right;}
.tagging, .tagged {font-size:0.9em; padding:0.25em;}
.tagging ul, .tagged ul {list-style:none; margin:0.25em; padding:0;}
.tagClear {clear:both;}

.footer {font-size:.9em;}
.footer li {display:inline;}

.annotation {padding:0.5em; margin:0.5em;}

* html .viewer pre {width:99%; padding:0 0 1em 0;}
.viewer {line-height:1.4em; padding-top:0.5em;}
.viewer .button {margin:0 0.25em; padding:0 0.25em;}
.viewer blockquote {line-height:1.5em; padding-left:0.8em;margin-left:2.5em;}
.viewer ul, .viewer ol {margin-left:0.5em; padding-left:1.5em;}

.viewer table, table.twtable {border-collapse:collapse; margin:0.8em 1.0em;}
.viewer th, .viewer td, .viewer tr,.viewer caption,.twtable th, .twtable td, .twtable tr,.twtable caption {padding:3px;}
table.listView {font-size:0.85em; margin:0.8em 1.0em;}
table.listView th, table.listView td, table.listView tr {padding:0 3px 0 3px;}

.viewer pre {padding:0.5em; margin-left:0.5em; font-size:1.2em; line-height:1.4em; overflow:auto;}
.viewer code {font-size:1.2em; line-height:1.4em;}

.editor {font-size:1.1em;}
.editor input, .editor textarea {display:block; width:100%; font:inherit;}
.editorFooter {padding:0.25em 0; font-size:.9em;}
.editorFooter .button {padding-top:0; padding-bottom:0;}

.fieldsetFix {border:0; padding:0; margin:1px 0px;}

.zoomer {font-size:1.1em; position:absolute; overflow:hidden;}
.zoomer div {padding:1em;}

* html #backstage {width:99%;}
* html #backstageArea {width:99%;}
#backstageArea {display:none; position:relative; overflow: hidden; z-index:150; padding:0.3em 0.5em;}
#backstageToolbar {position:relative;}
#backstageArea a {font-weight:bold; margin-left:0.5em; padding:0.3em 0.5em;}
#backstageButton {display:none; position:absolute; z-index:175; top:0; right:0;}
#backstageButton a {padding:0.1em 0.4em; margin:0.1em;}
#backstage {position:relative; width:100%; z-index:50;}
#backstagePanel {display:none; z-index:100; position:absolute; width:90%; margin-left:3em; padding:1em;}
.backstagePanelFooter {padding-top:0.2em; float:right;}
.backstagePanelFooter a {padding:0.2em 0.4em;}
#backstageCloak {display:none; z-index:20; position:absolute; width:100%; height:100px;}

.whenBackstage {display:none;}
.backstageVisible .whenBackstage {display:block;}
/*}}}*/
/***
StyleSheet for use when a translation requires any css style changes.
This StyleSheet can be used directly by languages such as Chinese, Japanese and Korean which need larger font sizes.
***/
/*{{{*/
body {font-size:0.8em;}
#sidebarOptions {font-size:1.05em;}
#sidebarOptions a {font-style:normal;}
#sidebarOptions .sliderPanel {font-size:0.95em;}
.subtitle {font-size:0.8em;}
.viewer table.listView {font-size:0.95em;}
/*}}}*/
/*{{{*/
@media print {
#mainMenu, #sidebar, #messageArea, .toolbar, #backstageButton, #backstageArea {display: none !important;}
#displayArea {margin: 1em 1em 0em;}
noscript {display:none;} /* Fixes a feature in Firefox 1.5.0.2 where print preview displays the noscript content */
}
/*}}}*/
<!--{{{-->
<div class='toolbar' role='navigation' macro='toolbar [[ToolbarCommands::ViewToolbar]]'></div>
<div class='title' macro='view title'></div>
<div class='subtitle'><span macro='view modifier link'></span>, <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
<div class='tagging' macro='tagging'></div>
<div class='tagged' macro='tags'></div>
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
/***
|''Name:''|BackstageSidebarPlugin|
|''Description:''|Adds a "new tiddler" option to the backstage|
|''Author''|Yoann Kubera|
|''CodeRepository:''|n/a |
|''Version:''|0.1|
|''Comments:''| |
|''License''|None |

***/


//{{{
if(!version.extensions.BackstageNewtiddlerPlugin) {
version.extensions.BackstageNewtiddlerPlugin= {installed:true};
config.tasks.newTiddler = {
        text: 'new tiddler',
        tooltip: config.macros.newTiddler.prompt,
        action: function(){
                var e=createTiddlyElement(document.body,'span');
                e.style.display='none';
                wikify("<<newTiddler>>",e);
                e.getElementsByTagName('a')[0].onclick( );
                document.body.removeChild(e);
        }
}
config.backstageTasks.push("newTiddler");
} //# end of 'install only once'
//}}}
/***
|''Name:''|BackstageSidebarPlugin|
|''Description:''|Moves the sidebar to the backstage, as suggested at http://www.tiddlywiki.org/wiki/Dev:Backstage#Customization|
|''Author''|JonathanLister|
|''CodeRepository:''|n/a |
|''Version:''|0.1|
|''Comments:''|Please make comments at http://groups.google.co.uk/group/TiddlyWikiDev |
|''License''|[[BSD License|http://www.opensource.org/licenses/bsd-license.php]] |
|''~CoreVersion:''|2.4|

***/

//{{{
if(!version.extensions.BackstageSidebarPlugin) {
version.extensions.BackstageSidebarPlugin = {installed:true};

config.tasks.sidebar = {
	text: "sidebar",
	tooltip: "sidebar options",
	content: "<<tiddler SideBarOptions>><<tiddler SideBarTabs>>"
};
config.backstageTasks.push("sidebar");

config.macros.BackstageSidebarPlugin = {
	tiddler:tiddler
};

config.macros.BackstageSidebarPlugin.init = function() {
	var tiddler = this.tiddler;
	setStylesheet(store.getTiddlerText(tiddler.title+'##Stylesheet'),'BackstageSidebarPlugin');
};

} //# end of 'install only once'
//}}}

/***
!Stylesheet
#sidebar {
	display:none;
}
!(end of Stylesheet)
***/
/*{{{*/
config.options.txtUserName='Designer';
config.options.chkSaveBackups=false;
config.options.chkDisableWikiLinks=true;
config.options.chkSinglePageMode=true;
config.options.chkHideTabsBarWhenSingleTab=true;
/*}}}*/
{{stepMainTitle{Content of the local dynamic state of a level}}}

The ''dynamic state'' of the simulation models the state of the simulation and of all its content at a specific time. In multi-level simulations, each level embodies a diffent viewpoint on the simulated phenomenon, and therefore has its own ''local dynamic state''. A local dynamic state is said ''consistent'' if it models the state of the simulation at a time stamp of the time model.
!!Structure of a local dynamic state of a level in SIMILAR
[>img(50%,)[images/simulationModel/lowLevel/dynamicStateOutline.png]]
In SIMILAR, a local dynamic state of a level is the sum of the following elements:
*the ''identifier of the level'' for which the state is defined;
*the ''time'' for which the state is defined;
*a ''state valuation'' containing the value of the ''public local state of each agent'' lying in that level and the value of the ''public local state of the environment'' at that time;
*a ''state dynamics'' containing the +++^14em^*@[actions]modeled by influences=== that were +++^30em^*@[still being performed]If \(t\) is the consistent time of the dynamic state, then such actions started before \(t\) and will end after \(t\)=== in that level at that time.
{{clearright{}}}
!!Specifications
In SIMILAR, the consistent dynamic state of a level is modeled with an instance of the {{className{[[IPublicLocalDynamicState|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicLocalDynamicState.html]]}}} interface. This interface is the parent of all the possible dynamic states of the simulation. Usually, two concrete classes implement this interface:
*The {{className{[[ConsistentPublicLocalDynamicState|../api/fr/lgi2a/similar/microkernel/dynamicstate/ConsistentPublicLocalDynamicState.html]]}}} class, modeling consistent local dynamic states;
*The {{className{[[TransitoryPublicLocalDynamicState|../api/fr/lgi2a/similar/microkernel/dynamicstate/TransitoryPublicLocalDynamicState.html]]}}} class, modeling transitory local dynamic states;
{{bigemphasisblock {
In the general case, only the methods from the {{className{IPublicLocalDynamicState}}} interface are necessary to build the behavior of the agents. The two concrete classes are useful only if the user defines a custom ''disambiguation criterion'' in a [[simulation engine|Simulation engines]].
}}}
The {{className{IPublicLocalDynamicState}}} interface defines the following methods:
*{{methodName{getLevel( )}}} gets the ''identifier of the level'' for which the local dynamic state is defined; {{doclink{[[Documentation|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicLocalDynamicState.html#getLevel( )]]}}}
*{{methodName{getPublicLocalStateOfEnvironment( )}}} gets the ''state of the environment'' of that level; {{doclink{[[Documentation|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicLocalDynamicState.html#getPublicLocalStateOfEnvironment()]]}}}
*{{methodName{getPublicLocalStateOfAgents()}}} gets the ''public local state of the agents'' lying in that level;{{doclink{[[Documentation|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicLocalDynamicState.html#getPublicLocalStateOfAgents()]]}}}
*{{methodName{getStateDynamics()}}} gets the ''influences'' from the state dynamics of that level; {{doclink{[[Documentation|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicLocalDynamicState.html#getStateDynamics()]]}}}
*{{methodName{getSystemInfluencesOfStateDynamics()}}} gets the ''system influences'' from the state dynamics; {{doclink{[[Documentation|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicLocalDynamicState.html#getSystemInfluencesOfStateDynamics()]]}}}
*{{methodName{getRegularInfluencesOfStateDynamics()}}} gets the ''regular influences'' from the state dynamics; {{doclink{[[Documentation|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicLocalDynamicState.html#getRegularInfluencesOfStateDynamics()]]}}}
{{nextButton{[[Back to the guidelines >>|SMD - Perception]]}}}
[[Home]]
*[[Start|Simulation models]]
*[[Preparation|SMD - Preparation]]
**[[Packages tree|SMD - Package tree]]
**[[Tools|SMD - Tools preparation]]
**[[Random values|SMD - Tools preparation - Random]]
**[[Parameters|SMD - Tools preparation - Parameters]]
*[[High level|SMD - High level specifications]]
**[[Level identification|SMD - Levels identification]]
**[[Agent identification|SMD - Agents identification]]
**[[Level skeleton|SMD - Level skeleton]]
**[[Environment skeleton|SMD - Environment skeleton]]
**[[Agents skeleton|SMD - Agents skeleton]]
**[[Time model|SMD - Time model]]
**[[Public states|SMD - Public local states]]
**[[Private states|SMD - Private local states]]
**[[Influences skeleton|SMD - Influences skeleton]]
*[[Low level|SMD - Low level specifications]]
**[[Perception|SMD - Perception - Plan]]
**[[Global state|SMD - Global state - Plan]]
**[[Decision|SMD - Decision]]
**[[Create agents|SMD - Agent creation]]
**[[Natural|SMD - Natural]]
**[[Reaction|SMD - Reaction]]
*[[Final steps|SMD - Final steps]]
**[[Initial state|SMD - Initial state]]
**[[Execution|SMD - Running the simulation]]
<<dropMenu>>
/***
|Name|DisableWikiLinksPlugin|
|Source|http://www.TiddlyTools.com/#DisableWikiLinksPlugin|
|Version|1.6.0|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|plugin|
|Description|selectively disable TiddlyWiki's automatic ~WikiWord linking behavior|
This plugin allows you to disable TiddlyWiki's automatic ~WikiWord linking behavior, so that WikiWords embedded in tiddler content will be rendered as regular text, instead of being automatically converted to tiddler links.  To create a tiddler link when automatic linking is disabled, you must enclose the link text within {{{[[...]]}}}.
!!!!!Usage
<<<
You can block automatic WikiWord linking behavior for any specific tiddler by ''tagging it with<<tag excludeWikiWords>>'' (see configuration below) or, check a plugin option to disable automatic WikiWord links to non-existing tiddler titles, while still linking WikiWords that correspond to existing tiddlers titles or shadow tiddler titles.  You can also block specific selected WikiWords from being automatically linked by listing them in [[DisableWikiLinksList]] (see configuration below), separated by whitespace.  This tiddler is optional and, when present, causes the listed words to always be excluded, even if automatic linking of other WikiWords is being permitted.  

Note: WikiWords contained in default ''shadow'' tiddlers will be automatically linked unless you select an additional checkbox option lets you disable these automatic links as well, though this is not recommended, since it can make it more difficult to access some TiddlyWiki standard default content (such as AdvancedOptions or SideBarTabs)
<<<
!!!!!Configuration
<<<
<<option chkDisableWikiLinks>> Disable ALL automatic WikiWord tiddler links
<<option chkAllowLinksFromShadowTiddlers>> ... except for WikiWords //contained in// shadow tiddlers
<<option chkDisableNonExistingWikiLinks>> Disable automatic WikiWord links for non-existing tiddlers
Disable automatic WikiWord links for words listed in: <<option txtDisableWikiLinksList>>
Disable automatic WikiWord links for tiddlers tagged with: <<option txtDisableWikiLinksTag>>
<<<
!!!!!Revisions
<<<
2008.07.22 [1.6.0] hijack tiddler changed() method to filter disabled wiki words from internal links[] array (so they won't appear in the missing tiddlers list)
2007.06.09 [1.5.0] added configurable txtDisableWikiLinksTag (default value: "excludeWikiWords") to allows selective disabling of automatic WikiWord links for any tiddler tagged with that value.
2006.12.31 [1.4.0] in formatter, test for chkDisableNonExistingWikiLinks
2006.12.09 [1.3.0] in formatter, test for excluded wiki words specified in DisableWikiLinksList
2006.12.09 [1.2.2] fix logic in autoLinkWikiWords() (was allowing links TO shadow tiddlers, even when chkDisableWikiLinks is TRUE).  
2006.12.09 [1.2.1] revised logic for handling links in shadow content
2006.12.08 [1.2.0] added hijack of Tiddler.prototype.autoLinkWikiWords so regular (non-bracketed) WikiWords won't be added to the missing list
2006.05.24 [1.1.0] added option to NOT bypass automatic wikiword links when displaying default shadow content (default is to auto-link shadow content)
2006.02.05 [1.0.1] wrapped wikifier hijack in init function to eliminate globals and avoid FireFox 1.5.0.1 crash bug when referencing globals
2005.12.09 [1.0.0] initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.DisableWikiLinksPlugin= {major: 1, minor: 6, revision: 0, date: new Date(2008,7,22)};

if (config.options.chkDisableNonExistingWikiLinks==undefined) config.options.chkDisableNonExistingWikiLinks= false;
if (config.options.chkDisableWikiLinks==undefined) config.options.chkDisableWikiLinks=false;
if (config.options.txtDisableWikiLinksList==undefined) config.options.txtDisableWikiLinksList="DisableWikiLinksList";
if (config.options.chkAllowLinksFromShadowTiddlers==undefined) config.options.chkAllowLinksFromShadowTiddlers=true;
if (config.options.txtDisableWikiLinksTag==undefined) config.options.txtDisableWikiLinksTag="excludeWikiWords";

// find the formatter for wikiLink and replace handler with 'pass-thru' rendering
initDisableWikiLinksFormatter();
function initDisableWikiLinksFormatter() {
	for (var i=0; i<config.formatters.length && config.formatters[i].name!="wikiLink"; i++);
	config.formatters[i].coreHandler=config.formatters[i].handler;
	config.formatters[i].handler=function(w) {
		// supress any leading "~" (if present)
		var skip=(w.matchText.substr(0,1)==config.textPrimitives.unWikiLink)?1:0;
		var title=w.matchText.substr(skip);
		var exists=store.tiddlerExists(title);
		var inShadow=w.tiddler && store.isShadowTiddler(w.tiddler.title);
		// check for excluded Tiddler
		if (w.tiddler && w.tiddler.isTagged(config.options.txtDisableWikiLinksTag))
			{ w.outputText(w.output,w.matchStart+skip,w.nextMatch); return; }
		// check for specific excluded wiki words
		var t=store.getTiddlerText(config.options.txtDisableWikiLinksList);
		if (t && t.length && t.indexOf(w.matchText)!=-1)
			{ w.outputText(w.output,w.matchStart+skip,w.nextMatch); return; }
		// if not disabling links from shadows (default setting)
		if (config.options.chkAllowLinksFromShadowTiddlers && inShadow)
			return this.coreHandler(w);
		// check for non-existing non-shadow tiddler
		if (config.options.chkDisableNonExistingWikiLinks && !exists)
			{ w.outputText(w.output,w.matchStart+skip,w.nextMatch); return; }
		// if not enabled, just do standard WikiWord link formatting
		if (!config.options.chkDisableWikiLinks)
			return this.coreHandler(w);
		// just return text without linking
		w.outputText(w.output,w.matchStart+skip,w.nextMatch)
	}
}

Tiddler.prototype.coreAutoLinkWikiWords = Tiddler.prototype.autoLinkWikiWords;
Tiddler.prototype.autoLinkWikiWords = function()
{
	// if all automatic links are not disabled, just return results from core function
	if (!config.options.chkDisableWikiLinks)
		return this.coreAutoLinkWikiWords.apply(this,arguments);
	return false;
}

Tiddler.prototype.disableWikiLinks_changed = Tiddler.prototype.changed;
Tiddler.prototype.changed = function()
{
	this.disableWikiLinks_changed.apply(this,arguments);
	// remove excluded wiki words from links array
	var t=store.getTiddlerText(config.options.txtDisableWikiLinksList,"").readBracketedList();
	if (t.length) for (var i=0; i<t.length; i++)
		if (this.links.contains(t[i]))
			this.links.splice(this.links.indexOf(t[i]),1);
};
//}}}
The micro kernel of SIMILAR is characterized by three components.
!Micro kernel API
[<img(25%,)[images/guidelines.png]]
The ''API of the micro kernel'', containing the java classes of that kernel. To help users in the definition of simulations using the micro-kernel, this documentation describes ''design guidelines'':
*Showing how to use the classes of the micro-kernel/common libraries to build simulations;
*Illustrating the best practices to design simulations with SIMILAR.
{{linkbigbtn center {[[Guidelines index]]}}}
!Common libraries
[<img(25%,)[images/libraries.png]]
The ''common libraries'' of the micro kernel, containing generic implementations of simulation algorithms and results exporting features. These libraries include:
*Simulation engines;
*Probes;
*Disambiguation operators;
*Generic default implementations (empty states/perceived data);
*Abstract implementations of most interfaces of the micro kernel.
{{linkbigbtn center {[[Common libraries index|./commonLibs/index.html]]<script>place.lastChild.target="_self";</script>}}}
!Micro-kernel usage examples
[<img(25%,)[images/examples.png]]
The examples illustrating the use of the micro kernel and the common libraries to design simulations. These examples include:
*A bubble chamber simulation. +++?[<span class="expandbutton">Usage details</span>]
{{moresection{
This simulation illustrates:
*how the concepts of the formal model of SIMILAR are applied to a concrete simulation;
*how to use the common libs to build simulations.
}}}
===

{{linkbigbtn center {[[Usage examples index|./examples/index.html]]<script>place.lastChild.target="_self";</script>}}}
{{clear{}}}
/***
|''Name:''|DropDownMenuPlugin|
|''Description:''|Create dropdown menus from unordered lists|
|''Author:''|Saq Imtiaz ( lewcid@gmail.com )|
|''Source:''|http://tw.lewcid.org/#DropDownMenuPlugin|
|''Code Repository:''|http://tw.lewcid.org/svn/plugins|
|''Version:''|2.1|
|''Date:''|11/04/2007|
|''License:''|[[Creative Commons Attribution-ShareAlike 3.0 License|http://creativecommons.org/licenses/by-sa/3.0/]]|
|''~CoreVersion:''|2.2.5|

!!Usage:
* create a two-level unordered list using wiki syntax, and place {{{<<dropMenu>>}}} on the line after it.
* to create a vertical menu use {{{<<dropMenu vertical>>}}} instead.
* to assign custom classes to the list, just pass them as parameters to the macro {{{<<dropMenu className1 className2 className3>>}}}

!!Features:
*Supports just a single level of drop-downs, as anything more usually provides a poor experience for the user.
* Very light weight, about 1.5kb of JavaScript and 4kb of CSS.
* Comes with two built in css 'themes', the default horizontal and vertical. 

!!Customizing:
* to customize the appearance of the menu's, you can either add a custom class as described above or, you can edit the CSS via the StyleSheetDropDownMenu shadow tiddler.

!!Examples:
* [[DropDownMenuDemo]]
!! Code
***/
//{{{
config.macros.dropMenu={

	dropdownchar: "\u25bc",

	handler : function(place,macroName,params,wikifier,paramString,tiddler){
		list = findRelated(place.lastChild,"UL","tagName","previousSibling");
		if (!list)
			return;
		addClass(list,"suckerfish");
		if (params.length){
			addClass(list,paramString);
		}
		this.fixLinks(list);
	},
	
	fixLinks : function(el){
		var els = el.getElementsByTagName("li");
		for(var i = 0; i < els.length; i++) {
			if(els[i].getElementsByTagName("ul").length>0){
				var link = findRelated(els[i].firstChild,"A","tagName","nextSibling");
				if(!link){
					var ih = els[i].firstChild.data;
					els[i].removeChild(els[i].firstChild);
					var d = createTiddlyElement(null,"a",null,null,ih+this.dropdownchar,{href:"javascript:;"});
					els[i].insertBefore(d,els[i].firstChild);
				}
				else{
					link.firstChild.data = link.firstChild.data + this.dropdownchar;
					removeClass(link,"tiddlyLinkNonExisting");
				}
			}
			els[i].onmouseover = function() {
				addClass(this, "sfhover");
			};
			els[i].onmouseout = function() {
				removeClass(this, "sfhover");
			};
		}
	}	
};

config.shadowTiddlers["StyleSheetDropDownMenuPlugin"] = 
	 "/*{{{*/\n"+
	 "/***** LAYOUT STYLES -  DO NOT EDIT! *****/\n"+
	 "ul.suckerfish, ul.suckerfish ul {\n"+
	 "	margin: 0;\n"+
	 "	padding: 0;\n"+
	 "	list-style: none;\n"+
	 "	line-height:1.4em;\n"+
	 "}\n\n"+
	 "ul.suckerfish  li {\n"+
	 "	display: inline-block; \n"+
	 "	display: block;\n"+
	 "	float: left; \n"+
	 "}\n\n"+
	 "ul.suckerfish li ul {\n"+
	 "	position: absolute;\n"+
	 "	left: -999em;\n"+
	 "}\n\n"+
	 "ul.suckerfish li:hover ul, ul.suckerfish li.sfhover ul {\n"+
	 "	left: auto;\n"+
	 "}\n\n"+
	 "ul.suckerfish ul li {\n"+
	 "	float: none;\n"+
	 "	border-right: 0;\n"+
	 "	border-left:0;\n"+
	 "}\n\n"+
	 "ul.suckerfish a, ul.suckerfish a:hover {\n"+
	 "	display: block;\n"+
	 "}\n\n"+
	 "ul.suckerfish li a.tiddlyLink, ul.suckerfish li a, #mainMenu ul.suckerfish li a {font-weight:bold;}\n"+
	 "/**** END LAYOUT STYLES *****/\n"+
	 "\n\n"+
	 "/**** COLORS AND APPEARANCE - DEFAULT *****/\n"+
	 "ul.suckerfish li a {\n"+
	 "	padding: 0.5em 1.5em;\n"+
	 "	color: #FFF;\n"+
	 "	background: #0066aa;\n"+
	 "	border-bottom: 0;\n"+
	 "	font-weight:bold;\n"+
	 "}\n\n"+
	 "ul.suckerfish li:hover a, ul.suckerfish li.sfhover a{\n"+
	 "	background: #00558F;\n"+
	 "}\n\n"+
	 "ul.suckerfish li:hover ul a, ul.suckerfish li.sfhover ul a{\n"+
	 "	color: #000;\n"+
	 "	background: #eff3fa;\n"+
	 "	border-top:1px solid #FFF;\n"+
	 "}\n\n"+
	 "ul.suckerfish ul li a:hover {\n"+
	 "	background: #e0e8f5;\n"+
	 "}\n\n"+
	 "ul.suckerfish li a{\n"+
	 "	width:9em;\n"+
	 "}\n\n"+
	 "ul.suckerfish ul li a, ul.suckerfish ul li a:hover{\n"+
	 "	display:inline-block;\n"+
	 "	width:9em;\n"+
	 "}\n\n"+
	 "ul.suckerfish li {\n"+
	 "	border-left: 1px solid #00558F;\n"+
	 "}\n"+
	 "/***** END COLORS AND APPEARANCE - DEFAULT *****/\n"+
	 "\n\n"+
	 "/***** LAYOUT AND APPEARANCE: VERTICAL *****/\n"+
	 "ul.suckerfish.vertical li{\n"+
	 "	width:10em;\n"+
	 "	border-left: 0px solid #00558f;\n"+
	 "}\n\n"+
	 "ul.suckerfish.vertical ul li, ul.suckerfish.vertical li a, ul.suckerfish.vertical li:hover a, ul.suckerfish.vertical li.sfhover a {\n"+
	 "	border-left: 0.8em solid #00558f;\n"+
	 "}\n\n"+
	 "ul.suckerfish.vertical li a, ul.suckerfish.vertical li:hover a, ul.suckerfish.vertical li.sfhover a,  ul.suckerfish.vertical li.sfhover a:hover{\n"+
	 "	width:8em;\n"+
	 "}\n\n"+
	 "ul.suckerfish.vertical {\n"+
	 "	width:10em; text-align:left;\n"+
	 "	float:left;\n"+
	 "}\n\n"+
	 "ul.suckerfish.vertical li a {\n"+
	 "	padding: 0.5em 1em 0.5em 1em;\n"+
	 "	border-top:1px solid  #fff;\n"+
	 "}\n\n"+
	 "ul.suckerfish.vertical, ul.suckerfish.vertical ul {\n"+
	 "	line-height:1.4em;\n"+
	 "}\n\n"+
	 "ul.suckerfish.vertical li:hover ul, ul.suckerfish.vertical li.sfhover ul { \n"+
	 "	margin: -2.4em 0 0 10.9em;\n"+
	 "}\n\n"+
	 "ul.suckerfish.vertical li:hover ul li a, ul.suckerfish.vertical li.sfhover ul li a {\n"+
	 "	border: 0px solid #FFF;\n"+
	 "}\n\n"+
	 "ul.suckerfish.vertical li:hover a, ul.suckerfish.vertical li.sfhover a{\n"+
	 "	padding-right:1.1em;\n"+
	 "}\n\n"+
	 "ul.suckerfish.vertical li:hover ul li, ul.suckerfish.vertical li.sfhover ul li {\n"+
	 "	border-bottom:1px solid  #fff;\n"+
	 "}\n\n"+
	 "/***** END LAYOUT AND APPEARANCE: VERTICAL *****/\n"+
	 "/*}}}*/";
store.addNotification("StyleSheetDropDownMenuPlugin",refreshStyles);
//}}}
[[StyleSheetCustomization]]

To get started with this blank TiddlyWiki, you'll need to modify the following tiddlers:
* [[SiteTitle]] & [[SiteSubtitle]]: The title and subtitle of the site, as shown above (after saving, they will also appear in the browser title bar)
* [[MainMenu]]: The menu (usually on the left)
* [[DefaultTiddlers]]: Contains the names of the tiddlers that you want to appear when the TiddlyWiki is opened
You'll also need to enter your username for signing your edits: <<option txtUserName>>

*Documentation inline test  +++?[<span class="docsmallbtn ">Documentation</span>]{{docsection{
This is the content of the documentation.
!A title inside the documentation
Another text.
{{javadoctitle{Javadoc:}}}
{{javadocsection{
A javadoc !
}}} 
}}}
===

*Implementation inline test +++?[<span class="implsmallbtn">Implementation</span>]{{implsection{
This is the content of an implementation.
!A title inside the implementation
Another text
{{{
A source code.
}}}
}}}
===

*Example inline test +++?[<span class="exsmallbtn">Example</span>]{{exsection{
This is the content of an example.
!A title inside the example
Another text
}}} 
===

+++?[<span class="docbigbtn ">Documentation</span>]{{docsection{
This is the content of the documentation.
!A title inside the documentation
Another text.
{{javadoctitle{Javadoc:}}}
{{javadocsection{
A javadoc !
}}} 
}}}
===

+++?[<span class="implbigbtn">Implementation</span>]{{implsection{
This is the content of an implementation.
!A title inside the implementation
Another text
{{{
A source code.
}}}
}}}
===

+++?[<span class="exbigbtn">Example</span>]{{exsection{
This is the content of an example.
!A title inside the example
Another text
}}} 
===


A normal paragraph having a word with a +++^34em^*@[tooltip]
The text of the tooltip.
===.

{{bigemphasisblock{
A block putting a big emphasis on a text.
}}}

+++?*[<span class="docbigbtn" style="width:100px;">Test 1</span>]{{docsection{
Tabulation content 1.
}}}
=== +++?*[<span class="docbigbtn" style="width:100px;">Test 2</span>]{{docsection{
Tabulation content 2.
}}}
===

[<img(10%,)[file:///C:/Users/yoakubera/Desktop/similarDoc/images/completeStructure.png]]
{{linkbigbtn center{[[Big link button | MainMenu]]}}}
This part of the documentation is dedicated to the design and the implementation of SIMILAR simulations ''using the micro-kernel only''. At the same time, it describes ''best practices'' facilitating the organization of the implementation of the simulation.

__Note:__ Libraries facilitating the design of simulations are available in the [[common libs|./commonlibs/index.html]] of the micro kernel. This library especially contains the definition of a generic simulation engine. Do not hesitate to refer to this library to facilitate the implementation of your simulations!
!Available guidelines
The guidelines describe how to implement the following components of a simulation:

{{center{[img(22%,)[images/engineIcon.png][Simulation engines]] [img(22%,)[images/modelIcon.png][Simulation models]] [img(22%,)[images/probeIcon.png][Observation probes]] [img(22%,)[images/runIcon.png][Simulation execution]]}}}

[>img(45%,)[images/structure_microKernel.png]]
The ''micro kernel'' of SIMILAR defines the core classes of the SIMILAR API. It provides the minimal implementation of these concepts and leaves the implementation of the simulations opened to many optimizations. Thus, this kernel is appropriate for developers wishing to ''tune the low level implementation of the simulation''.

This documentation provides ''design guidelines'' to implement SIMILAR simulations using the micro-kernel. At the same time, it describes ''best practices'' facilitating the organization of the implementation of the simulation.

{{linkbigbtn{[[Documentation content|Documentation content]]}}}
In SIMILAR, this data structure is an instance of the {{className{[[IPublicDynamicStateMap|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicDynamicStateMap.html]]}}} class. This interface is a lightweight version of the {{className{Map}}} interface of java and works similarly to it. It defines the following methods:
*{{methodName{keySet()}}} lists the identifier of the perceptible levels contained in the map; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicDynamicStateMap.html#keySet()]]}}}
*{{methodName{get(LevelIdentifier)}}} gets the local dynamic state of a level having a specific identifier;  {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicDynamicStateMap.html#get(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier)]]}}}
*{{methodName{put(IPublicLocalDynamicState)}}} sets the local dynamic state of a specific level in this map. {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/dynamicstate/IPublicDynamicStateMap.html#put(fr.univ_artois.lgi2a.similar.microkernel.dynamicstate.IPublicLocalDynamicState)]]}}}
/***
|Name|ImageSizePlugin|
|Source|http://www.TiddlyTools.com/#ImageSizePlugin|
|Version|1.2.3|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|plugin|
|Description|adds support for resizing images|
This plugin adds optional syntax to scale an image to a specified width and height and/or interactively resize the image with the mouse.
!!!!!Usage
<<<
The extended image syntax is:
{{{
[img(w+,h+)[...][...]]
}}}
where ''(w,h)'' indicates the desired width and height (in CSS units, e.g., px, em, cm, in, or %). Use ''auto'' (or a blank value) for either dimension to scale that dimension proportionally (i.e., maintain the aspect ratio). You can also calculate a CSS value 'on-the-fly' by using a //javascript expression// enclosed between """{{""" and """}}""". Appending a plus sign (+) to a dimension enables interactive resizing in that dimension (by dragging the mouse inside the image). Use ~SHIFT-click to show the full-sized (un-scaled) image. Use ~CTRL-click to restore the starting size (either scaled or full-sized).
<<<
!!!!!Examples
<<<
{{{
[img(100px+,75px+)[images/meow2.jpg]]
}}}
[img(100px+,75px+)[images/meow2.jpg]]
{{{
[<img(34%+,+)[images/meow.gif]]
[<img(21% ,+)[images/meow.gif]]
[<img(13%+, )[images/meow.gif]]
[<img( 8%+, )[images/meow.gif]]
[<img( 5% , )[images/meow.gif]]
[<img( 3% , )[images/meow.gif]]
[<img( 2% , )[images/meow.gif]]
[img(  1%+,+)[images/meow.gif]]
}}}
[<img(34%+,+)[images/meow.gif]]
[<img(21% ,+)[images/meow.gif]]
[<img(13%+, )[images/meow.gif]]
[<img( 8%+, )[images/meow.gif]]
[<img( 5% , )[images/meow.gif]]
[<img( 3% , )[images/meow.gif]]
[<img( 2% , )[images/meow.gif]]
[img(  1%+,+)[images/meow.gif]]
{{tagClear{
}}}
<<<
!!!!!Revisions
<<<
2011.09.03 [1.2.3] bypass addStretchHandlers() if no '+' suffix is used (i.e., not resizable)
2010.07.24 [1.2.2] moved tip/dragtip text to config.formatterHelpers.imageSize object to enable customization
2009.02.24 [1.2.1] cleanup width/height regexp, use '+' suffix for resizing
2009.02.22 [1.2.0] added stretchable images
2008.01.19 [1.1.0] added evaluated width/height values
2008.01.18 [1.0.1] regexp for "(width,height)" now passes all CSS values to browser for validation
2008.01.17 [1.0.0] initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.ImageSizePlugin= {major: 1, minor: 2, revision: 3, date: new Date(2011,9,3)};
//}}}
//{{{
var f=config.formatters[config.formatters.findByField("name","image")];
f.match="\\[[<>]?[Ii][Mm][Gg](?:\\([^,]*,[^\\)]*\\))?\\[";
f.lookaheadRegExp=/\[([<]?)(>?)[Ii][Mm][Gg](?:\(([^,]*),([^\)]*)\))?\[(?:([^\|\]]+)\|)?([^\[\]\|]+)\](?:\[([^\]]*)\])?\]/mg;
f.handler=function(w) {
	this.lookaheadRegExp.lastIndex = w.matchStart;
	var lookaheadMatch = this.lookaheadRegExp.exec(w.source)
	if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
		var floatLeft=lookaheadMatch[1];
		var floatRight=lookaheadMatch[2];
		var width=lookaheadMatch[3];
		var height=lookaheadMatch[4];
		var tooltip=lookaheadMatch[5];
		var src=lookaheadMatch[6];
		var link=lookaheadMatch[7];

		// Simple bracketted link
		var e = w.output;
		if(link) { // LINKED IMAGE
			if (config.formatterHelpers.isExternalLink(link)) {
				if (config.macros.attach && config.macros.attach.isAttachment(link)) {
					// see [[AttachFilePluginFormatters]]
					e = createExternalLink(w.output,link);
					e.href=config.macros.attach.getAttachment(link);
					e.title = config.macros.attach.linkTooltip + link;
				} else
					e = createExternalLink(w.output,link);
			} else 
				e = createTiddlyLink(w.output,link,false,null,w.isStatic);
			addClass(e,"imageLink");
		}

		var img = createTiddlyElement(e,"img");
		if(floatLeft) img.align="left"; else if(floatRight) img.align="right";
		if(width||height) {
			var x=width.trim(); var y=height.trim();
			var stretchW=(x.substr(x.length-1,1)=='+'); if (stretchW) x=x.substr(0,x.length-1);
			var stretchH=(y.substr(y.length-1,1)=='+'); if (stretchH) y=y.substr(0,y.length-1);
			if (x.substr(0,2)=="{{")
				{ try{x=eval(x.substr(2,x.length-4))} catch(e){displayMessage(e.description||e.toString())} }
			if (y.substr(0,2)=="{{")
				{ try{y=eval(y.substr(2,y.length-4))} catch(e){displayMessage(e.description||e.toString())} }
			img.style.width=x.trim(); img.style.height=y.trim();
			if (stretchW||stretchH) config.formatterHelpers.addStretchHandlers(img,stretchW,stretchH);
		}
		if(tooltip) img.title = tooltip;

		// GET IMAGE SOURCE
		if (config.macros.attach && config.macros.attach.isAttachment(src))
			src=config.macros.attach.getAttachment(src); // see [[AttachFilePluginFormatters]]
		else if (config.formatterHelpers.resolvePath) { // see [[ImagePathPlugin]]
			if (config.browser.isIE || config.browser.isSafari) {
				img.onerror=(function(){
					this.src=config.formatterHelpers.resolvePath(this.src,false);
					return false;
				});
			} else
				src=config.formatterHelpers.resolvePath(src,true);
		}
		img.src=src;
		w.nextMatch = this.lookaheadRegExp.lastIndex;
	}
}

config.formatterHelpers.imageSize={
	tip: 'SHIFT-CLICK=show full size, CTRL-CLICK=restore initial size',
	dragtip: 'DRAG=stretch/shrink, '
}

config.formatterHelpers.addStretchHandlers=function(e,stretchW,stretchH) {
	e.title=((stretchW||stretchH)?this.imageSize.dragtip:'')+this.imageSize.tip;
	e.statusMsg='width=%0, height=%1';
	e.style.cursor='move';
	e.originalW=e.style.width;
	e.originalH=e.style.height;
	e.minW=Math.max(e.offsetWidth/20,10);
	e.minH=Math.max(e.offsetHeight/20,10);
	e.stretchW=stretchW;
	e.stretchH=stretchH;
	e.onmousedown=function(ev) { var ev=ev||window.event;
		this.sizing=true;
		this.startX=!config.browser.isIE?ev.pageX:(ev.clientX+findScrollX());
		this.startY=!config.browser.isIE?ev.pageY:(ev.clientY+findScrollY());
		this.startW=this.offsetWidth;
		this.startH=this.offsetHeight;
		return false;
	};
	e.onmousemove=function(ev) { var ev=ev||window.event;
		if (this.sizing) {
			var s=this.style;
			var currX=!config.browser.isIE?ev.pageX:(ev.clientX+findScrollX());
			var currY=!config.browser.isIE?ev.pageY:(ev.clientY+findScrollY());
			var newW=(currX-this.offsetLeft)/(this.startX-this.offsetLeft)*this.startW;
			var newH=(currY-this.offsetTop )/(this.startY-this.offsetTop )*this.startH;
			if (this.stretchW) s.width =Math.floor(Math.max(newW,this.minW))+'px';
			if (this.stretchH) s.height=Math.floor(Math.max(newH,this.minH))+'px';
			clearMessage(); displayMessage(this.statusMsg.format([s.width,s.height]));
		}
		return false;
	};
	e.onmouseup=function(ev) { var ev=ev||window.event;
		if (ev.shiftKey) { this.style.width=this.style.height=''; }
		if (ev.ctrlKey)  { this.style.width=this.originalW; this.style.height=this.originalH; }
		this.sizing=false;
		clearMessage();
		return false;
	};
	e.onmouseout=function(ev) { var ev=ev||window.event;
		this.sizing=false;
		clearMessage();
		return false;
	};
}
//}}}
The {{className{InfluencesMap}}} class defines a data structure that was created mainly for engine design purposes. From the point of view of the decision process, only the following addition methods are put to use:
*{{methodName{add( IInfluence )}}} adding one influence to the data structure; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/influences/InfluencesMap.html#add(fr.univ_artois.lgi2a.similar.microkernel.influences.IInfluence)]]}}}
*{{methodName{addAll( Collection<IInfluence> )}}} adding a collection of influences to the data structure. {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/influences/InfluencesMap.html#addAll(java.util.Collection)]]}}}
/***
|Name|InlineJavascriptPlugin|
|Source|http://www.TiddlyTools.com/#InlineJavascriptPlugin|
|Documentation|http://www.TiddlyTools.com/#InlineJavascriptPluginInfo|
|Version|1.9.6|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|plugin|
|Description|Insert Javascript executable code directly into your tiddler content.|
''Call directly into TW core utility routines, define new functions, calculate values, add dynamically-generated TiddlyWiki-formatted output'' into tiddler content, or perform any other programmatic actions each time the tiddler is rendered.
!!!!!Documentation
>see [[InlineJavascriptPluginInfo]]
!!!!!Revisions
<<<
2010.12.15 1.9.6 allow (but ignore) type="..." syntax
|please see [[InlineJavascriptPluginInfo]] for additional revision details|
2005.11.08 1.0.0 initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.InlineJavascriptPlugin= {major: 1, minor: 9, revision: 6, date: new Date(2010,12,15)};

config.formatters.push( {
	name: "inlineJavascript",
	match: "\\<script",
	lookahead: "\\<script(?: type=\\\"[^\\\"]*\\\")?(?: src=\\\"([^\\\"]*)\\\")?(?: label=\\\"([^\\\"]*)\\\")?(?: title=\\\"([^\\\"]*)\\\")?(?: key=\\\"([^\\\"]*)\\\")?( show)?\\>((?:.|\\n)*?)\\</script\\>",
	handler: function(w) {
		var lookaheadRegExp = new RegExp(this.lookahead,"mg");
		lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = lookaheadRegExp.exec(w.source)
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			var src=lookaheadMatch[1];
			var label=lookaheadMatch[2];
			var tip=lookaheadMatch[3];
			var key=lookaheadMatch[4];
			var show=lookaheadMatch[5];
			var code=lookaheadMatch[6];
			if (src) { // external script library
				var script = document.createElement("script"); script.src = src;
				document.body.appendChild(script); document.body.removeChild(script);
			}
			if (code) { // inline code
				if (show) // display source in tiddler
					wikify("{{{\n"+lookaheadMatch[0]+"\n}}}\n",w.output);
				if (label) { // create 'onclick' command link
					var link=createTiddlyElement(w.output,"a",null,"tiddlyLinkExisting",wikifyPlainText(label));
					var fixup=code.replace(/document.write\s*\(/gi,'place.bufferedHTML+=(');
					link.code="function _out(place,tiddler){"+fixup+"\n};_out(this,this.tiddler);"
					link.tiddler=w.tiddler;
					link.onclick=function(){
						this.bufferedHTML="";
						try{ var r=eval(this.code);
							if(this.bufferedHTML.length || (typeof(r)==="string")&&r.length)
								var s=this.parentNode.insertBefore(document.createElement("span"),this.nextSibling);
							if(this.bufferedHTML.length)
								s.innerHTML=this.bufferedHTML;
							if((typeof(r)==="string")&&r.length) {
								wikify(r,s,null,this.tiddler);
								return false;
							} else return r!==undefined?r:false;
						} catch(e){alert(e.description||e.toString());return false;}
					};
					link.setAttribute("title",tip||"");
					var URIcode='javascript:void(eval(decodeURIComponent(%22(function(){try{';
					URIcode+=encodeURIComponent(encodeURIComponent(code.replace(/\n/g,' ')));
					URIcode+='}catch(e){alert(e.description||e.toString())}})()%22)))';
					link.setAttribute("href",URIcode);
					link.style.cursor="pointer";
					if (key) link.accessKey=key.substr(0,1); // single character only
				}
				else { // run script immediately
					var fixup=code.replace(/document.write\s*\(/gi,'place.innerHTML+=(');
					var c="function _out(place,tiddler){"+fixup+"\n};_out(w.output,w.tiddler);";
					try	 { var out=eval(c); }
					catch(e) { out=e.description?e.description:e.toString(); }
					if (out && out.length) wikify(out,w.output,w.highlightRegExp,w.tiddler);
				}
			}
			w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
		}
	}
} )
//}}}

// // Backward-compatibility for TW2.1.x and earlier
//{{{
if (typeof(wikifyPlainText)=="undefined") window.wikifyPlainText=function(text,limit,tiddler) {
	if(limit > 0) text = text.substr(0,limit);
	var wikifier = new Wikifier(text,formatter,null,tiddler);
	return wikifier.wikifyPlain();
}
//}}}

// // GLOBAL FUNCTION: $(...) -- 'shorthand' convenience syntax for document.getElementById()
//{{{
if (typeof($)=='undefined') { function $(id) { return document.getElementById(id.replace(/^#/,'')); } }
//}}}
/***
|Name|InlineJavascriptPluginInfo|
|Source|http://www.TiddlyTools.com/#InlineJavascriptPlugin|
|Documentation|http://www.TiddlyTools.com/#InlineJavascriptPluginInfo|
|Version|1.9.6|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|documentation|
|Description|Documentation for InlineJavascriptPlugin|
''Call directly into TW core utility routines, define new functions, calculate values, add dynamically-generated TiddlyWiki-formatted output'' into tiddler content, or perform any other programmatic actions each time the tiddler is rendered.
!!!!!Usage
<<<
This plugin adds wiki syntax for surrounding tiddler content with {{{<script>}}} and {{{</script>}}} markers, so that it can be recognized as embedded javascript code.  When a tiddler is rendered, the plugin automatically invokes any embedded scripts, which can be used to construct and return dynamically-generated output that is inserted into the tiddler content.
{{{
<script type="..." src="..." label="..." title="..." key="..." show>
	/* javascript code goes here... */
</script>
}}}
All parameters are //optional//.    When the ''show'' keyword is used, the plugin will also include the script source code in the output that it displays in the tiddler.  This is helpful when creating examples for documentation purposes (such as used in this tiddler!)

__''Deferred execution from an 'onClick' link''__
<script label="click here" title="mouseover tooltip text" key="X" show>
	/* javascript code goes here... */
	alert('you clicked on the link!');
</script>
By including a {{{label="..."}}} parameter in the initial {{{<script>}}} marker, the plugin will create a link to an 'onclick' script that will only be executed when that specific link is clicked, rather than running the script each time the tiddler is rendered.  You may also include a {{{title="..."}}} parameter to specify the 'tooltip' text that will appear whenever the mouse is moved over the onClick link text, and a {{{key="X"}}} parameter to specify an //access key// (which must be a //single// letter or numeric digit only).

__''Loading scripts from external source files''__
<script src="URL" show>
	/* optional javascript code goes here... */
</script>You can also load javascript directly from an external source URL, by including a src="..." parameter in the initial {{{<script>}}} marker (e.g., {{{<script src="demo.js"></script>}}}).  This is particularly useful when incorporating third-party javascript libraries for use in custom extensions and plugins.  The 'foreign' javascript code remains isolated in a separate file that can be easily replaced whenever an updated library file becomes available.

In addition to loading the javascript from the external file, you can also use this feature to invoke javascript code contained within the {{{<script>...</script>}}} markers.  This code is invoked //after// the external script file has been processed, and can make immediate use of the functions and/or global variables defined by the external script file.
>Note: To ensure that your javascript functions are always available when needed, you should load the libraries from a tiddler that is rendered as soon as your TiddlyWiki document is opened, such as MainMenu.  For example: put your {{{<script src="..."></script>}}} syntax into a separate 'library' tiddler (e.g., LoadScripts), and then add {{{<<tiddler LoadScripts>>}}} to MainMenu so that the library is loaded before any other tiddlers that rely upon the functions it defines. 
>
>Normally, loading external javascript in this way does not produce any direct output, and should not have any impact on the appearance of your MainMenu.  However, if your LoadScripts tiddler contains notes or other visible content, you can suppress this output by using 'inline CSS' in the MainMenu, like this: {{{@@display:none;<<tiddler LoadScripts>>@@}}}
<<<
!!!!!Creating dynamic tiddler content and accessing the ~TiddlyWiki DOM
<<<
An important difference between TiddlyWiki inline scripting and conventional embedded javascript techniques for web pages is the method used to produce output that is dynamically inserted into the document: in a typical web document, you use the {{{document.write()}}} (or {{{document.writeln()}}}) function to output text sequences (often containing HTML tags) that are then rendered when the entire document is first loaded into the browser window.

However, in a ~TiddlyWiki document, tiddlers (and other DOM elements) are created, deleted, and rendered "on-the-fly", so writing directly to the global 'document' object does not produce the results you want (i.e., replacing the embedded script within the tiddler content), and instead will //completely replace the entire ~TiddlyWiki document in your browser window (which is clearly not a good thing!)//.  In order to allow scripts to use {{{document.write()}}}, the plugin automatically converts and buffers all HTML output so it can be safely inserted into your tiddler content, immediately following the script.

''Note that {{{document.write()}}} can only be used to output "pure HTML" syntax.  To produce //wiki-formatted// output, your script should instead return a text value containing the desired wiki-syntax content'', which will then be automatically rendered immediately following the script.  If returning a text value is not sufficient for your needs, the plugin also provides an automatically-defined variable, 'place', that gives the script code ''direct access to the //containing DOM element//'' into which the tiddler output is being rendered.  You can use this variable to ''perform direct DOM manipulations'' that can, for example:
* generate wiki-formatted output using {{{wikify("...content...",place)}}}
* vary the script's actions based upon the DOM element in which it is embedded
* access 'tiddler-relative' DOM information using {{{story.findContainingTiddler(place)}}}
Note:
''When using an 'onclick' script, the 'place' element actually refers to the onclick //link text// itself, instead of the containing DOM element.''  This permits you to directly reference or modify the link text to reflect any 'stateful' conditions that might set by the script.  To refer to the containing DOM element from within an 'onclick' script, you can use "place.parentNode" instead.
<<<
!!!!!Instant "bookmarklets"
<<<
You can also use an 'onclick' link to define a "bookmarklet": a small piece of javascript that can be ''invoked directly from the browser without having to be defined within the current document.''  This allows you to create 'stand-alone' commands that can be applied to virtually ANY TiddlyWiki document... even remotely-hosted documents that have been written by others!!  To create a bookmarklet, simply define an 'onclick' script and then grab the resulting link text and drag-and-drop it onto your browser's toolbar (or right-click and use the 'bookmark this link' command to add it to the browser's menu).

Notes:
*When writing scripts intended for use as bookmarklets, due to the ~URI-encoding required by the browser, ''you cannot not use ANY double-quotes (") within the bookmarklet script code.''
*All comments embedded in the bookmarklet script must ''use the fully-delimited {{{/* ... */}}} comment syntax,'' rather than the shorter {{{//}}} comment syntax.
*Most importantly, because bookmarklets are invoked directly from the browser interface and are not embedded within the TiddlyWiki document, there is NO containing 'place' DOM element surrounding the script.  As a result, ''you cannot use a bookmarklet to generate dynamic output in your document,''  and using {{{document.write()}}} or returning wiki-syntax text or making reference to the 'place' DOM element will halt the script and report a "Reference Error" when that bookmarklet is invoked.  
Please see [[InstantBookmarklets]] for many examples of 'onclick' scripts that can also be used as bookmarklets.
<<<
!!!!!Special reserved function name
<<<
The plugin 'wraps' all inline javascript code inside a function, {{{_out()}}}, so that any return value you provide can be correctly handled by the plugin and inserted into the tiddler.  To avoid unpredictable results (and possibly fatal execution errors), this function should never be redefined or called from ''within'' your script code.
<<<
!!!!!$(...) 'shorthand' function
<<<
As described by Dustin Diaz [[here|http://www.dustindiaz.com/top-ten-javascript/]], the plugin defines a 'shorthand' function that allows you to write:
{{{
$(id)
}}}
in place of the normal standard javascript syntax:
{{{
document.getElementById(id)
}}}
This function is provided merely as a convenience for javascript coders that may be familiar with this abbreviation, in order to allow them to save a few bytes when writing their own inline script code.
<<<
!!!!!Examples
<<<
simple dynamic output:
><script show>
	document.write("The current date/time is: "+(new Date())+"<br>");
	return "link to current user: [["+config.options.txtUserName+"]]\n";
</script>
dynamic output using 'place' to get size information for current tiddler:
><script show>
	if (!window.story) window.story=window;
	var title=story.findContainingTiddler(place).getAttribute("tiddler");
	var size=store.getTiddlerText(title).length;
	return title+" is using "+size+" bytes";
</script>
dynamic output from an 'onclick' script, using {{{document.write()}}} and/or {{{return "..."}}}
><script label="click here" show>
	document.write("<br>The current date/time is: "+(new Date())+"<br>");
	return "link to current user: [["+config.options.txtUserName+"]]\n";
</script>
creating an 'onclick' button/link that accesses the link text AND the containing tiddler:
><script label="click here" title="clicking this link will show an 'alert' box" key="H" show>
	if (!window.story) window.story=window;
	var txt=place.firstChild.data;
	var tid=story.findContainingTiddler(place).getAttribute('tiddler');
	alert('Hello World!\nlinktext='+txt+'\ntiddler='+tid);
</script>
dynamically setting onclick link text based on stateful information:
>{{block{
{{{
<script label="click here">
	/* toggle "txtSomething" value */
	var on=(config.txtSomething=="ON");
	place.innerHTML=on?"enable":"disable";
	config.txtSomething=on?"OFF":"ON";
	return "\nThe current value is: "+config.txtSomething;
</script><script>
	/* initialize onclick link text based on current "txtSomething" value */
	var on=(config.txtSomething=="ON");
	place.lastChild.previousSibling.innerHTML=on?"disable":"enable";
</script>
}}}
<script label="click here">
	/* toggle "txtSomething" value */
	var on=(config.txtSomething=="ON");
	place.innerHTML=on?"enable":"disable";
	config.txtSomething=on?"OFF":"ON";
	return "\nThe current value is: "+config.txtSomething;
</script><script>
	/* initialize onclick link text based on current "txtSomething" value */
	var on=(config.txtSomething=="ON");
	place.lastChild.innerHTML=on?"enable":"disable";
</script>
}}}
loading a script from a source url:
>http://www.TiddlyTools.com/demo.js contains:
>>{{{function inlineJavascriptDemo() { alert('Hello from demo.js!!') } }}}
>>{{{displayMessage('InlineJavascriptPlugin: demo.js has been loaded');}}}
>note: When using this example on your local system, you will need to download the external script file from the above URL and install it into the same directory as your document.
>
><script src="demo.js" show>
	return "inlineJavascriptDemo() function has been defined"
</script>
><script label="click to invoke inlineJavascriptDemo()" key="D" show>
	inlineJavascriptDemo();
</script>
<<<
!!!!!Revisions
<<<
2010.12.15 1.9.6 allow (but ignore) type="..." syntax
2009.04.11 1.9.5 pass current tiddler object into wrapper code so it can be referenced from within 'onclick' scripts
2009.02.26 1.9.4 in $(), handle leading '#' on ID for compatibility with JQuery syntax
2008.06.11 1.9.3 added $(...) function as 'shorthand' for document.getElementById()
2008.03.03 1.9.2 corrected fallback declaration of wikifyPlainText() (fixes Safari "parse error")
2008.02.23 1.9.1 in onclick function, use string instead of array for 'bufferedHTML' (fixes IE errors)
2008.02.21 1.9.0 output from 'onclick' scripts (return value or document.write() calls) are now buffered and rendered into into a span following the script.  Also, added default 'return false' handling if no return value provided (prevents HREF from being triggered -- return TRUE to allow HREF to be processed).  Thanks to Xavier Verges for suggestion and preliminary code.
2008.02.14 1.8.1 added backward-compatibility for use of wikifyPlainText() in TW2.1.3 and earlier
2008.01.08 [*.*.*] plugin size reduction: documentation moved to ...Info tiddler
2007.12.28 1.8.0 added support for key="X" syntax to specify custom access key definitions
2007.12.15 1.7.0 autogenerate URI encoded HREF on links for onclick scripts.  Drag links to browser toolbar to create bookmarklets.  IMPORTANT NOTE: place is NOT defined when scripts are used as bookmarklets.  In addition, double-quotes will cause syntax errors.  Thanks to PaulReiber for debugging and brainstorming.
2007.11.26 1.6.2 when converting "document.write()" function calls in inline code, allow whitespace between "write" and "(" so that "document.write ( foobar )" is properly converted.
2007.11.16 1.6.1 when rendering "onclick scripts", pass label text through wikifyPlainText() to parse any embedded wiki-syntax to enable use of HTML entities or even TW macros to generate dynamic label text.
2007.02.19 1.6.0 added support for title="..." to specify mouseover tooltip when using an onclick (label="...") script
2006.10.16 1.5.2 add newline before closing '}' in 'function out_' wrapper.  Fixes error caused when last line of script is a comment.
2006.06.01 1.5.1 when calling wikify() on script return value, pass hightlightRegExp and tiddler params so macros that rely on these values can render properly
2006.04.19 1.5.0 added 'show' parameter to force display of javascript source code in tiddler output
2006.01.05 1.4.0 added support 'onclick' scripts.  When label="..." param is present, a button/link is created using the indicated label text, and the script is only executed when the button/link is clicked.  'place' value is set to match the clicked button/link element.
2005.12.13 1.3.1 when catching eval error in IE, e.description contains the error text, instead of e.toString().  Fixed error reporting so IE shows the correct response text.  Based on a suggestion by UdoBorkowski
2005.11.09 1.3.0 for 'inline' scripts (i.e., not scripts loaded with src="..."), automatically replace calls to 'document.write()' with 'place.innerHTML+=' so script output is directed into tiddler content.  Based on a suggestion by BradleyMeck
2005.11.08 1.2.0 handle loading of javascript from an external URL via src="..." syntax
2005.11.08 1.1.0 pass 'place' param into scripts to provide direct DOM access 
2005.11.08 1.0.0 initial release
<<<
{{toparent{[[back to parent|../README.html]]<script>place.lastChild.target="_self";</script>}}}
''[[General|Home]]''
----
*[[Index|Documentation content]]
''[[Design guidelines|Guidelines index]]''
----
*[[Engines design|Simulation engines]]
*[[Models design|Simulation models]]
*[[Probes design|Observation probes]]
*[[Execution management|Simulation execution]]
''Micro-kernel helpers''
----
*[[Common libraries|./commonLibs/index.html]]<script>place.lastChild.target="_self";</script>
*[[Usage examples|./examples/index.html]]<script>place.lastChild.target="_self";</script>
/***
|''Name:''|MathJaxPlugin|
|''Description:''|Enable LaTeX formulas for TiddlyWiki|
|''Version:''|1.0.1|
|''Date:''|Feb 11, 2012|
|''Source:''|http://www.guyrutenberg.com/2011/06/25/latex-for-tiddlywiki-a-mathjax-plugin|
|''Author:''|Guy Rutenberg|
|''License:''|[[BSD open source license]]|
|''~CoreVersion:''|2.5.0|
 
!! Changelog
!!! 1.0.1 Feb 11, 2012
* Fixed interoperability with TiddlerBarPlugin
!! How to Use
Currently the plugin supports the following delemiters:
* """\(""".."""\)""" - Inline equations
* """$$""".."""$$""" - Displayed equations
* """\[""".."""\]""" - Displayed equations
!! Demo
This is an inline equation \(P(E)   = {n \choose k} p^k (1-p)^{ n-k}\) and this is a displayed equation:
\[J_\alpha(x) = \sum_{m=0}^\infty \frac{(-1)^m}{m! \, \Gamma(m + \alpha + 1)}{\left({\frac{x}{2}}\right)}^{2 m + \alpha}\]
This is another displayed equation $$e=mc^2$$
!! Code
***/
//{{{
config.extensions.MathJax = {
  mathJaxScript : "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
  // uncomment the following line if you want to access MathJax using SSL
  // mathJaxScript : "https://d3eoax9i5htok0.cloudfront.net/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
  displayTiddler: function(TiddlerName) {
    config.extensions.MathJax.displayTiddler_old.apply(this, arguments);
    MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
  }
};
 
jQuery.getScript(config.extensions.MathJax.mathJaxScript, function(){
    MathJax.Hub.Config({
      extensions: ["tex2jax.js"],
      "HTML-CSS": { scale: 100 }
    });
 
    MathJax.Hub.Startup.onload();
    config.extensions.MathJax.displayTiddler_old = story.displayTiddler;
    story.displayTiddler = config.extensions.MathJax.displayTiddler;
});
 
config.formatters.push({
	name: "mathJaxFormula",
	match: "\\\\\\[|\\$\\$|\\\\\\(",
	//lookaheadRegExp: /(?:\\\[|\$\$)((?:.|\n)*?)(?:\\\]|$$)/mg,
	handler: function(w)
	{
		switch(w.matchText) {
		case "\\[": // displayed equations
			this.lookaheadRegExp = /\\\[((?:.|\n)*?)(\\\])/mg;
			break;
		case "$$": // inline equations
			this.lookaheadRegExp = /\$\$((?:.|\n)*?)(\$\$)/mg;
			break;
		case "\\(": // inline equations
			this.lookaheadRegExp = /\\\(((?:.|\n)*?)(\\\))/mg;
			break;
		default:
			break;
		}
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			createTiddlyElement(w.output,"span",null,null,lookaheadMatch[0]);
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
});
//}}}
/***
|Name|NestedSlidersPlugin2|
|Source|http://www.TiddlyTools.com/#NestedSlidersPlugin|
|Documentation|http://www.TiddlyTools.com/#NestedSlidersPluginInfo|
|Version|2.4.9|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|plugin|
|Description|show content in nest-able sliding/floating panels, without creating separate tiddlers for each panel's content|
!!!!!Documentation
>see [[NestedSlidersPluginInfo]]
!!!!!Configuration
<<<
<<option chkFloatingSlidersAnimate>> allow floating sliders to animate when opening/closing
>Note: This setting can cause 'clipping' problems in some versions of InternetExplorer.
>In addition, for floating slider animation to occur you must also allow animation in general (see [[AdvancedOptions]]).
<<<
!!!!!Revisions
<<<
2008.11.15 - 2.4.9 in adjustNestedSlider(), don't make adjustments if panel is marked as 'undocked' (CSS class).  In onClickNestedSlider(), SHIFT-CLICK docks panel (see [[MoveablePanelPlugin]])
|please see [[NestedSlidersPluginInfo]] for additional revision details|
2005.11.03 - 1.0.0 initial public release.  Thanks to RodneyGomes, GeoffSlocock, and PaulPetterson for suggestions and experiments.
<<<
!!!!!Code
***/
//{{{
version.extensions.NestedSlidersPlugin= {major: 2, minor: 4, revision: 9, date: new Date(2008,11,15)};

// options for deferred rendering of sliders that are not initially displayed
if (config.options.chkFloatingSlidersAnimate===undefined)
	config.options.chkFloatingSlidersAnimate=false; // avoid clipping problems in IE

// default styles for 'floating' class
setStylesheet(".floatingPanel { position:absolute; z-index:10; padding:0.5em; margin:0em; \
	background-color:#eee; color:#000; border:1px solid #000; text-align:left; }","floatingPanelStylesheet");

// if removeCookie() function is not defined by TW core, define it here.
if (window.removeCookie===undefined) {
	window.removeCookie=function(name) {
		document.cookie = name+'=; expires=Thu, 01-Jan-1970 00:00:01 UTC; path=/;'; 
	}
}

config.formatters.push( {
	name: "nestedSliders",
	match: "\\n?\\+{3}",
	terminator: "\\s*\\={3}\\n?",
	lookahead: "\\n?\\+{3}(\\+)?(\\([^\\)]*\\))?(\\?)?(\\!*)?(\\^(?:[^\\^\\*\\@\\[\\>]*\\^)?)?(\\*)?(\\@)?(?:\\{\\{([\\w]+[\\s\\w]*)\\{)?(\\[[^\\]]*\\])?(\\[[^\\]]*\\])?(?:\\}{3})?(\\#[^:]*\\:)?(\\>)?(\\.\\.\\.)?\\s*",
	handler: function(w)
		{
			lookaheadRegExp = new RegExp(this.lookahead,"mg");
			lookaheadRegExp.lastIndex = w.matchStart;
			var lookaheadMatch = lookaheadRegExp.exec(w.source)
			if(lookaheadMatch && lookaheadMatch.index == w.matchStart)
			{
				var defopen=lookaheadMatch[1];
				var cookiename=lookaheadMatch[2];
				var special=lookaheadMatch[3];
				var header=lookaheadMatch[4];
				var panelwidth=lookaheadMatch[5];
				var transient=lookaheadMatch[6];
				var hover=lookaheadMatch[7];
				var buttonClass=lookaheadMatch[8];
				var label=lookaheadMatch[9];
				var openlabel=lookaheadMatch[10];
				var panelID=lookaheadMatch[11];
				var blockquote=lookaheadMatch[12];
				var deferred=lookaheadMatch[13];

				// location for rendering button and panel
				var place=w.output;

				// default to closed, no cookie, no accesskey, no alternate text/tip
				var show="none"; var cookie=""; var key="";
				var closedtext=">"; var closedtip="";
				var openedtext="<"; var openedtip="";

				// extra "+", default to open
				if (defopen) show="block";

				// cookie, use saved open/closed state
				if (cookiename) {
					cookie=cookiename.trim().slice(1,-1);
					cookie="chkSlider"+cookie;
					if (config.options[cookie]==undefined)
						{ config.options[cookie] = (show=="block") }
					show=config.options[cookie]?"block":"none";
				}

				// parse label/tooltip/accesskey: [label=X|tooltip]
				if (label) {
					var parts=label.trim().slice(1,-1).split("|");
					closedtext=parts.shift();
					if (closedtext.substr(closedtext.length-2,1)=="=")	
						{ key=closedtext.substr(closedtext.length-1,1); closedtext=closedtext.slice(0,-2); }
					openedtext=closedtext;
					if (parts.length) closedtip=openedtip=parts.join("|");
					else { closedtip="show "+closedtext; openedtip="hide "+closedtext; }
				} else {
					buttonClass='expandbutton';
				}

				// parse alternate label/tooltip: [label|tooltip]
				if (openlabel) {
					var parts=openlabel.trim().slice(1,-1).split("|");
					openedtext=parts.shift();
					if (parts.length) openedtip=parts.join("|");
					else openedtip="hide "+openedtext;
				}

				var title=show=='block'?openedtext:closedtext;
				var tooltip=show=='block'?openedtip:closedtip;

				// create the button
				if (header) { // use "Hn" header format instead of button/link
					var lvl=(header.length>5)?5:header.length;
					var btn = createTiddlyElement(createTiddlyElement(place,"h"+lvl,null,null,null),"a",null,buttonClass,title);
					btn.onclick=onClickNestedSlider;
					btn.setAttribute("href","javascript:;");
					btn.setAttribute("title",tooltip);
				} else if(special) {
					var btn = createTiddlyElement(createTiddlyElement(place,"a",null,null,null),"a",null,buttonClass,title);
					btn.onclick=onClickNestedSlider;
					btn.setAttribute("href","javascript:;");
					btn.setAttribute("title",tooltip);
				} else {
					var btn = createTiddlyButton(place,title,tooltip,onClickNestedSlider,buttonClass);
				}
				btn.innerHTML=title; // enables use of HTML entities in label

				// set extra button attributes
				btn.setAttribute("closedtext",closedtext);
				btn.setAttribute("closedtip",closedtip);
				btn.setAttribute("openedtext",openedtext);
				btn.setAttribute("openedtip",openedtip);
				btn.sliderCookie = cookie; // save the cookiename (if any) in the button object
				btn.defOpen=defopen!=null; // save default open/closed state (boolean)
				btn.keyparam=key; // save the access key letter ("" if none)
				if (key.length) {
					btn.setAttribute("accessKey",key); // init access key
					btn.onfocus=function(){this.setAttribute("accessKey",this.keyparam);}; // **reclaim** access key on focus
				}
				btn.setAttribute("hover",hover?"true":"false");
				btn.onmouseover=function(ev) {
					// optional 'open on hover' handling
					if (this.getAttribute("hover")=="true" && this.sliderPanel.style.display=='none') {
						document.onclick.call(document,ev); // close transients
						onClickNestedSlider(ev); // open this slider
					}
					// mouseover on button aligns floater position with button
					if (window.adjustSliderPos) window.adjustSliderPos(this.parentNode,this,this.sliderPanel);
				}

				// create slider panel
				var panelClass=panelwidth?"floatingPanel":"sliderPanel";
				if (panelID) panelID=panelID.slice(1,-1); // trim off delimiters
				var panel=createTiddlyElement(place,"div",panelID,panelClass,null);
				panel.button = btn; // so the slider panel know which button it belongs to
				btn.sliderPanel=panel; // so the button knows which slider panel it belongs to
				panel.defaultPanelWidth=(panelwidth && panelwidth.length>2)?panelwidth.slice(1,-1):"";
				panel.setAttribute("transient",transient=="*"?"true":"false");
				panel.style.display = show;
				panel.style.width=panel.defaultPanelWidth;
				panel.onmouseover=function(event) // mouseover on panel aligns floater position with button
					{ if (window.adjustSliderPos) window.adjustSliderPos(this.parentNode,this.button,this); }

				// render slider (or defer until shown) 
				w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
				if ((show=="block")||!deferred) {
					// render now if panel is supposed to be shown or NOT deferred rendering
					w.subWikify(blockquote?createTiddlyElement(panel,"blockquote"):panel,this.terminator);
					// align floater position with button
					if (window.adjustSliderPos) window.adjustSliderPos(place,btn,panel);
				}
				else {
					var src = w.source.substr(w.nextMatch);
					var endpos=findMatchingDelimiter(src,"+++","===");
					panel.setAttribute("raw",src.substr(0,endpos));
					panel.setAttribute("blockquote",blockquote?"true":"false");
					panel.setAttribute("rendered","false");
					w.nextMatch += endpos+3;
					if (w.source.substr(w.nextMatch,1)=="\n") w.nextMatch++;
				}
			}
		}
	}
)

function findMatchingDelimiter(src,starttext,endtext) {
	var startpos = 0;
	var endpos = src.indexOf(endtext);
	// check for nested delimiters
	while (src.substring(startpos,endpos-1).indexOf(starttext)!=-1) {
		// count number of nested 'starts'
		var startcount=0;
		var temp = src.substring(startpos,endpos-1);
		var pos=temp.indexOf(starttext);
		while (pos!=-1)  { startcount++; pos=temp.indexOf(starttext,pos+starttext.length); }
		// set up to check for additional 'starts' after adjusting endpos
		startpos=endpos+endtext.length;
		// find endpos for corresponding number of matching 'ends'
		while (startcount && endpos!=-1) {
			endpos = src.indexOf(endtext,endpos+endtext.length);
			startcount--;
		}
	}
	return (endpos==-1)?src.length:endpos;
}
//}}}
//{{{
window.onClickNestedSlider=function(e)
{
	if (!e) var e = window.event;
	var theTarget = resolveTarget(e);
	while (theTarget && theTarget.sliderPanel==undefined) theTarget=theTarget.parentNode;
	if (!theTarget) return false;
	var theSlider = theTarget.sliderPanel;
	var isOpen = theSlider.style.display!="none";

	// if SHIFT-CLICK, dock panel first (see [[MoveablePanelPlugin]])
	if (e.shiftKey && config.macros.moveablePanel) config.macros.moveablePanel.dock(theSlider,e);

	// toggle label
	theTarget.innerHTML=isOpen?theTarget.getAttribute("closedText"):theTarget.getAttribute("openedText");
	// toggle tooltip
	theTarget.setAttribute("title",isOpen?theTarget.getAttribute("closedTip"):theTarget.getAttribute("openedTip"));

	// deferred rendering (if needed)
	if (theSlider.getAttribute("rendered")=="false") {
		var place=theSlider;
		if (theSlider.getAttribute("blockquote")=="true")
			place=createTiddlyElement(place,"blockquote");
		wikify(theSlider.getAttribute("raw"),place);
		theSlider.setAttribute("rendered","true");
	}

	// show/hide the slider
	if(config.options.chkAnimate && (!hasClass(theSlider,'floatingPanel') || config.options.chkFloatingSlidersAnimate))
		anim.startAnimating(new Slider(theSlider,!isOpen,e.shiftKey || e.altKey,"none"));
	else
		theSlider.style.display = isOpen ? "none" : "block";

	// reset to default width (might have been changed via plugin code)
	theSlider.style.width=theSlider.defaultPanelWidth;

	// align floater panel position with target button
	if (!isOpen && window.adjustSliderPos) window.adjustSliderPos(theSlider.parentNode,theTarget,theSlider);

	// if showing panel, set focus to first 'focus-able' element in panel
	if (theSlider.style.display!="none") {
		var ctrls=theSlider.getElementsByTagName("*");
		for (var c=0; c<ctrls.length; c++) {
			var t=ctrls[c].tagName.toLowerCase();
			if ((t=="input" && ctrls[c].type!="hidden") || t=="textarea" || t=="select")
				{ try{ ctrls[c].focus(); } catch(err){;} break; }
		}
	}
	var cookie=theTarget.sliderCookie;
	if (cookie && cookie.length) {
		config.options[cookie]=!isOpen;
		if (config.options[cookie]!=theTarget.defOpen) window.saveOptionCookie(cookie);
		else window.removeCookie(cookie); // remove cookie if slider is in default display state
	}

	// prevent SHIFT-CLICK from being processed by browser (opens blank window... yuck!)
	// prevent clicks *within* a slider button from being processed by browser
	// but allow plain click to bubble up to page background (to close transients, if any)
	if (e.shiftKey || theTarget!=resolveTarget(e))
		{ e.cancelBubble=true; if (e.stopPropagation) e.stopPropagation(); }
	Popup.remove(); // close open popup (if any)
	return false;
}
//}}}
//{{{
// click in document background closes transient panels 
document.nestedSliders_savedOnClick=document.onclick;
document.onclick=function(ev) { if (!ev) var ev=window.event; var target=resolveTarget(ev);

	if (document.nestedSliders_savedOnClick)
		var retval=document.nestedSliders_savedOnClick.apply(this,arguments);
	// if click was inside a popup... leave transient panels alone
	var p=target; while (p) if (hasClass(p,"popup")) break; else p=p.parentNode;
	if (p) return retval;
	// if click was inside transient panel (or something contained by a transient panel), leave it alone
	var p=target; while (p) {
		if ((hasClass(p,"floatingPanel")||hasClass(p,"sliderPanel"))&&p.getAttribute("transient")=="true") break;
		p=p.parentNode;
	}
	if (p) return retval;
	// otherwise, find and close all transient panels...
	var all=document.all?document.all:document.getElementsByTagName("DIV");
	for (var i=0; i<all.length; i++) {
		 // if it is not a transient panel, or the click was on the button that opened this panel, don't close it.
		if (all[i].getAttribute("transient")!="true" || all[i].button==target) continue;
		// otherwise, if the panel is currently visible, close it by clicking it's button
		if (all[i].style.display!="none") window.onClickNestedSlider({target:all[i].button})
		if (!hasClass(all[i],"floatingPanel")&&!hasClass(all[i],"sliderPanel")) all[i].style.display="none";
	}
	return retval;
};
//}}}
//{{{
// adjust floating panel position based on button position
if (window.adjustSliderPos==undefined) window.adjustSliderPos=function(place,btn,panel) {
	if (hasClass(panel,"floatingPanel") && !hasClass(panel,"undocked")) {
		// see [[MoveablePanelPlugin]] for use of 'undocked'
		var rightEdge=document.body.offsetWidth-1;
		var panelWidth=panel.offsetWidth;
		var left=0;
		var top=btn.offsetHeight; 
		if (place.style.position=="relative" && findPosX(btn)+panelWidth>rightEdge) {
			left-=findPosX(btn)+panelWidth-rightEdge; // shift panel relative to button
			if (findPosX(btn)+left<0) left=-findPosX(btn); // stay within left edge
		}
		if (place.style.position!="relative") {
			var left=findPosX(btn);
			var top=findPosY(btn)+btn.offsetHeight;
			var p=place; while (p && !hasClass(p,'floatingPanel')) p=p.parentNode;
			if (p) { left-=findPosX(p); top-=findPosY(p); }
			if (left+panelWidth>rightEdge) left=rightEdge-panelWidth;
			if (left<0) left=0;
		}
		panel.style.left=left+"px"; panel.style.top=top+"px";
	}
}
//}}}
//{{{
// TW2.1 and earlier:
// hijack Slider stop handler so overflow is visible after animation has completed
Slider.prototype.coreStop = Slider.prototype.stop;
Slider.prototype.stop = function()
	{ this.coreStop.apply(this,arguments); this.element.style.overflow = "visible"; }

// TW2.2+
// hijack Morpher stop handler so sliderPanel/floatingPanel overflow is visible after animation has completed
if (version.major+.1*version.minor+.01*version.revision>=2.2) {
	Morpher.prototype.coreStop = Morpher.prototype.stop;
	Morpher.prototype.stop = function() {
		this.coreStop.apply(this,arguments);
		var e=this.element;
		if (hasClass(e,"sliderPanel")||hasClass(e,"floatingPanel")) {
			// adjust panel overflow and position after animation
			e.style.overflow = "visible";
			if (window.adjustSliderPos) window.adjustSliderPos(e.parentNode,e.button,e);
		}
	};
}
//}}}
/***
|Name|NestedSlidersPluginInfo|
|Source|http://www.TiddlyTools.com/#NestedSlidersPlugin|
|Documentation|http://www.TiddlyTools.com/#NestedSlidersPluginInfo|
|Version|2.4.9|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|documentation|
|Description|documentation for NestedSlidersPlugin|
This plugin adds new wiki syntax for embedding 'slider' panels directly into tiddler content.
!!!!!Usage
<<<
//{{{
++++(cookiename)!!!!!^width^*@{{class{[label=key|tooltip][altlabel|alttooltip]}}}#panelID:>...
content goes here
===
//}}}
* ''"""+++""" (or """++++""") and """==="""''<br>marks the start and end of the slider definition, respectively.  When the extra {{{+}}} is used, the slider will be open when initially displayed.
* ''"""(cookiename)"""''<br>saves the slider opened/closed state, and restores this state whenever the slider is re-rendered.
* ''"""! through !!!!!"""''<br>displays the slider label using a formatted headline (Hn) style instead of a button/link style
* ''"""^width^ (or just ^)"""''<br>makes the slider 'float' on top of other content rather than shifting that content downward.  'width' must be a valid CSS value (e.g., "30em", "180px", "50%", etc.).  If omitted, the default width is "auto" (i.e., fit to content)
* ''"""*"""''<br>denotes "transient display": when a click occurs elsewhere in the document, the slider/floating panel will be automatically closed.  This is useful for creating 'pulldown menus' that automatically go away after they are used.  //Note: using SHIFT-click on a slider label will open/close that slider without triggering the automatic closing of any transient slider panels that are currently displayed, permitting ''temporary'' display of several transient panels at once.//
* ''"""@"""''<br>denotes "open on hover": the slider/floating panel will be automatically opened as soon as the mouse moves over the slider label, without requiring a click.
* ''"""{{class{[label=key|tooltip][altlabel|alttooltip]}}}"""''<br>uses label/tooltip/accesskey.  """{{class{...}}}""", """=key""", """|tooltip""" and """[altlabel|alttooltip]""" are optional.  'class' is any valid CSS class name, used to style the slider label text.  'key' must be a ''single letter only''.  altlabel/alttooltip specify alternative label/tooltip for use when slider/floating panel is displayed.  //Note: you can use HTML syntax within the label text to include HTML entities (e.g., {{{&raquo;}}} (&raquo;) or {{{&#x25ba;}}} (&#x25ba;), or even embedded images (e.g., {{{<img src="images/eric3.gif">}}}).//
* ''"""#panelID:"""''<br>defines a unique DOM element ID that is assigned to the panel element used to display the slider content.  This ID can then be used later to reposition the panel using the {{{<<DOM move id>>}}} macro (see [[DOMTweaksPlugin]]), or to access/modify the panel element through use of {{{document.getElementById(...)}}}) javascript code in a plugin or inline script.
* ''""">"""''<br>automatically adds blockquote formatting to slider content
* ''"""..."""''<br>defers rendering of closed sliders until the first time they are opened.
Notes:
*You can 'nest' sliders as deep as you like (see complex nesting example below), so that expandable 'tree-like' hierarchical displays can be created.
*Deferred rendering (...) can be used to offset processing overhead until actually needed. However, this may produce unexpected results in some cases.  Use with care.
* To make slider definitions easier to read and recognize when editing a tiddler, newlines immediately following the 'start slider' or preceding the 'end slider' sequences are automatically supressed so that excess whitespace is eliminated from the output.
<<<
!!!!!Examples
<<<
simple in-line slider: 
{{{
+++content===
}}}
+++content===
----
use a custom label and tooltip: 
{{{
+++[label|tooltip]content===
}}}
+++[label|tooltip]content===
----
content automatically blockquoted: 
{{{
+++>content===
}}}
+++>content===
----
all options (except cookie) //(default open, heading, sized floater, transient, open on hover, class, label/tooltip/key, blockquoted, deferred)//
{{{
++++!!!^30em^*@{{big{[label=Z|click or press Alt-Z to open]}}}>...
   content
===
}}}
++++!!!^30em^*@{{big{[label=Z|click or press Alt-Z to open]}}}>...
   content
===
----
complex nesting example:
{{{
+++[get info...=I|click for information or press Alt-I]
	put some general information here,
	plus a floating panel with more specific info:
	+++^10em^[view details...|click for details]
		put some detail here, which could in turn contain a transient panel,
		perhaps with a +++^25em^*[glossary definition]explaining technical terms===
	===
===
}}}
+++[get info...=I|click for information or press Alt-I]
	put some general information here,
	plus a floating panel with more specific info:
	+++^10em^[view details...|click for details]
		put some detail here, which could in turn contain a transient panel,
		perhaps with a +++^25em^*[glossary definition]explaining technical terms===
	===
===
----
embedded image as slider button
{{{
+++[<img src=images/eric3.gif>|click me!]>
	{{big{OUCH!}}}
===
}}}
+++[<img src=images/eric3.gif>|click me!]>
	{{big{OUCH!}}}
===
<<<
!!!!!Revisions
<<<
2008.11.15 2.4.9 in adjustNestedSlider(), don't make adjustments if panel is marked as 'undocked' (CSS class).  In onClickNestedSlider(), SHIFT-CLICK docks panel (see [[MoveablePanelPlugin]])
2008.11.13 2.4.8 in document.onclick(), if transient panel is not a sliderPanel or floatingPanel, hide it via CSS
2008.10.05 2.4.7 in onClickNestedSlider(), added try/catch around focus() call to prevent IE error if input field being focused on is currently not visible.
2008.09.07 2.4.6 added removeCookie() function for compatibility with [[CookieManagerPlugin]]
2008.06.07 2.4.5 in 'onmouseover' handler for 'open on hover' slider buttons, use call() method when invoking document.onclick function (avoids error in IE)
2008.06.07 2.4.4 changed default for chkFloatingSlidersAnimate to FALSE to avoid clipping problem on some browsers (IE).  Updated Morpher hijack (again) to adjust regular sliderPanel styles as well as floatingPanel styles.
2008.05.07 2.4.3 updated Morpher hijack to adjust floatingPanel styles after animation without affecting other animated elements (i.e. popups).  Also, updated adjustSliderPos() to account for scrollwidth and use core findWindowWidth().
2008.04.02 2.4.2 in onClickNestedSlider, handle clicks on elements contained //within// slider buttons (e.g., when using HTML to display an image as a slider button).
2008.04.01 2.4.1 open on hover also triggers document.onclick to close other transient sliders
2008.04.01 2.4.0 re-introduced 'open on hover' feature using "@" symbol
2008.03.26 2.3.5 in document.onclick(), if click is in popup, don't dismiss transient panel (if any)
2008.01.08 [*.*.*] plugin size reduction: documentation moved to ...Info tiddler
2007.12.28 2.3.4 added hijack for Animator.prototype.startAnimating().  Previously, the plugin code simply set the overflow to "visible" after animation.  This code tweak corrects handling of elements that were styled with overflow=hidden/auto/scroll before animation by saving the overflow style and then restoring it after animation has completed.
2007.12.17 2.3.3 use hasClass() instead of direct comparison to test for "floatingPanel" class.  Allows floating panels to have additional classes assigned to them (i.e., by AnimationEffectsPlugin).
2007.11.14 2.3.2 in onClickNestedSlider(), prevent SHIFT-click events from opening a new, empty browser window by setting "cancelBubble=true" and calling "stopPropagation()".  Note: SHIFT-click is still processed as a normal click (i.e., it toggles the slider panel display).  Also, using SHIFT-click will prevent 'transient' sliders from being automatically closed when another slider is opened, allowing you to *temporarily* display several transient sliders at once.
2007.07.26 2.3.1 in document.onclick(), propagate return value from hijacked core click handler to consume OR bubble up click as needed.  Fixes "IE click disease", whereby nearly every mouse click causes a page transition.
2007.07.20 2.3.0 added syntax for setting panel ID (#panelID:).  This allows individual slider panels to be repositioned within tiddler content simply by giving them a unique ID and then moving them to the desired location using the {{{<<DOM move id>>}}} macro.
2007.07.19 2.2.0 added syntax for alttext and alttip (button label and tooltip to be displayed when panel is open)
2007.07.14 2.1.2 corrected use of 'transient' attribute in IE to prevent (non-recursive) infinite loop
2007.07.12 2.1.0 replaced use of "*" for 'open/close on rollover' (which didn't work too well).  "*" now indicates 'transient' panels that are automatically closed if a click occurs somewhere else in the document.  This permits use of nested sliders to create nested "pulldown menus" that automatically disappear after interaction with them has been completed.  Also, in onClickNestedSlider(), use "theTarget.sliderCookie", instead of "this.sliderCookie" to correct cookie state tracking when automatically dismissing transient panels.
2007.06.10 2.0.5 add check to ensure that window.adjustSliderPanel() is defined before calling it (prevents error on shutdown when mouse event handlers are still defined)
2007.05.31 2.0.4 add handling to invoke adjustSliderPanel() for onmouseover events on slider button and panel.  This allows the panel position to be re-synced when the button position shifts due to changes in unrelated content above it on the page.  (thanks to Harsha for bug report)
2007.03.30 2.0.3 added chkFloatingSlidersAnimate (default to FALSE), so that slider animation can be disabled independent of the overall document animation setting (avoids strange rendering and focus problems in floating panels)
2007.03.01 2.0.2 for TW2.2+, hijack Morpher.prototype.stop so that "overflow:hidden" can be reset to "overflow:visible" after animation ends
2007.03.01 2.0.1 in hijack for Slider.prototype.stop, use apply() to pass params to core function
2006.07.28 2.0.0 added custom class syntax around label/tip/key syntax: {{{{{classname{[label=key|tip]}}}}}}
2006.07.25 1.9.3 when parsing slider, save default open/closed state in button element, then in onClickNestedSlider(), if slider state matches saved default, instead of saving cookie, delete it.  Significantly reduces the 'cookie overhead' when default slider states are used.
2006.06.29 1.9.2 in onClickNestedSlider(), when setting focus to first control, skip over type="hidden"
2006.06.22 1.9.1 added panel.defaultPanelWidth to save requested panel width, even after resizing has changed the style value
2006.05.11 1.9.0 added optional '^width^' syntax for floating sliders and '=key' syntax for setting an access key on a slider label
2006.05.09 1.8.0 in onClickNestedSlider(), when showing panel, set focus to first child input/textarea/select element
2006.04.24 1.7.8 in adjustSliderPos(), if floating panel is contained inside another floating panel, subtract offset of containing panel to find correct position
2006.02.16 1.7.7 corrected deferred rendering to account for use-case where show/hide state is tracked in a cookie
2006.02.15 1.7.6 in adjustSliderPos(), ensure that floating panel is positioned completely within the browser window (i.e., does not go beyond the right edge of the browser window)
2006.02.04 1.7.5 add 'var' to unintended global variable declarations to avoid FireFox 1.5.0.1 crash bug when assigning to globals
2006.01.18 1.7.4 only define adjustSliderPos() function if it has not already been provided by another plugin.  This lets other plugins 'hijack' the function even when they are loaded first.
2006.01.16 1.7.3 added adjustSliderPos(place,btn,panel,panelClass) function to permit specialized logic for placement of floating panels.  While it provides improved placement for many uses of floating panels, it exhibits a relative offset positioning error when used within *nested* floating panels.  Short-term workaround is to only adjust the position for 'top-level' floaters.
2006.01.16 1.7.2 added button property to slider panel elements so that slider panel can tell which button it belongs to.  Also, re-activated and corrected animation handling so that nested sliders aren't clipped by hijacking Slider.prototype.stop so that "overflow:hidden" can be reset to "overflow:visible" after animation ends
2006.01.14 1.7.1 added optional "^" syntax for floating panels.  Defines new CSS class, ".floatingPanel", as an alternative for standard in-line ".sliderPanel" styles.
2006.01.14 1.7.0 added optional "*" syntax for rollover handling to show/hide slider without requiring a click (Based on a suggestion by tw4efl)
2006.01.03 1.6.2 When using optional "!" heading style, instead of creating a clickable "Hn" element, create an "A" element inside the "Hn" element.  (allows click-through in SlideShowPlugin, which captures nearly all click events, except for hyperlinks)
2005.12.15 1.6.1 added optional "..." syntax to invoke deferred ('lazy') rendering for initially hidden sliders
removed checkbox option for 'global' application of lazy sliders
2005.11.25 1.6.0 added optional handling for 'lazy sliders' (deferred rendering for initially hidden sliders)
2005.11.21 1.5.1 revised regular expressions: if present, a single newline //preceding// and/or //following// a slider definition will be suppressed so start/end syntax can be place on separate lines in the tiddler 'source' for improved readability.  Similarly, any whitespace (newlines, tabs, spaces, etc.) trailing the 'start slider' syntax or preceding the 'end slider' syntax is also suppressed.
2005.11.20 1.5.0 added (cookiename) syntax for optional tracking and restoring of slider open/close state
2005.11.11 1.4.0 added !!!!! syntax to render slider label as a header (Hn) style instead of a button/link style
2005.11.07 1.3.0 removed alternative syntax {{{(((}}} and {{{)))}}} (so they can be used by other formatting extensions) and simplified/improved regular expressions to trim multiple excess newlines
2005.11.05 1.2.1 changed name to NestedSlidersPlugin
2005.11.04 1.2.0 added alternative character-mode syntax {{{(((}}} and {{{)))}}}
tweaked "eat newlines" logic for line-mode {{{+++}}} and {{{===}}} syntax
2005.11.03 1.1.1 fixed toggling of default tooltips ("more..." and "less...") when a non-default button label is used.  code cleanup, added documentation
2005.11.03 1.1.0 changed delimiter syntax from {{{(((}}} and {{{)))}}} to {{{+++}}} and {{{===}}}.  changed name to EasySlidersPlugin
2005.11.03 1.0.0 initial public release
<<<
{{stepMainTitle{Observing simulation results with SIMILAR}}}

<html><hr class="topSep"/></html>
<<tiddler [[Observation probes - Intro]]>>
!Structure of a probe in SIMILAR
<<tiddler [[Observation probes - Structure]]>><html>
<h1>Specifications and implementation instructions</h1></html>
<<tiddler [[Observation probes - Specifications]]>><html>
<h1>Creation of a probe class</h1></html>
<<tiddler [[Observation probes - Example]]>>
Type the text for 'New Tiddler'
The generated class has to:
*Be located in the ''probes'' package of the [[tree hierarchy|SMD - Package tree]], or at least in a sub-package of that package;
*Be named explicitly after the role of the probe in the simulation.

+++?[<span class="exbigbtn">Observation probe full example 1</span>]
{{exsection{
This example illustrates the creation of a probe writing in a file the evolution of the population of agents from specific families in the simulation. This probe is named {{className{ProbeListingAgentsPerCategory}}} and will be put in the {{packageName{fr.univ_artois.lgi2a.similar.customprobes}}} package.
!Code
The following code illustrates the implementation of such a probe. This code is also available as a [[stand alone|files/probes/ProbeListingAgentsPerCategory.java]] file:
<html><pre><object width='100%' height='350px' type='text/plain' data='files/probes/ProbeListingAgentsPerCategory.java' border='0' ></pre></object></html>
}}} ===
{{focusemphasisblock{
This part of the documentation is dedicated to the design and the implementation of observation probes.
}}}
In SIMILAR, a probe is a ''read-only'' component that can ''observe the dynamic state'' of the simulation during ''consistent or half-consistent'' states to extract data from it. These data are then displayed using various means for the users.
Usually, probes are defined to show or export the simulation results.
An observation probe is a class extending the {{className{[[IProbe|../api/fr/lgi2a/similar/microkernel/IProbe.html]]}}} interface, and defining the following methods it defines:
*{{methodName{prepareObservation( )}}}, called by the engine before even initializing the simulation;  +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
This method prepares the observation of a new simulation. It is defined to open the streams or the other resources used during the observation of one simulation.
{{{
public void prepareObservation( );
}}}
}}} ===

*{{methodName{observeAtInitialTimes( ... )}}}, called by the engine after the initialization of the simulation +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
This method triggers the observation of the state of the simulation when the initial time stamp is reached.
{{{
void observeAtInitialTimes(
	SimulationTimeStamp initialTimestamp,
	ISimulationEngine simulationEngine
);
}}}
This method defines the following arguments:
*{{argumentName{initialTimestamp}}} modeling the value of the initial time stamp of the simulation;
*{{argumentName{simulationEngine}}} providing a reference to the simulation engine and the simulation it runs;
}}} ===

*{{methodName{observeAtPartialConsistentTime( ... )}}}, called by the engine after a reaction in the simulation +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
This method triggers the observation of the state of the simulation when at least one level reached a consistent state.
{{{
void observeAtPartialConsistentTime(
	SimulationTimeStamp timestamp,
	ISimulationEngine simulationEngine
);
}}}
This method defines the following arguments:
*{{argumentName{timestamp}}} modeling the value of the half-consistent time stamp of the simulation;
*{{argumentName{simulationEngine}}} providing a reference to the simulation engine and the simulation it runs.
}}} ===

*{{methodName{observeAtFinalTime( ... )}}}, called by the engine after the last reaction of the simulation +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
This method triggers the observation of the state of the simulation when the final consistent state of the simulation is reached.
{{{
void observeAtFinalTime(
	SimulationTimeStamp finalTimestamp,
	ISimulationEngine simulationEngine
);
}}}
This method defines the following arguments:
*{{argumentName{finalTimestamp}}} modeling the value of the final time stamp of the simulation;
*{{argumentName{simulationEngine}}} providing a reference to the simulation engine and the simulation it runs.
}}} ===

*{{methodName{reactToAbortion( ... )}}}, called by the engine when the simulation ended on the request of the user; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
This method triggers the observation of the last half-consistent state reached by the simulation before its abortion.
{{{
public void reactToAbortion( 
	SimulationTimeStamp timestamp,
	ISimulationEngine simulationEngine
);
}}}
This method defines the following arguments:
*{{argumentName{timestamp}}} modeling the time stamp of the last half-consistent state reached by the simulation before the abortion;
*{{argumentName{simulationEngine}}} providing a reference to the simulation engine and the simulation it runs.
}}} ===

*{{methodName{reactToError( )}}}, called by the engine when the execution of the simulation caused an error;  +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
This method triggers the observation of an error thrown by the currently running simulation.
{{{
public void reactToError(
	String errorMessage,
	Throwable cause
);
}}}
This method defines the following arguments:
*{{argumentName{errorMessage}}} modeling the error message associated with the error;
*{{argumentName{cause}}} modeling the error that caused the simulation to stop.
}}} ===

*{{methodName{endObservation( )}}}, called by the engine at the very end of the simulation.  +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
This method is called at the end of the simulation, whatever the reason that caused the simulation to stop (normal end, error, abortion). It is defined to close the streams or the other resources used during the observation of one simulation.
{{{
public void endObservation( );
}}}
}}} ===

The observation of the simulation is based on specific accessors defined in the {{className{[[ISimulationEngine|../api/fr/lgi2a/similar/microkernel/ISimulationEngine.html]]}}} class. They are defined by the following methods:
*{{methodName{getLevels()}}}, getting the identifier of the levels defined for the simulation; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/ISimulationEngine.html#getLevels()]]}}}
*{{methodName{getSimulationDynamicStates()}}}, getting the dynamic state of each level of the simulation; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/ISimulationEngine.html#getSimulationDynamicStates()]]}}}
*{{methodName{getEnvironment()}}}, getting the environment of the simulation; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/ISimulationEngine.html#getEnvironment()]]}}}
*{{methodName{getAgents()}}}, getting the agents currently lying in the simulation; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/ISimulationEngine.html#getAgents()]]}}}
*{{methodName{getAgents(LevelIdentifier)}}}, getting the agents currently lying in a specific level of the simulation. {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/ISimulationEngine.html#getAgents(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier)]]}}}
In SIMILAR, an ''observation probe'' is a software component that can observe and extract data from the dynamic state of the simulation:
*At the ''initial time'' of the simulation;
*At each ''consistent'' or ''half-consistent time'' of the simulation;
*At the ''final time'' of the simulation;
Since simulations do not always execute peacefully, probes also have to manage the case when the simulation fails because of an error. Moreover, since some probes might use external resources, they also have to be notified when a new simulation is about to start or has ended. Consequently, probes are also notified when:
*A ''new simulation'' has been ''started'' with the simulation engine;
*The ''simulation has ended'' (no matter the reason);
*The ''simulation'' ends because of an ''error'';
*The ''simulation'' has been ''aborted''.
<!--{{{-->
<div id='header' class='header'>

<div class='headerShadow'>
<span class='searchBar' macro='search'></span>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
<div id='topMenu' refresh='content'></div>
</div>

<div id='displayArea'>
<div id='leftMenu' refresh='content' tiddler='MainMenu'></div>
<div id='messageArea'></div>
<div id='tiddlersBar' refresh='none' ondblclick='config.macros.tiddlersBar.onTiddlersBarAction(event)'></div>
<div id='tiddlerDisplay'></div>
</div>
<div id='contentFooter' refresh='content' tiddler='contentFooter'></div>
<!--}}}-->
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the agent initialization profiles}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Decision]]  |  [[next step >>|SMD - Natural]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Agent creation - Intro]]>>
!Structure of an agent factory
<<tiddler [[SMD - Agent creation - Structure]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Agent creation - Specifications]]>>
!Creating an agent factory
<<tiddler [[SMD - Agent creation - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Natural]]}}}
The agent factory class has to:
*Be located in the same package than the class of the agent (see [[this page|SMD - Agents skeleton]]);
*Be named explicitly after the category of the agent;
*Be named explicitly after the profile of the created agents;
*Define a static field containing a reference to the ''simulation parameters'';
The method generating an agent instance has to:
*Define the context dependent parameters as arguments;
*Call the appropriate constructor of the agent class;
*Create and set the initial global state of the agent, using the values from the arguments and the static parameters;
*Create, initialize and set the private and public local states of the agent for all the levels where it initially lies, using the values from the arguments and the static parameters;

+++?*[<span class="exbigbtn ">Example</span>]
{{exsection{
[>img[images/simulationModel/lowLevel/factoryTree.png]]
This example is a continuation of the example stated in the definition of [[public local states|SMD - Public local states]] and of the [[perception process|SMD - Perception]] of the ''lion'' agent of a ''wildlife simulation''.

The ''lion'' agent is defined in the [[AgtLion class|files/simulationModel/lowLevel/AgtLion.java]]. It lies only in the ''Savannah'' level and therefore is characterized by:
*A public local state implemented as the {{className{[[AgtLionPLSInSavannahLevel|files/simulationModel/highLevel/AgtLionPLSInSavannahLevel.java]]}}} class and defining:
**Its age;
**Its location;
*A private local state implemented as the {{className{[[AgtLionHLSInSavannahLevel|files/simulationModel/lowLevel/AgtLionHLSInSavannahLevel.java]]}}} class and defining:
**A threshold age over which the lion ignores gazelles;
**A threshold distance over which the lion cannot see gazelles;
*An empty global state defined by the {{className{[[AgtLionGS|files/simulationModel/lowLevel/AgtLionGS.java]]}}} class;
In this example, we assume that:
*The parameters of the simulation are defined in the {{className{[[WildlifeSimulationParam|files/simulationModel/lowLevel/WildlifeSimulationParam.java]]}}} class;
*The random generation strategy defines a method:
{{{
public long randomLong( long rangeMin, long rangeMax );
}}}
The initialization profile defined in this example is such that:
*The age is initially equal to {{{0}}};
*The initial location is a context dependent value;
*The threshold age is a random value within the range {{{[0;5]}}} defined in the simulation parameters;
*The threshold distance is defined in the simulation parameters as equal to {{{500}}};
!Code
Such a lion agent generation factory is implemented with the following code. The sources of this class are also available as a [[stand alone|files/simulationModel/lowLevel/AgtLionFactory.java]] file.
<html><pre><object width='100%' height='350px' type='text/plain' data='files/simulationModel/lowLevel/AgtLionFactory.java' border='0' ></pre></object></html>
}}} ===
We strongly recommend designers to keep from using directly the constructor of the agents to create new agents. Indeed:
*The [[parameters class|SMD - Tools preparation - Parameters]] of the simulation is more difficult to use in that context, since a reference to the parameters has to be available;
*The addition of initialization profiles to an agent implies the modification of its class (//i.e.// addition of new constructors). Therefore, the more initialization profiles are defined, the more unreadable the class of the agent becomes.
Instead, we defend that agents have to be created using ''factories'', where each factory embodies ''one'' initialization profile.
The agent factory usually takes the form of a class using the ''//factory// design pattern'', storing the instance of the ''parameter'' class as a ''static value''. Agents are created using ''static factory methods'' having the ''context dependent'' parameters ''as arguments''.

[img(100%,)[images/simulationModel/lowLevel/agentFactoryStructure.png]]

The role of the factory method is to:
*Create the instance of the agent class (//i.e.// an instance of the {{className{IAgent4Engine}}} interface);
*Initialize the global state of the created agent;  +++?*[<span class="docsmallbtn ">Documentation</span>]
{{docsection{
No specific method is defined in the {{className{IAgent4Engine}}} interface to perform such a task, since this is an implementation-dependent feature. Users have to define this method themselves if they use only the micro-kernel.
Otherwise, the {{className{[[AbstractAgent|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractAgent.html]]}}} class from the common libs includes such a feature, in the {{methodName{[[initializeGlobalState(IGlobalState)|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractAgent.html#initializeGlobalState(fr.univ_artois.lgi2a.similar.microkernel.agents.IGlobalState)]]}}} method.
}}} === +++?*[<span class="exsmallbtn ">Example</span>]
{{exsection{
The initialization of the global state of an agent is made with the following instructions:
{{{
AbstractAgent theAgent = ...;
IGlobalState initialGlobalState = ...;
theAgent.initializeGlobalState(
	initialGlobalState
);
}}}
}}} ===

*Define the public and private local states of the agent in its initial levels; +++?*[<span class="docsmallbtn ">Documentation</span>]
{{docsection{
The initial levels of an agent are specified using the following method:
*{{methodName{includeNewLevel(...)}}} specifying both a private and a public local state for a level; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html#includeNewLevel(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier, fr.univ_artois.lgi2a.similar.microkernel.agents.ILocalStateOfAgent, fr.univ_artois.lgi2a.similar.microkernel.agents.ILocalStateOfAgent)]]}}}
}}} === +++?*[<span class="exsmallbtn ">Example</span>]
{{exsection{
The initialization of the public local state of an agent in a ''Savannah'' level is made with the following instructions:
{{{
IAgent4Engine theAgent = ...;
ILocalStateOfAgent initialPublicLocalStateInSavannah = ...;
ILocalStateOfAgent initialPrivateLocalStateInSavannah = ...;
LevelIdentifier savannahIdentifier = ...;
theAgent.includeNewLevel(
	savannahIdentifier,
	initialPublicLocalStateInSavannah,
	initialPrivateLocalStateInSavannah 
);
}}}
}}} ===

+++?*[<span class="exbigbtn ">Structure example: Default case</span>]
{{exsection{
This example is a continuation of the example stated in the definition of [[public local states|SMD - Public local states]] and of the [[perception process|SMD - Perception]] of the ''lion'' agent of a ''wildlife simulation''.

The ''lion'' agent is characterized by:
*A public local state defining:
**Its age;
**Its location;
*A private local state defining:
**A threshold age over which the lion ignores gazelles;
**A threshold distance over which the lion cannot see gazelles.
In this example, we assume that:
*The [[parameters of the simulation|SMD - Tools preparation - Parameters]] are defined in the {{className{WildlifeSimulationParam}}} class;
*The age is initially equal to {{{0}}};
*The initial location is a context dependent value;
*The threshold age is a random value within the range {{{[0;5]}}} defined in the simulation parameters;
*The threshold distance is defined in the simulation parameters as equal to {{{500}}};
Then, the lion agent generation factory has the following shape:

[img(98%,)[images/simulationModel/lowLevel/agentFactoryStructureEx1.png]]
}}} ===


+++?*[<span class="exbigbtn ">Structure example: Defining two initialization profiles</span>]
{{exsection{
This example is a continuation of the example stated in the definition of [[public local states|SMD - Public local states]] and of the [[perception process|SMD - Perception]] of the ''lion'' agent of a ''wildlife simulation''.

The ''lion'' agent is characterized by:
*A public local state defining:
**Its age;
**Its location;
*A private local state defining:
**A threshold age over which the lion ignores gazelles;
**A threshold distance over which the lion cannot see gazelles.
In this example, we assume that:
*The [[parameters of the simulation|SMD - Tools preparation - Parameters]] are defined in the {{className{WildlifeSimulationParam}}} class;
*The age is initially equal to {{{0}}};
*The initial location is a context dependent value;
*The threshold age is a value within the range {{{[0;5]}}} defined in the simulation parameters;
*The threshold distance is defined in the simulation parameters as equal to {{{500}}};
*The lions can have two different profiles:
**''Normal'' lions chase gazelles that are in the second half of the threshold age range (in this example {{{[2.5;5]}}});
**''Fierce'' lions chase gazelles that are below the maximal age {{{5}}};
In this case, two different shapes can be given to the lion agent factory:
!Single factory approach
[img(98%,)[images/simulationModel/lowLevel/agentFactoryStructureEx2.png]]
!Multiple factories approach
[img(98%,)[images/simulationModel/lowLevel/agentFactoryStructureEx3.png]]
}}} ===
The initialization profile defined in an agent factory is characterized by:
*Some parameters coming from the [[parameters class|SMD - Tools preparation - Parameters]] of the simulation;  +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
For instance parameters related to the default values of the elements of the public or private local states (//e.g.// a default value, a range for the default values) or related to computations precision (//e.g.// the epsilon used in double values comparison)
}}} ===

*Other parameters coming from the context of the construction of the agent; +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
For instance the current density of a specific agent population in the simulation, the current value of a private local state of an agent, etc.
}}} ===

*The way these parameters are used, in order to:
**Call the constructor of the agent (to initialize the private local state of the agent);
**Create the initial global state of the agent;
**Create the initial public local states of the agent;
An agent is created with such factories by calling one of its factory methods and providing a value to the context dependent parameters (see the image).

[img(100%,)[images/simulationModel/lowLevel/agentFactoryPrinciple.png]]
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Identification of the agents}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Levels identification]]  |  [[next step >>|SMD - Level skeleton]]}}}
<html><hr class="topSep"/></html>
The second concrete step in the design of the simulation model is the identification of the agents participating in the simulation. In this step, no precise knowledge about the agents is necessary. The only important point here is to ''identify the existence of the agents, and give them a unique category''^^''1''^^.

Once the agent categories are known, the user can create a class summing up these information.

{{focusemphasisblock{This step focuses on the creation of a class listing all the agent categories of the simulation.}}}
~~//''__1:__ A name identifying the equivalence class of the agent. Usually, agents having the same category have the same perceptible state.''//~~
!Creating an agent category
In SIMILAR, an agent category is modeled as an instance of the {{className{[[AgentCategory|../api/fr/lgi2a/similar/microkernel/AgentCategory.html]]}}} class. An agent category is built using the following constructor:
{{{
public AgentCategory( String levelName );
}}}
Note that the {{argumentName{levelName}}} argument cannot be null. Moreover, its value has to be different for each category being modeled.

+++?[<span class="exbigbtn">Agent category creation example</span>]
{{exsection {
This example illustrates the creation of the agent category named "city bus":
{{{
AgentCategory cityBusCategory = new AgentCategory( "city bus" );
}}}
}}} ===

!The agent categories list
An agent category is unique and does not change over the simulation. To avoid misspelling errors during the implementation, we highly recommend to create an enum-like structure containing all the agent categories of the simulation. This structure is called the ''"agent categories list"''.
!!Creating the agent categories list
[>img[images/simulationModel/highLevel/categoriesList_package.png]]
The ''"agent categories list"'' class is designed to avoid misspelling errors in the simulation. It relies on a specific structure supporting inheritance. Owing to this property, simulation models +++^34em^*@[extending this simulation model]
Simulations which model includes additional features to the model of another simulation like new levels, new agents, new influences, //etc.//
=== can be created.

This class has to:
*Be //public//;
*Define a single //protected// constructor with no arguments;
*Contain as many //public statc final// fields from the {{{AgentCategory}}} class as the number of agent categories in the simulation.
*Be located into the ''"agents''" package.
{{clear{}}}
+++?[<span class="exbigbtn">Agent category creation example</span>]
{{exsection {
This example illustrates the creation of a level identifiers list called {{className{MyAgentCategoriesList}}}. This list contains the "car", "pedestrian", "city bus" and "market" agent categories.

This example is also available in a [[stand alone file|./files/simulationModel/highLevel/MyAgentCategoriesList.java]].
!Code
<html><pre><object width='100%' height="500" type='text/plain' data='./files/simulationModel/highLevel/MyAgentCategoriesList.java' border='0' ></pre></object></html>
}}} ===

!!Using the list of agent categories
Once the class of the agent categories list is declared, it becomes no longer necessary to create instances of the {{className{[[AgentCategory|../api/fr/lgi2a/similar/microkernel/AgentCategory.html]]}}} class to have access to the feratures of the simulation. Instead, users have to refer to a static field of the ''"agent categories list"'' class.

+++?[<span class="exbigbtn">Usage example</span>]
{{exsection {
This example illustrates the use of the "agent categories list" in replacement to the manual creation of agent categories, in the context of checking if a public local state belongs to an agent from the "Car" category.

Without using the "agent categories list", the comparison is made with the following instructions:
{{{
ILocalStateOfAgent state = ...;
AgentCategory agtCat = new AgentCategory ( "Car" );
if( state.getCategoryOfAgent().isA( agtCat ) ){
	// The agent is a "car"
} else {
	// The agent is not a "car"
}
}}}
When using the list, the code becomes:
{{{
ILocalStateOfAgent state = ...;
if( state.getCategoryOfAgent().isA( MyAgentCategoriesList.CAR) ){
	// The agent is a "car"
} else {
	// The agent is not a "car"
}
}}}
}}} ===

{{nextButton{[[Go to the next step >>|SMD - Level skeleton]]}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the skeleton of the agents}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Environment skeleton]]  |  [[next step >>|SMD - Time model]]}}}
<html><hr class="topSep"/></html>
The agents of the simulation also rely on an incremental design process. Therefore, a skeleton has to be defined for them before going for the operational code of the simulation.

{{focusemphasisblock{
This step focuses on the creation of a skeleton class for each agent that was identified during the [[agents identification|SMD - Agents identification]] phase.
}}}
<<tiddler [[SMD - Agents skeleton - Structure]]>>
<<tiddler [[SMD - Agents skeleton - Implementation]]>>
<<tiddler [[SMD - Agents skeleton - Create class]]>>
{{nextButton{[[Go to the next step >>|SMD - Time model]]}}}
!Creating an agent class in SIMILAR
The constructor of the agent has to comply with the following requirements:
*Its category has to be set;
*Its initial global state is set later (see [[details|SMD - Agent creation]]);
*Its initial public local states are set later (see [[details|SMD - Agent creation]]);
*Its initial private local states are set later (see [[details|SMD - Agent creation]]);
The generated class has to:
*Be located in a sub-package of the ''agents'' package:
**The sub-package has to be named after the category of the agent;
**The sub-package has to contain only lower case letters or figures\(^2\);
**The sub-package has to start with a letter\(^2\);
*Be named explicitly after the category of the agent;

The implementation of the methods of the skeleton (see the previous section) has either to be done manually (micro-kernel only approach) or with the {{className{[[AbstractAgent|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractAgent.html]]}}} class (micro-kernel with common libs).

+++?[<a class="exbigbtn">Agent skeleton full example</a>]
{{exsection {
[>img[images/simulationModel/highLevel/agentSkeletonTree.png]]
This step illustrates the creation of an agent named "City bus". The source of the class modeling the "City bus" agent is located in the ''agents.citybus'' package of the source tree hierarchy (see the image):@@clear:right;display:block;margin:0;padding:0;@@
*The micro-kernel only approach is implemented as the {{className{CityBusAgent}}} class +++?[<a class="implsmallbtn">Implementation</a>]
{{implsection {
The following code illustrates the implementation of the "City bus" agent using only the micro-kernel. The implementation of its methods follows the implementation recommendations of each method. The following code is also available as a [[stand alone file|./files/simulationModel/highLevel/CityBusAgent.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/highLevel/CityBusAgent.java' border='0' ></pre></object></html>
}}} ===

*The micro-kernel with common libs approach is implemented as the {{className{CityBusAgent2}}} class +++?[<a class="implsmallbtn">Implementation</a>]
{{implsection {
The following code illustrates the implementation of the "City bus" agent using both the micro-kernel and the common libs. The following code is also available as a [[stand alone file|./files/simulationModel/highLevel/CityBusAgent2.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/highLevel/CityBusAgent2.java' border='0' ></pre></object></html>
}}} ===

}}}===

\(_{\underline{2:}\text{ These constraints come from java best practices.}}\)
!Specifications and implementation instructions
[<img(50%,)[images/simulationModel/highLevel/agentDesignOutline2.png]]
In SIMILAR, the agents are modeled as instances of the {{className{[[IAgent4Engine|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html]]}}} interface. This interface defines methods providing access to the core elements of an agent (global memory state and public local states) and defines the core behavior of the agent (perception, memory revision, decision).

To facilitate simulation revisions, each core element and behavior is reified as a separate method.

In the first step of the specification of the agents, only subset of the content of each agent is specified and implemented. Therefore, the unspecified methods have to throw an {{className{UnsupportedOperationException}}} at this stage.

In this skeleton, the following elements have to be defined:
*The ''category'' of the agent; <<tiddler [[SMD - Agents skeleton - Implementation - Category buttons]]>>
*The access to the ''levels'' where the agent lies; <<tiddler [[SMD - Agents skeleton - Implementation - Levels buttons]]>>
*The access to the ''perceived data'' of the agent; <<tiddler [[SMD - Agents skeleton - Implementation - Perception buttons]]>>
*The access to the ''global state'' of the agent; <<tiddler [[SMD - Agents skeleton - Implementation - Global state buttons]]>>
*The access to the ''public local states'' of the agent; <<tiddler [[SMD - Agents skeleton - Implementation - Public local states buttons]]>>
*The access to the ''private local states'' of the agent; <<tiddler [[SMD - Agents skeleton - Implementation - Private local states buttons]]>>
{{bigemphasisblock{
Note that the [[common libs|commonLibs/index.html]]<script>place.lastChild.target="_self";</script> of the micro-kernel defines the {{className{[[AbstractAgent|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractAgent.html]]}}} class providing a default implementation of these features.
}}}
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The access to the category of the agent is defined by the following methods:
*The {{methodName{getCategory()}}} method; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent.html#getCategory()]]}}}
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of these methods usually consists in:
*Adding a field to the class having the type {{className{AgentCategory}}};
*Setting its initial value in the constructor of the class;
*Granting access to that field in the appropriate methods (//i.e.// {{methodName{getCategory( )}}}).
}}} ===
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The access to the global state of the agent is defined by the following method:
*The {{methodName{getGlobalState( )}}} method; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent.html#getGlobalState()]]}}}
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
In SIMILAR, the global state of an agent is a sub class of the {{className{[[IGlobalState|../api/fr/lgi2a/similar/microkernel/agents/IGlobalState.html]]}}} class. This class and its usage are [[described later|SMD - Global state - Plan]].

To facilitate the definition of various initialization profiles of the global state of the agent, its inital value should not be defined within the constructor. Instead, we uphold that a ''setter has to be defined, to delay the initialization'' when it becomes appropriate.
}}} === +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
This example illustrates the management of the global state of an agent named "City bus". This agent is declared in the class called {{className{CityBusAgent}}}.
{{{
public class CityBusAgent implements IAgent4Engine {
	
	[...]
	
	private IGlobalState globalState;

	[...]

	public IGlobalState getGlobalState( ){
		return this.globalState;
	}
	
	public void initializeGlobalState(
		IGlobalState initialGlobalState
	){
		if( initialGlobalState == null ){
			throw new IllegalArgumentException( "The arguments cannot be null." );
		}
		this.globalState = initialGlobalState;
	}
	
	[...]

}
}}}
}}} ===
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The access to the levels where the agent lies is defined by the following methods: 
*The {{methodName{getLevels( )}}} method; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent.html#getLevels()]]}}}
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
Since this notion is tightly bound with the existence of a local state for that level. Therefore, to simplify our task, we consider that this method benefits from an appropriate data structure for the public local state of the agent (see the last item of this enumeration). Assuming that the public local states are stored using a {{className{Map<LevelIdentifier,ILocalStateOfAgent>}}} data structure, the implementation of this method consists in retrieving the keys of that structure.
}}} ===  +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
Assuming that the public local states of the agent are stored in a field named {{fieldName{publicLocalStates}}}, the code of the skeleton of the "City bus" agent becomes:
{{{
public class CityBusAgent implements IAgent4Engine {
	
	[...]

	private Map<LevelIdentifier,ILocalStateOfAgent> publicLocalStates;
	
	[...]
			
	public CityBusAgent(){

		[...]

		this.publicLocalStates = new LinkedHashMap<LevelIdentifier, ILocalStateOfAgent>();

		[...]

	}

	public Set<LevelIdentifier> getLevels() {
		return this.publicLocalStates.keySet();
	}
	
	[...]

}
}}}
}}} ===
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The access to the perceived data of the agent is defined by the following methods:
*{{methodName{getPerceivedData( )}}} gets the lastly perceived data from ''all the levels'' where the agent lies; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html#getPerceivedData()]]}}}
*{{methodName{setPerceivedData(...)}}} sets the lastly perceived data from ''a level''; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html#setPerceivedData(fr.univ_artois.lgi2a.similar.microkernel.agents.IPerceivedData)]]}}}
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
In SIMILAR, the perceived data of an agent from a level are modeled as instances of the {{className{IPerceivedData}}} class. Because of the signature of the perceived data-related methods, designers do not have much freedom in the implementation of this part of the IAgent interface. It has to revolve around a filed having the type {{className{Map<LevelIdentifier, IPerceivedData>}}}.
}}} === +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
This example illustrates the implementation of the perceived data-related methods of an agent named "City bus". This agent is declared in the class called {{className{CityBusAgent}}}.
{{{
public class CityBusAgent implements IAgent4Engine {
	
	[...]

	private Map<LevelIdentifier, IPerceivedData> lastPerceivedData;
	
	[...]
			
	public CityBusAgent(){

		[...]

		this.lastPerceivedData = new LinkedHashMap<LevelIdentifier, IPerceivedData>();

		[...]

	}
	
	[...]

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Map<LevelIdentifier, IPerceivedData> getPerceivedData() {
		return this.lastPerceivedData;
	}

	/**
	 * 
	 * 
	 * {@inheritDoc}
	 * @param perceivedData
	 */
	@Override
	public void setPerceivedData(
		IPerceivedData perceivedData
	) {{
		if( perceivedData == null ){
			throw new IllegalArgumentException( "The arguments cannot be null." );
		}
		this.lastPerceivedData.put( 
			perceivedData.getLevel(), 
			perceivedData 
		);
	}
	
	[...]

}
}}}
}}} ===
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The notion of level where an agent lies is tightly bound with the notion of private local state. Indeed, if an agent has a private local state in a specific level, then the agent is necessarily lying in that level. Therefore, adding a private local state to an agent is synonym of adding that agent to a level.
!Specification of the access methods
The access to the private local states of the agent is defined by the following methods:
*{{methodName{getPrivateLocalState(LevelIdentifier)}}} gets the private local state of an agent for a specific level; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent.html#getPrivateLocalState(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier)]]}}}
*{{methodName{includeNewLevel(...)}}} adds an agent to a level; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html#includeNewLevel(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier, fr.univ_artois.lgi2a.similar.microkernel.agents.ILocalStateOfAgent, fr.univ_artois.lgi2a.similar.microkernel.agents.ILocalStateOfAgent)]]}}}
*{{methodName{excludeFromLevel(...)}}} removes the agent from a level; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html#excludeFromLevel(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier)]]}}}
}}} ===  +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
In SIMILAR, the ''private local states'' of an agent from a level are modeled as instances of the {{className{ILocalStateOfAgent4Engine}}} class. This class and its usage are [[described later|SMD - Perception]].

Because of the signature of the private local state-related methods, designers do not have much freedom in the implementation of this part of the {{className{IAgent4Engine}}} interface. It usually revolves around a field having the type {{className{Map<LevelIdentifier,ILocalStateOfAgent>}}}
}}} ===  +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
This example illustrates the management of the private local states of an agent named "City bus". This agent is declared in the class called {{className{CityBusAgent}}}.
{{{
public class CityBusAgent implements IAgent4Engine {
   
   [...]

   private Map<LevelIdentifier,ILocalStateOfAgent> privateLocalStates;

   [...]
   
   public CityBusAgent( ) {
      
      [...]
            
      this.privateLocalStates = new LinkedHashMap<LevelIdentifier,ILocalStateOfAgent>();
      
      [...]
   }
   
   [...]
   
   public ILocalStateOfAgent getPrivateLocalState( 
         LevelIdentifier levelIdentifier 
   ) {
      if( levelIdentifier == null ){
         throw new IllegalArgumentException( "The arguments cannot be null." );
      }
      ILocalStateOfAgent result = this.privateLocalStates.get( levelIdentifier );
      if( result == null ){
         throw new NoSuchElementException( 
            "The agent does not define a private local " + 
            "state for the level '" + levelIdentifier + "'." 
         );
      }
      return result;
   }
   
   public void includeNewLevel( 
      LevelIdentifier levelIdentifier, 
      ILocalStateOfAgent publicLocalState,
      ILocalStateOfAgent privateLocalState 
   ) {
      if( levelIdentifier == null || publicLocalState == null || privateLocalState == null ){
         throw new IllegalArgumentException( "The arguments cannot be null." );
      }
      if( ! this.getLevels().contains( levelIdentifier ) ){
         this.privateLocalStates.put( levelIdentifier, privateLocalState );
         [...]
      }
   }
   
   public void excludeFromLevel( 
      LevelIdentifier levelIdentifier 
   ) {
      if( levelIdentifier == null ){
         throw new IllegalArgumentException( "The arguments cannot be null." );
      }
      if( this.getLevels().contains( levelIdentifier ) ){
         this.privateLocalStates.remove( levelIdentifier );
         [...]
      }
   }
   
   [...]

}
}}}
}}} ===
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The notion of level where an agent lies is tightly bound with the notion of public local state. Indeed, if an agent has a public local state in a specific level, then the agent is necessarily lying in that level. Therefore, adding a public local state to an agent is synonym of adding that agent to a level.
!Specification of the access methods
The access to the public local states of the agent is defined by the following methods:
*{{methodName{getPublicLocalState(LevelIdentifier)}}} gets the public local state of an agent for a specific level; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent.html#getPublicLocalState(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier)]]}}}
*{{methodName{getPublicLocalStates( )}}} gets the public local state of an agent all the levels; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html#getPublicLocalStates()]]}}}
*{{methodName{includeNewLevel(...)}}} adds an agent to a level; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html#includeNewLevel(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier, fr.univ_artois.lgi2a.similar.microkernel.agents.ILocalStateOfAgent, fr.univ_artois.lgi2a.similar.microkernel.agents.ILocalStateOfAgent)]]}}}
*{{methodName{excludeFromLevel(...)}}} removes the agent from a level; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html#excludeFromLevel(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier)]]}}}
}}} ===  +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
In SIMILAR, the ''public local states'' of an agent from a level are modeled as instances of the {{className{ILocalStateOfAgent4Engine}}} class. This class and its usage are [[described later|SMD - Perception]].

Because of the signature of the public local state-related methods, designers do not have much freedom in the implementation of this part of the {{className{IAgent4Engine}}} interface. It usually revolves around a field having the type {{className{Map<LevelIdentifier,ILocalStateOfAgent>}}}
}}} ===  +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
This example illustrates the management of the public local states of an agent named "City bus". This agent is declared in the class called {{className{CityBusAgent}}}.
{{{
public class CityBusAgent implements IAgent4Engine {
   
   [...]

   private Map<LevelIdentifier,ILocalStateOfAgent> publicLocalStates;

   [...]
   
   public CityBusAgent( ) {
      
      [...]
            
      this.publicLocalStates = new LinkedHashMap<LevelIdentifier,ILocalStateOfAgent>();
      
      [...]
   }
   
   [...]
   
   public ILocalStateOfAgent getPublicLocalState( 
         LevelIdentifier levelIdentifier 
   ) {
      if( levelIdentifier == null ){
         throw new IllegalArgumentException( "The arguments cannot be null." );
      }
      ILocalStateOfAgent result = this.publicLocalStates.get( levelIdentifier );
      if( result == null ){
         throw new NoSuchElementException( 
            "The agent does not define a public local " + 
            "state for the level '" + levelIdentifier + "'." 
         );
      }
      return result;
   }
   
   public Map<LevelIdentifier,ILocalStateOfAgent> getPublicLocalStates( ){
      return this.publicLocalStates;
   }
   
   public void includeNewLevel( 
      LevelIdentifier levelIdentifier, 
      ILocalStateOfAgent publicLocalState,
      ILocalStateOfAgent privateLocalState 
   ) {
      if( levelIdentifier == null || publicLocalState == null || privateLocalState == null ){
         throw new IllegalArgumentException( "The arguments cannot be null." );
      }
      if( ! this.getLevels().contains( levelIdentifier ) ){
         this.publicLocalStates.put( levelIdentifier, publicLocalState );
         [...]
      }
   }
   
   public void excludeFromLevel( 
      LevelIdentifier levelIdentifier 
   ) {
      if( levelIdentifier == null ){
         throw new IllegalArgumentException( "The arguments cannot be null." );
      }
      if( this.getLevels().contains( levelIdentifier ) ){
         this.publicLocalStates.remove( levelIdentifier );
         [...]
      }
   }
   
   [...]

}
}}}
}}} ===
!Structure of an agent in SIMILAR
[>img(50%,)[images/simulationModel/highLevel/agentDesignOutline1.png]]
In SIMILAR, an agent is the sum of the following elements^^''1''^^:
*A ''category'', modeling the //"type"// of the agent;
*A ''global state'';
*A ''global state revision'' process;
*A ''public local state'' for each level of the agent;
*A ''private local state'' for each level of the agent;
*A ''perceived data'' for each level of the agent;
*A ''perception'' process for each level of the agent;
*A ''decision'' process for each level of the agent.
\(_{\underline{1:}\text{ See the reference papers on SIMILAR and IRM4MLS for the full description of these elements.}}\)
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Specification of the decision}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Global state revision]]  |  [[next step >>|SMD - Agent creation]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Decision - Introduction]]>>
!Structure of the decision process 
<<tiddler [[SMD - Decision - Structure]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Decision - Specifications]]>>
!Writing the decision phase of an agent class
<<tiddler [[SMD - Decision - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Agent creation]]}}}
The implementation of this method consists in:
*Identifying the level from which the decisions are made;
*Casting the global state of the agent in the appropriate class, to access its various data;
*Casting the private and public local states of the agent in the appropriate class, to access their various data;
*Casting the perceived data of the agent in the appropriate class, to access its various data;
*Creating influences based on the read information, and adding them to the {{argumentName{producedInfluences}}} map;
During the redaction of the decision process, the information required by the decisions can become clearer. Therefore, this step will likely lead to the revision of:
*The data from the [[private local state|SMD - Private local states]] used as a parameter of the decisions;
*The [[perceived data|SMD - Perception - Perceived data]] necessary to perform the decisions;
*The [[perception process|SMD - Perception]] as a side effect of the revision of the perceived data;
*The data from the [[global state|SMD - Global state model]] that are necessary to perform the decisions;
*The [[global state revision process|SMD - Global state revision]] as a side effect of the revision of the global state;
*The [[regular influences|SMD - Influences skeleton]] produced by the decisions: it can lead either to the addition of new metadata to existing regular influences, or the creation of new regular influences;
*The [[influence relation graph|SMD - Level skeleton]]: new levels can be added to the levels that can be influenced by the level from which the decision is made;
+++?*[<span class="exbigbtn ">Decision process full example</span>]
{{exsection{
[>img[images/simulationModel/lowLevel/decisionTree.png]]
This example is a continuation of the example started in the documentation of the [[perceived data model|SMD - Perception - Perceived data]].
In this example, a ''lion'' agent decides to ''eat'' the closest ''gazelle'' agent. If the agent is close enough, it directly eats the gazelle. Otherwise, it ''moves towards'' the gazelle. Note that if two gazelles are at the same distance, then the agent chooses one of them randomly.

The notion of "close engouh" implies the definition of a threshold distance, under which the action is possible. This threshold belongs purely to the decision process of the agent, and therefore has to be included in its [[global state|SMD - Global state model]] or in its [[private local state|SMD - Private local states]]. In this example, it is added to the private local state of the "Lion" agent in the "Savannah" level.
!Code
We assume that the following influences are defined:
*The ''eat'' influence is implemented as the {{{RISavannahEat}}} class, defining a constructor having the following signature:
{{{
public RISavannahEat( 
	AgtLionPLSInSavannahLevel predator, 
	AgtGazellePLSInSavannahLevel prey,
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound
)
}}}
*The ''move towards'' influence is implemented as the {{{RISavannahMove}}} class, defining a constructor having the following signature:
{{{
public RISavannahMove( 
	AgtLionPLSInSavannahLevel predator,
	double desiredX,
	double desiredY,
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound
)
}}}
We also assume that the [[random number generation class|SMD - Tools preparation - Random]] provides the following tool method getting a random element within a list:
{{{
public <T> T randomElement( List<T> list );
}}}
Finally, we assume that the private local state of the agent is implemented as a {{className{AgtLionHLSInSavannahLevel}}} class defining the {{methodName{getEatDistanceThreshold()}}} method, modeling the maximal distance between a lion and a prey to consider them as "close".

The implementation of such a decision process of the ''lion'' agent from the ''Savannah'' level corresponds to the following code. The sources of this class are also available in a [[stand alone file|files/simulationModel/lowLevel/AgtLion2.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/lowLevel/AgtLion2.java' border='0' ></pre></object></html>
}}} ===
The behavior of an agent is defined by three different steps (see the image):
*The ''perception phase'', where the agent decodes the data from the public local dynamic state of the perceptible levels, identifies the relevant data and stores them into a ''perceived data set'';
*The ''global state revision phase'', where the agent revises its global state using the value of its former global state and the recently perceived data;
*The ''decision phase'', where the agent uses its perceived data and its revised global state to determine what it does;
{{focusemphasisblock{
This step of the methology focuses on the implementation of the //decision phase// of each agent.
}}}
[img(100%,)[images/simulationModel/lowLevel/agentBehaviorModel_decision.png]]
[>img(45%,)[images\simulationModel\lowLevel\agentDesignOutline6.png]]
In the micro-kernel of SIMILAR, the decision process is modeled by the following method of the {{className{[[IAgent4Engine|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html]]}}} interface:
{{{
public void decide(
	LevelIdentifier levelId,
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound,
	IGlobalState globalState,
	ILocalStateOfAgent publicLocalState,
	ILocalStateOfAgent privateLocalState,
	IPerceivedData perceivedData,
	InfluencesMap producedInfluences
);
}}}
{{clearright{}}}
This method defines the following arguments:
*{{argumentName{levelId}}} corresponds to the identifier of the level from which the decision is made;
*{{argumentName{timeLowerBound}}} identifies the lower bound of the transitory period for which the decision is made;
*{{argumentName{timeUpperBound}}} identifies the upper bound of the transitory period for which the decision is made;
*{{argumentName{globalState}}} corresponds to the revised global state on which the decisions are based;
*{{argumentName{publicLocalState}}} models the public local state of the agent in the level where the decision is made;
*{{argumentName{privateLocalState}}} models the private local state of the agent in the level where the decision is made;
*{{argumentName{perceivedData}}} models the data that were perceived from the level having the identifier {{argumentName{levelId}}}, during the transitory period ]{{argumentName{timeLowerBound}}}, {{argumentName{timeUpperBound}}}[;
*{{argumentName{producedInfluences}}} models where the influences produced by the decisions of the agents are stored. Basically, it corresponds to the value returned by the decision application presented above; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection {
<<tiddler [[InfluencesMap - Documentation]]>>
}}} ===

<<tiddler [[System influences - Specifications]]>>
In SIMILAR, the decision model can be seen as an ''application'' taking into parameters the ''perceived data'' from the level where the decision is made and the +++^31em^*@[<strong>revised global state</strong>]The value of the global state of the agent after the global state revision phase.=== of the agent, and returning the ''influences'' modeling the actions the agent wishes to perform in the various influenceable levels.

<<tiddler [[System influences - Structure]]>>
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the skeleton of the environment}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Level skeleton]]  |  [[next step >>|SMD - Agents skeleton]]}}}
<html><hr class="topSep"/></html>
The environment of the simulation also relies on an incremental design process. Therefore, a skeleton has to be defined for it before going for the operational code of the simulation.

{{focusemphasisblock{
This step focuses on the creation of a skeleton class for the environment.
}}}
!Structure of the environment in SIMILAR
<<tiddler [[SMD - Environment skeleton - Structure]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Environment skeleton - Specifications]]>>
!Creating the environment in SIMILAR
<<tiddler [[SMD - Environment skeleton - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Agents skeleton]]}}}
The constructor of the environment has to comply with the following requirements:
*The ''initial public local states'' of the environment are set later (see [[details|SMD - Initial state]]);
*The ''initial private local states'' of the environment are set later (see [[details|SMD - Initial state]]);
The generated class has to:
*Be located in the ''environment'' package of the package tree hierarchy.
The implementation of the methods of the skeleton (see the previous section) has either to be done manually (micro-kernel only approach) or with the {{className{[[AbstractEnvironment|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractEnvironment.html]]}}} class (micro-kernel with common libs).

+++?*[<span class="exbigbtn ">Environment skeleton full example</span>]
{{exsection{
[>img[images/simulationModel/highLevel/environmentSkeletonTree.png]]
This example illustrates the creation of the skeleton of an environment. The source of class modeling the environment is located in the {{packageName{environment}}} package of the source tree hierarchy (see the image):
{{clear{}}}
*The micro-kernel only approach is implemented as the {{className{EnvironmentSkeleton}}} class +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The following code illustrates the implementation of the environment using only the micro-kernel. The sources of this class are also available in a [[stand alone file|./files/simulationModel/highLevel/EnvironmentSkeleton.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/highLevel/EnvironmentSkeleton.java' border='0' ></pre></object></html>
}}} ===

*The micro-kernel with common libs approach is implemented as the {{className{EnvironmentSkeleton2}}} class +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The following code illustrates the implementation of the environment using both the micro-kernel and the common libs. The sources of this class are also available in a [[stand alone file|./files/simulationModel/highLevel/EnvironmentSkeleton2.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/highLevel/EnvironmentSkeleton2.java' border='0' ></pre></object></html>
}}} ===

}}} ===
To facilitate the design of simulations where the initial state of the simulation can easily be changed, we advise users to avoid creating the private local states of the environment during its construction. Indeed, having different initialization process for the environment would require the definition of a constructor per initialization process. This goes against the best practices in object oriented engineering.

Instead, we advise to create a method setting the value of each private local state. This way, the class of the environment won't be changed if a new initialization process is created for the environment.

To facilitate the extension of the model of the agents, we also advise designers to rely on a map rather than on a field per level. Indeed, this approach supports the addition of new levels with less efforts.

Knowing all these information, and that a private local state of an environment is an instance of the {{className{[[ILocalStateOfEnvironment|../api/fr/lgi2a/similar/microkernel/environment/ILocalStateOfEnvironment.html]]}}} interface, the environment should declare a field having the type {{className{Map<LevelIdentifier,ILocalStateOfEnvironment>}}}.
To facilitate the design of simulations where the initial state of the simulation can easily be changed, we advise users to avoid creating the public local states of the environment during its construction. Indeed, having different initialization process for the environment would require the definition of a constructor per initialization process. This goes against the best practices in object oriented engineering.

Instead, we advise to create a method setting the value of each public local state. This way, the class of the environment won't be changed if a new initialization process is created for the environment.

To facilitate the extension of the model of the agents, we also advise designers to rely on a map rather than on a field per level. Indeed, this approach supports the addition of new levels with less efforts.

Knowing all these information, and that a public local state of an environment is an instance of the {{className{[[ILocalStateOfEnvironment|../api/fr/lgi2a/similar/microkernel/environment/ILocalStateOfEnvironment.html]]}}} interface, the environment should declare a field having the type {{className{Map<LevelIdentifier,ILocalStateOfEnvironment>}}}.
[>img(50%,)[images/simulationModel/highLevel/environmentDesignOutline2.png]]
In SIMILAR, the environment is modeled as an instance of the {{className{[[IEnvironment4Engine|../api/fr/lgi2a/similar/microkernel/environment/IEnvironment4Engine.html]]}}} interface. This interface defines methods providing access to the core elements of an environment (public and private local states) and to the core behavior of the environment (natural action process).

To facilitate simulation revisions, each core element and behavior is reified as a separate method.

In the first step of the specification of the environment, only subset of this content is specified and implemented. Therefore, the unspecified methods have to throw an {{className{UnsupportedOperationException}}} at this stage.
{{clear{}}}
In this skeleton, the following elements have to be defined:
*The access\(^1\) to the ''public local states'' of the environment; +++?*[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The public local state of the environment models the data that can be perceived about the environment in a specific level. It access is therefore crucial to the construction of a simulation.

In SIMILAR, the access to a ''public local state'' of the environment is made using the following methods:
*The {{methodName{getPublicLocalState( LevelIdentifier )}}} method granting access to a public local state; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/environment/IEnvironment.html#getPublicLocalState(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier)]]}}}
*The {{methodName{getPublicLocalStates( )}}} method granting access to all the public local states; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/environment/IEnvironment4Engine.html#getPublicLocalStates()]]}}}
}}}
=== +++?*[<span class="implsmallbtn ">Implementation</span>]
{{implsection{
<<tiddler [[SMD - Environment skeleton - Public local states]]>>
}}}
=== +++?*[<span class="exsmallbtn ">Example</span>]
{{exsection{
This example illustrates the definition of an environment skeleton following the implementation guidelines provided in this page.
!Code
{{{
public class EnvironmentModel implements IEnvironment4Engine {
	[...]

	private Map<LevelIdentifier,ILocalStateOfEnvironment> publicLocalStates;

	[...]

	public EnvironmentModel( ) {
		[...]
		this.publicLocalStates = new LinkedHashMap<LevelIdentifier, ILocalStateOfEnvironment>( );
		[...]
	}

	[...]

	public ILocalStateOfEnvironment getPublicLocalState( 
		LevelIdentifier level 
	) throws NoSuchElementException {
		ILocalStateOfEnvironment result = this.publicLocalStates.get( level );
		if( result == null ){
			throw new NoSuchElementException( 
				"No public local state is defined in the environment for the level '" + 
				level + "'." 
			);
		}
		return result;
	}

	public void includeNewLevel( 
		LevelIdentifier level, 
		ILocalStateOfEnvironment publicLocalState,
		ILocalStateOfEnvironment privateLocalState 
	){
		if( level == null || publicLocalState == null || privateLocalState == null){
			throw new IllegalArgumentException( "An argument is null." );
		} else if( this.publicLocalStates.containsKey( level ) ){
			throw new IllegalArgumentException( 
				"The level '" + level + "' is already defined for this environment." 
			);
		}
		this.publicLocalStates.put( level, publicLocalState );

		[...]

	}

	[...]
}
}}}
}}} ===

*The access\(^1\) to the ''private local states'' of the environment; +++?*[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The private local state of the environment models the data that cannot be perceived about the environment in a specific level, but that participate in the computation of its natural action. It access is therefore crucial to the construction of a simulation.

In SIMILAR, the access to a ''private local state'' of the environment is made using the following method:
*The {{methodName{getPrivateLocalState( LevelIdentifier )}}} method granting access to a private local state; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/environment/IEnvironment.html#getPrivateLocalState(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier)]]}}}
}}}
=== +++?*[<span class="implsmallbtn ">Implementation</span>]
{{implsection{
<<tiddler [[SMD - Environment skeleton - Private local states]]>>
}}}
=== +++?*[<span class="exsmallbtn ">Example</span>]
{{exsection{
This example illustrates the definition of an environment skeleton following the implementation guidelines provided in this page.
!Code
{{{
public class EnvironmentModel implements IEnvironment4Engine {
	[...]

	private Map<LevelIdentifier,ILocalStateOfEnvironment> privateLocalStates;

	[...]

	public EnvironmentModel( ) {
		[...]
		this.privateLocalStates = new LinkedHashMap<LevelIdentifier, ILocalStateOfEnvironment>( );
		[...]
	}

	[...]

	public ILocalStateOfEnvironment getPrivateLocalState( 
		LevelIdentifier level 
	) throws NoSuchElementException {
		ILocalStateOfEnvironment result = this.privateLocalStates.get( level );
		if( result == null ){
			throw new NoSuchElementException( 
				"No private local state is defined in the environment for the level '" + 
				level + "'." 
			);
		}
		return result;
	}

	public void includeNewLevel( 
		LevelIdentifier level, 
		ILocalStateOfEnvironment publicLocalState,
		ILocalStateOfEnvironment privateLocalState 
	){
		if( level == null || publicLocalState == null || privateLocalState == null){
			throw new IllegalArgumentException( "An argument is null." );
		} else if( this.privateLocalStates.containsKey( level ) ){
			throw new IllegalArgumentException( 
				"The level '" + level + "' is already defined for this environment." 
			);
		}
		this.privateLocalStates.put( level, privateLocalState );

		[...]

	}

	[...]
}
}}}
}}} ===

{{bigemphasisblock{Note that the [[common libraries|./commonlibs/index.html]]<script>place.lastChild.target="_self";</script> of the micro-kernel define the {{className{[[AbstractEnvironment|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractEnvironment.html]]}}} class providing a default implementation to these methods.}}}
\(_{\underline{1:}\text{ At this stage, only the structure supporting the acces to the public and private local states is defined. The actual public and private local states are defined later.}}\)
[>img(50%,)[images/simulationModel/highLevel/environmentDesignOutline1.png]]
In SIMILAR, the environment is the sum of the following elements:
*A ''public local state'' for each level of the simulation;
*A ''private local state'' for each level of the simulation;
*A ''natural action'' process from each level of the simulation.
{{clear{}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Final specifications of the simulation}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Reaction - To regular influences]]  |  [[next step >>|SMD - Initial state]]}}}
<html><hr class="topSep"/></html>
At this stage of the simulation model design process, the general behavior of the simulation has been described. The ''final steps'' of the simualtion model design process consists in:
*Specifying the [[initialization profile(s)|SMD - Initial state]] of a simulation model;
*Writing the [[main class|SMD - Running the simulation]] performing the simulation;

{{nextButton{[[Go to the next step >>|SMD - Initial state]]}}}
The behavior of an agent is defined by three different steps (see the image):
*The ''perception phase'', where the agent decodes the data from the public local dynamic state of the perceptible levels, identifies the relevant data and stores them into a ''perceived data set'';
*The ''global state revision phase'', where the agent revises its global state using the value of its former global state and the recently perceived data;
*The ''decision phase'', where the agent uses its perceived data and its revised global state to determine what it does;
{{focusemphasisblock{
This step of the methology focuses on the creation of both the //global state// and the //global state revision phase// of each agent.
}}}
[img(100%,)[images/simulationModel/lowLevel/agentBehaviorModel_global.png]]
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Specification of the global state}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Perception]] | [[next step >>|SMD - Global state model]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Global state - Introduction]]>>
!Specifying the global state revision process of an agent class
The specification of the global state revision process of an agent relies on the implementation of two distinct elements:
*The model of the global state of the agent;
*The model determining how the global state model is updated, using its previous value and the lastly perceived data from all the levels where the agent lies;
{{nextButton{[[Go to the next step >>|SMD - Global state model]]}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the global state model}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Global state - Plan]]  |  [[next step >>|SMD - Global state revision]]}}}
<html><hr class="topSep"/></html>
The ''global state'' of an agent models the cross-level information used by the decision process of an agent. This state usually contains cross-level plans or mind states.

{{focusemphasisblock{
This step of the methology focuses on the creation of the //global state// of each agent.
}}}
!Content of the gobal state of an agent
<<tiddler [[SMD - Global state model - Content]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Global state model - Specifications]]>>
!Creating the global state of an agent in SIMILAR
<<tiddler [[SMD - Global state model - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Global state revision]]}}}
The identification of the data that should be in the ''global state'' and the data that should be in the ''private local state'' of the agent is a hard task. Indeed, their only difference lies in the number of levels where the decision uses the same information.

Even if not absolute, one of the following rules can be used to determine if information have to be put in the global state:
<<<
//If the data is used in more than one level and cannot be perceived by the other agents, then it belongs to the global memory state//
<<<
or
<<<
//If an element from the state of an agent:
*cannot be perceived by the other agents;
*must be exact for crucial decisions of an agent in more than one level;
*changes quickly (for instance between each time step);
Then that information has likely to be put in the global state of the agent.//
<<<
{{bigemphasisblock{
Note that these rules are not always appropriate: they are mere design guides. In the end, it is up to the user to determine the information to include in the global state.
}}}
The class of the global state has to:
*Be located in the ''agents.XYZ'' package, where ''XYZ'' is the category of the agent owning the state;
*Be named explicitly after the category of the agent;
*Either:
**Define {{{public}}} fields containing the data of the global state;
**Define {{{private}}} fields containing the data of the global state and read/write methods for them;
+++?*[<span class="exbigbtn ">Global state full example</span>]
{{exsection{
[>img[images/simulationModel/lowLevel/globalStateModelTree.png]]
This example illustrates an implementation of the global state in the context of a simulation studying the impact of stress on both the ''physical'' and ''social'' level of a ''test subject'', living among other ''individuals''.

In this simulation, the public local state of ''individuals'' and ''test subjects'' is the same. The main difference between these agents lies in their decision process:
*The ''individual'' agents do not use a stress factor in their decisions;
*The decisions of the ''test subject'' agents are conditioned by a stress factor;
*The actions of the ''individual'' and ''test subject'' agents can cause stress for ''test subject'' agents.
Since the stress influences both the decisions in the ''social'' and in the ''physical'' level, we decide to put the ''stress degree'' of ''test subjects'' in their global state.
!Code
The following code illustrates the implementation of this global state. The sources of this class are also available in a [[stand alone file|files/simulationModel/lowLevel/AgtTestSubjectGS.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/lowLevel/AgtTestSubjectGS.java' border='0' ></pre></object></html>
}}} ===
In SIMILAR, a global state is modeled as an instance of the {{className{[[IGlobalState|../api/fr/lgi2a/similar/microkernel/agents/IGlobalState.html]]}}} interface. This interface defines no methods: it only provides the means to identify explicitly the classes modeling the global state of the agents. The concrete content of the state have to be ''defined as fields'' and have to be ''accessed using read or write methods''.
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the global state revision model}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Global state model]]  |  [[next step >>|SMD - Decision]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Global state revision - Intro]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Global state revision - Specifications]]>>
!Writing the global state revision phase of an agent class
<<tiddler [[SMD - Global state revision - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Decision]]}}}
The implementation of this method consists in:
*Casting the global state of the agent in the appropriate class, to read or write data from it;
*Getting the perceived data of the relevant levels;
*Casting the perceived data in the appropriate class, to read data from it;
*Modifying the global state according to the information being read, in accordance with the revision model;
During the redaction of the global state revision process, the information required by the revision can become clearer. Therefore, this step will likely lead to the revision of:
*The content of the [[global state|SMD - Global state model]] being revised;
*The [[perceived data|SMD - Perception - Perceived data]] necessary to perform the revision;
*The [[perception process|SMD - Perception]] as a side effect of the revision of the perceived data;
+++?*[<span class="exbigbtn ">Global state revision process full example</span>]
{{exsection{
[>img[images/simulationModel/lowLevel/globalStateRevisionTree.png]]
This example is a continuation of the example started in the documentation of the [[global state model|SMD - Global state model]].

We illustrate the implementation of the global state revision process of a ''test subject'' agent, assuming that the stress degree of the agent:
*Denpends on the number of individuals (the test subject included) in the ''physical'' level;
*Depends on the number of social interactions between the ''test subject'' and the ''individuals'';
Therefore, the data perceived from the ''physical'' level have to contain the number of individuals in that level, and the data perceived from the ''social'' level have to contain the number of interactions involving the agent.

We assume that the stress of the agent is computed with the following formulae:
*\(stressFromPhysical = \frac{min(\mathcal{N}_a, T)}{T}\), where \(\mathcal{N}_a\) is the number of individuals  in the ''physical'' level and \(T\) a threshold;
*\(stressFromSocial = 1 - e^{-\frac{(\mathcal{N}_i - O)^2}{2}}\) where \(\mathcal{N}_i\) is the number of social actions currently involving the agent and \(O\) the optimal number of interactions the agent can undergo in the social level;
*\(stress = \frac{(1+stressFromPhysical).(1+stressFromSocial) - 1}{3}\)
!Code
If we consider that:
*The ''test subject'' agent is implemented in the {{className{AgtTestSubject}}} class;
*The perceived data of the ''test subject'' agent from the ''physical'' level is implemented in the {{className{AgtTestSubjectPDFPhysicalLevel}}} class and defines a {{methodName{getIndividualNum()}}} method;
*The perceived data of the ''test subject'' agent from the ''social'' level is implemented in the {{className{AgtTestSubjectPDFSocialLevel}}} class and defines a {{methodName{getInteractionNum()}}} method;
*The global state {{className{[[AgtTestSubjectGS2|files/simulationModel/lowLevel/AgtTestSubjectGS2.java]]}}} of the agent includes two new methods:
**{{methodName{getIndividualNumberStressThreshold()}}} getting the threshold of individuals number in the 'physical' level over which the agent becomes fully stressed.
**{{methodName{getPreferredNumberOfInteractions()}}} getting the optimal number of interactions the agent can undergo in the social level.
Then the implementation of the global state revision process of the ''test subject'' agent corresponds to the following code. The sources of this class are also available in a [[stand alone file|files/simulationModel/lowLevel/AgtTestSubject.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/lowLevel/AgtTestSubject.java' border='0' ></pre></object></html>
}}} ===
The value of the global state of an agent is revised every time the agent perceives things from the perspective of a level. This process relies on a ''global state revision'' model to determine how this revision is made.

In SIMILAR, the global state revision model can be seen as an ''application'' taking into parameters the ''most recent perceived data'' from each level where the agent lies and the former value of the ''global state'', and returning the ''revised value of the global state''.

{{focusemphasisblock{
This step of the methology focuses on the specification of the global state revision phase of each agent.
}}}
[>img(40%,)[images/simulationModel/lowLevel/agentDesignOutline5.png]]
In the micro-kernel of SIMILAR, the global state revision process is modeled by the following method of the {{className{[[IAgent4Engine|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html]]}}} interface:
{{{
public void reviseGlobalState(
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound,
	Map<LevelIdentifier, IPerceivedData> perceivedData, 
	IGlobalState globalState 
);
}}}
This method defines the following parameters:
*{{argumentName{timeLowerBound}}} identifies the ''lower bound'' of the ''transitory period'' during which the global state revision takes place;
*{{argumentName{timeUpperBound}}} identifies the ''upper bound'' of the ''transitory period'' during which the global state revision takes place;
*{{argumentName{perceivedData}}} defines the ''most recently perceived data'' from the perspective of all the levels where the agent lies;
*{{argumentName{globalState}}} defines the value of the ''global state'' of the agent at the time {{argumentName{timeLowerBound}}};
This method directly modifies the value of {{argumentName{globalState}}}. As a side effect of this method call, the global state \(\mu_{a}(t)\) contained in the argument {{argumentName{globalState}}} becomes the revised global state \(\mu_{a}(]t,t+d_t[)\) of the agent.
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{High-level specifications of the simulation}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Tools preparation - Parameters]]  |  [[next step >>|SMD - Levels identification]]}}}
<html><hr class="topSep"/></html>
The following step in the design of a simulation model is the ''description of the simulation at a coarse grain''. During this step, no attention is paid to the inner mechanisms of the levels, the agents and the environment. Instead, the design is focused on the general description of the simulation: the identification of the levels, the agents, the environment, their public local states and the influences that can be produced.

This following step create the content of the simulation model at a coarse grain:
*[[Identification of the levels|SMD - Levels identification]] of the simulation
*[[Identification of the agents|SMD - Agents identification]] of the simulation
*Creation of the [[skeleton of the levels|SMD - Level skeleton]]
*Creation of the [[skeleton of the environment|SMD - Environment skeleton]]
*Creation of the [[skeleton of the agents|SMD - Agents skeleton]]
*Definition of the [[time model|SMD - Time model]] of the levels
*Creation of the [[public local states|SMD - Public local states]] of the environment and of the agents
*Creation of the [[skeleton of the private local states|SMD - Private local states]] of the environment and of the agents
*Creation of the [[skeleton of the influences|SMD - Influences skeleton]]
{{nextButton{[[Go to the next step >>|SMD - Levels identification]]}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the skeleton of the influences}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Private local states]]  |  [[next step >>|SMD - Low level specifications]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Influences skeleton - Introduction]]>>
!Structure of an influence in SIMILAR
<<tiddler [[SMD - Influences skeleton - Structure]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Influences skeleton - Specification]]>>
!Creating an influence skeleton with SIMILAR
<<tiddler [[SMD - Influences skeleton - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Low level specifications]]}}}
The constructor of an influence has to comply with the following requirements:
*The ''category'' of the influence has to be set using the static value defined in the class;
*The ''identifier of the level'' at which the influence is aimed has to be set;
*The ''parameters'' of the influence have to be initialized using the arguments of the constructor;
The generated class has to:
*Be located in the ''influences.toXYZ'' package of the hierarchy, where ''XYZ'' is the identifier of the level at which the influence is aimed. If the influence can be aimed at more than one level, then it has to be located in the ''influences'' package of the hierarchy.
*Be named explicitly after the category of the influence;
*Define a {{{public static final}}} field identifying the ''category'' of the influence.
+++?*[<span class="exbigbtn ">Influence skeleton full example</span>]
{{exsection{
[>img[images/simulationModel/highLevel/influenceSkeletonTree.png]]
This example illustrates the creation of the skeleton of an influence from the ''grow old'' category. This influence is aimed at the ''savanah'' level of a ''wildlife'' simulation. This influence is located in the {{packageName{influences.tosavannah}}} package of the source tree hierarchy (see the image).
{{clearright{}}}
The sources of this class are also available in a [[stand alone file|./files/simulationModel/highLevel/GrowOldInfluence.java]]:
<html><pre><object width='100%' height="400" type='text/plain' data='files/simulationModel/highLevel/GrowOldInfluence.java' border='0' ></pre></object></html>
}}} ===
The last step of the high level specifications of a simulation consist in the identification of the ''influences'' that are sent by the agents and the environment to the different levels of the simulation. During this phase, modelers have to determine:
#''Which actions can be performed by the agents?'' Answering to this question usually consist in wondering what they can do, independently from how and under which conditions they decide to do these actions; +++?*[<span class="exsmallbtn">Example</span>]
{{exsection{
In the context of a road traffic simulation, the drivers of the vehicles can use their break, their accelerator or their steering wheel. Therefore, there might be three influences:
*An ''Accelerate'' influence;
*A ''Break'' influence;
*A ''Turn steering wheel'' influence.
Since acceleration and breaking are similar enough, two influences are enough:
*A ''Modify acceleration'' influence;
*A ''Turn steering wheel'' influence.
}}} ===

#''Which actions can be performed by the environment?'' Answering to this question consists in wondring:
**What can have an effect on an agent, independently from their behavior? +++?*[<span class="exsmallbtn">Example</span>]
{{exsection{
In the context of an ecosystem simulation, agents age independently from their behavior. Therefore, a ''Grow old'' influence can be sent by the environment to trigger the aging phenomenon of the agents.
}}} ===

**What can have an effect on the environment, independently from the behavior of the agents? +++?*[<span class="exsmallbtn">Example</span>]
{{exsection{
In the context of an ecosystem simulation, the behavior of the animals can be influenced by night/day cycles. Therefore, a ''Day/Night evolution'' influence can be sent by the environment to tell that the twilight or the dust comes.
}}} ===

Answering these questions don't require operational knowledge about the agents or the environment. Their answer is obtained by simplying wondering what happens in the simulation. The operational considerations come in the further steps of the methodology, where the model of the influences will be completed: at this stage, influences are mere ''skeletons''.

{{focusemphasisblock{
This step focuses on the identification and creation of the skeleton of the influences of the simulation.
}}}
Note that the identification of all the influences at this stage is difficult, especially in big models. Consequently, new influences are added during the whole simulation design process. Despite this, we highly recommend to identify as much elements as possible at this stage.
[>img(45%,)[images/simulationModel/highLevel/influenceOutline2.png]]
In SIMILAR, the influences are modeled as instances of the {{className{[[IInfluence|../api/fr/lgi2a/similar/microkernel/influences/IInfluence.html]]}}} interface. This interface is the parent to all the interfaces of a simulation. The definition of custom +++^34em^*@[regular influences]Influences defined only in the context of a simulation. By definition, these influences are not generic like the ''system influences'' that can be used in any simulation.=== rely on a more specific class named {{className{[[RegularInfluence|../api/fr/lgi2a/similar/microkernel/influences/RegularInfluence.html]]}}}.

Because the influences are often specific to a level, we do not define an influence category list like we did for agent categories and level identifiers. Instead, we consider that each influence class embeds its category as a static value.
@@clear:right;display:block;margin:0;padding:0;@@
The {{className{RegularInfluence}}} class already defines the access to the ''category'', to the ''identifier of the target level'' and to the ''transitory period'' of the influence. Their value is set using the following constructor of that class:
{{{
public RegularInfluence( 
	String category, 
	LevelIdentifier targetLevel,
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound
);
}}}
[>img(45%,)[images/simulationModel/highLevel/influenceOutline.png]]
In SIMILAR, an influence is the sum of the following elements:
*The ''category'' of the influence^^//''1''//^^;
*The ''identifier of the level'' they are aimed at, //i.e.// the level whose reaction will take into consideration the influence;
*The ''transitory period'' when the influence was created;
*The ''parameters'' identifying the metadata required to manage the reaction to the influence; +++?*[<span class="exsmallbtn">Example</span>]
{{exsection{
For instance:
*The ''eat prey'' influence of an ecosystem simulation requires the identification of the public local state of the predator and the one of the prey.
*The ''Modify acceleration'' influence a road traffic simulation requires the identification of the public local state of the vehicle accelerating and the amount of the acceleration.
*The ''Update ambient temperature'' influence of an "Efficiency energy use" simulation requires the identification of the new ambient temperature of the environment.
}}} ===

{{clearright{}}}
~~//''__1:__ This notion is similar to the notion of agent category''//~~
@@clear:right;display:block;margin:0;padding:0;@@
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creating the initial state of a simulation}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Final steps]]  |  [[next step >>|SMD - Running the simulation]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Initial state - Intro]]>>
!Structure of an initialization profile of the simulation
<<tiddler [[SMD - Initial state - Structure]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Initial state - Specifications]]>>
!Creating an initialization profile for a simulation
<<tiddler [[SMD - Initial state - Creation]]>>

{{nextButton{[[Go to the next step >>|SMD - Running the simulation]]}}}
The constructor of the simulation model initialization profile has to comply with the following requirements:
*It has to take the simulation parameters class as an argument;
*It has to set the value of the initial time stamp of the simulation;
The generated class has to:
*Be located in the ''initializations'' package of the tree hierarchy;
*Generate at least one level.
The implementation of the generic methods of the class (see the previous section) has either to be done manually (micro-kernel only approach) or with the {{className{[[AbstractSimulationModel|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractSimulationModel.html]]}}} class (micro-kernel with common libs).

+++?[<span class="exbigbtn">Simulation model initialization profile full example</span>]
{{exsection{
We consider a wildlife simulation with this [[list of levels|files/simulationModel/highLevel/WildlifeLevelList.java]] and this [[list of agents|files/simulationModel/highLevel/WildlifeAgentCategoriesList.java]]. In this example, we wish to define a wildlife simulation with lion and gazelle agents only. Therefore, this initialization profile:
*creates only a "Savannah" level;
*places only an initial number of agents of both classes in the simulation, at random locations;
*stops when a final time is reached.
!Code
We assume that:
*The "Savannah" level is modeled by the {{className{SavannahLevel}}} class, which constructor has the following arguments:
*#{{argumentName{initialTime}}} modeling the initial time stamp of the simulation;
*#{{argumentName{eatThreshold}}} modeling a threshold distance for the eat behavior of predators (see the example of [[this step|SMD - Reaction - To regular influences]] of the methodology);
*The environment is implemented as a {{className{WildlifeEnvironment}}} extending the {{className{AbstractEnvironment}}} class from the common libs. {{className{WildlifeEnvironment}}} defines a constructor with no arguments, and has the following as public and private local states:
**{{className{EnvPLSInSavannah}}} modeling the public local state of the environment in the "savannah" level. Its constructor is assumed to have the following arguments:
***{{argumentName{initialHumidity}}} modeling the initial humidity of the environment;
***{{argumentName{gridWidth}}} modeling the width of the topology of the environment;
***{{argumentName{gridHeight}}} modeling the height of the topology of the environment;
**{{className{EnvHLSInSavannah}}} modeling a private local state of the environment in the "savannah" level. Its constructor is assumed to have no arguments;
*Agents from the ''gazelle'' category can be created using the {{className{AgtGazelleFactory}}} agent factory class. This class defines a static agent generation method named {{methodName{generate(...)}}} having the initial location of the agent as an argument. This location is modeled as an instance of the {{className{Point2D}}} class;
*Agents from the ''lion'' category can be created using the {{className{AgtLionFactory}}} agent factory class. This class defines a static agent generation method named {{methodName{generate(...)}}} having the initial location of the agent as an argument. This location is modeled as an instance of the {{className{Point2D}}} class;
*A [[random number generator|SMD - Tools preparation - Random]] class {{className{RandomValueFactory}}} defines in its strategy a method named {{methodName{randomLocationIn(doube,double)}}} getting a random location within the specified bounds having a width and a height provided as arguments;
*The parameters of the simulation are declared as a field named {{fieldName{parameters}}}, containing the following public fields:
**{{fieldName{initialTime}}} modeling the initial time of the simulation;
**{{fieldName{finalTime}}} modeling the final time of the simulation;
**{{fieldName{envWidth}}} modeling the width of the environment in all the levels;
**{{fieldName{envHeight}}} modeling the height of the environment in all the levels;
**{{fieldName{initialHumidity}}} modeling the initial humidity level in the "Savannah" level;
**{{fieldName{initialNumOfGazelles}}} modeling the initial number of gazelle agents used in the simulation;
**{{fieldName{initialNumOfLions}}} modeling the initial number of lion agents used in the simulation;
**{{fieldName{eatBehaviorThresholdDistance}}} modeling the maximal distance that can separate a predator from its prey for a "eat" behavior.
Based on these information, the corresponding ''simulation model initialization profile'' is implemented with the following code. The sources of this class are also available as a [[stand alone|files/simulationModel/finalStep/WildlifeSimulationModel.java]] file.
<html><pre><object width='100%' height='350px' type='text/plain' data='files/simulationModel/finalStep/WildlifeSimulationModel.java' border='0' ></pre></object></html>
}}} ===
Just like for the initialization of agents, different factors have an impact on the initial state of a simulation:
*The simulation parameters;
*The way the parameters are used to generate the initial state of the simulation;
Consequently, different initialization profiles can be define for the same simulation model, depending on the goals of the simulation.

{{focusemphasisblock{
This step of the simulation focuses on the specifications of the various initialization profiles of a simulation model.
}}}
In SIMILAR, the initialization profile of a simulation are modeled as instances of the {{className{[[ISimulationModel|../api/fr/lgi2a/similar/microkernel/ISimulationModel.html]]}}} interface. This interface defines methods determining the initial and final time stamps of the simulation, as well as the nature of the levels, agents, environments and influences lying in the initial dynamic state of the simulation.

This interface defines the following elements:
*The ''initial time'' of the simulation; <<tiddler [[SMD - Initial state - Specifications - Initial time]]>>
*The ''ending criterion'' of the simulation; <<tiddler [[SMD - Initial state - Specifications - Ending criterion]]>>
*The ''level generation'' profile of the simulation; <<tiddler [[SMD - Initial state - Specifications - Level generation]]>>
*The ''environment generation'' profile of the simulation; <<tiddler [[SMD - Initial state - Specifications - Environment generation]]>>
*The ''agent generation'' profile of the simulation; <<tiddler [[SMD - Initial state - Specifications - Agents generation]]>>
{{bigemphasisblock{
Note that the [[common libs|commonLibs/index.html]]<script>place.lastChild.target="_self";</script> of the micro-kernel defines the {{className{[[AbstractSimulationModel|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractSimulationModel.html]]}}} class providing a default implementation of the generic features of this interface (initial time).
}}}
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The ''generation profile of the agents'' is a method creating the instances of the {{className{IAgent4Engine}}} interface initially lying in the simulation. This method is named {{methodName{[[generateAgents(...)|../api/fr/lgi2a/similar/microkernel/ISimulationModel.html#generateAgents(fr.univ_artois.lgi2a.similar.microkernel.SimulationTimeStamp, java.util.Map)]]}}} and has the following signature:
{{{
public AgentInitializationData generateAgents(
	SimulationTimeStamp initialTime, 
	Map<LevelIdentifier, ILevel> levels
);
}}}
This method defines the following arguments:
*{{argumentName{initialTime}}} corresponding to the initial time of the simulation;
*{{argumentName{levels}}} modeling all the levels of the simulation that were created by the ''generation profile of the levels''. These levels are accessed by their ''level identifier'' defined as the key of this map;
This method returns an instance of the {{className{[[AgentInitializationData|../api/fr/lgi2a/similar/microkernel/ISimulationModel.AgentInitializationData.html]]}}} class containing the initialized agent instances initially lying in the simulation.
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The value returned this method has to be created using the following constructor:
{{{
public AgentInitializationData( );
}}}
This constructor defines no arguments. The agents initially lying in the simulation have to be added to the agent list returned by its {{methodName{[[getAgents( )|../api/fr/lgi2a/similar/microkernel/ISimulationModel.AgentInitializationData.html#getAgents()]]}}} method.

The creation of an initialized agent instance is made using the agent factories that were specified in a [[previous step|SMD - Agent creation]] of the methodology.

Note that for a cleaner definition of the simulation, the actual value of the parameters used to create the agents have to come from the parameters of the simulation. Therefore, a simulation model has to define a field named {{fieldName{parameters}}} containing the simulation parameters being used by the initialization profile.
}}} === +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
We consider a wildlife simulation with this [[list of levels|files/simulationModel/highLevel/WildlifeLevelList.java]] and this [[list of agents|files/simulationModel/highLevel/WildlifeAgentCategoriesList.java]]. In this example, we wish to define a wildlife simulation with ''lion'' and ''gazelle'' agents only. This initialization profile places an initial number of agents of both classes in the simulation, at random locations.
!Code
We assume that:
*Agents from the ''gazelle'' category can be created using the {{className{AgtGazelleFactory}}} agent factory class. This class defines a static agent generation method named {{methodName{generate(...)}}} having the initial location of the agent as an argument. This location is modeled as an instance of the {{className{Point2D}}} class;
*Agents from the ''lion'' category can be created using the {{className{AgtLionFactory}}} agent factory class. This class defines a static agent generation method named {{methodName{generate(...)}}} having the initial location of the agent as an argument. This location is modeled as an instance of the {{className{Point2D}}} class;
*A [[random number generator|SMD - Tools preparation - Random]] class {{className{RandomValueFactory}}} defines in its strategy a method named {{methodName{randomLocationIn(doube,double)}}} getting a random location within the specified bounds having a width and a height provided as arguments;
*The parameters of the simulation are declared as a field named {{fieldName{parameters}}}, containing the following public fields:
**{{fieldName{envWidth}}} modeling the width of the environment in all the levels;
**{{fieldName{envHeight}}} modeling the height of the environment in all the levels;
**{{fieldName{initialNumOfGazelles}}} modeling the initial number of gazelle agents used in the simulation;
**{{fieldName{initialNumOfLions}}} modeling the initial number of lion agents used in the simulation;
Then the generation of the initial agents of the simulation is made with the following code:
{{{
public AgentInitializationData generateAgents(
	SimulationTimeStamp initialTime, 
	Map<LevelIdentifier, ILevel> levels
) {
	AgentInitializationData result = new AgentInitializationData( );
	// Create the initial gazelle agents.
	for( int gazelleId = 0; gazelleId < this.parameters.initialNumOfGazelles; gazelleId++ ){
		IAgent4Engine gazelle = AgtGazelleFactory.generate(
			RandomValueFactory.getStrategy().randomLocationIn(
				this.parameters.envWidth, 
				this.parameters.envHeight
			)
		);
		result.getAgents().add( gazelle );
	}
	// Create the initial lion agents.
	for( int lionId = 0; lionId < this.parameters.initialNumOfLions; lionId++ ){
		IAgent4Engine lion = AgtLionFactory.generate(
			RandomValueFactory.getStrategy().randomLocationIn(
				this.parameters.envWidth, 
				this.parameters.envHeight
			)
		);
		result.getAgents().add( lion );
	}
	return result;
}
}}}
}}} ===
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The ending criterion of a simulation model determines when the simulation has to stop. Instead of relying on a static value, this criterion is defined as an abstract method providing more lattitude to its definition. Ending critera can be defined as:
*Reaching a specific time stamp (//i.e.// the final time stamp);
*Reaching a specific agent density in a level;
*Reaching a situation where no influences remain in the dynamic state of a level;
*//etc.//
The ending criterion is defined as the {{methodName{[[isFinalTimeOrAfter(...)|../api/fr/lgi2a/similar/microkernel/ISimulationModel.html#isFinalTimeOrAfter(fr.univ_artois.lgi2a.similar.microkernel.SimulationTimeStamp, fr.univ_artois.lgi2a.similar.microkernel.ISimulationEngine)]]}}} method, which signature is:
{{{
public boolean isFinalTimeOrAfter( 
	SimulationTimeStamp currentTime, 
	ISimulationEngine engine 
);
}}}
This method defines two arguments:
*{{argumentName{currentTime}}} modeling the current half-consistent state of the simulation. This method checks if this current time will be the final time of the simulation or not;
*{{argumentName{engine}}} modeling a reference to the simulation engine. This object contains all the information about the simulation being performed, including:
**The agents currently lying in each level;
**The environment of the simulation;
**The dynamic state of each level;
For more information about the {{argumentName{engine}}} argument, see the documentation of the [[observation probes|Observation probes]].
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The only requirements of this method are that:
*The method has to be deterministic: calling this method twice with the same parameters (independently from the call context) has to produce the same output;
*The method must have no side effects on the parameters.

The ending criterion can be implemented as any condition based on the current value of:
*The time of the current half-consistent state of the simulation;
*The state of the agents lying in the simulation;
*The state of the environment;
*The dynamic state of each level.
}}} === +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
This example illustrates the implementation of an ending criterion checking if a final time having the identifier {{{500}}} has been reached.

This example assumes that the simulation model defines a field named {{fieldName{finalTime}}} corresponding to that value.
{{{
public boolean isFinalTimeOrAfter( 
	SimulationTimeStamp currentTime, 
	ISimulationEngine engine 
) {
	return this.currentTime.compareTo( finalTime ) >= 0;
}
}}}
}}} ===
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The ''generation profile of the environment'' is a method creating the instance of the {{className{IEnvironment4Engine}}} interface modling the environment of the simulation. This method is named {{methodName{[[generateEnvironment(...)|../api/fr/lgi2a/similar/microkernel/ISimulationModel.html#generateEnvironment(fr.univ_artois.lgi2a.similar.microkernel.SimulationTimeStamp, java.util.Map)]]}}} and has the following signature:
{{{
public EnvironmentInitializationData generateEnvironment( 
	SimulationTimeStamp initialTime, 
	Map<LevelIdentifier, ILevel> levels 
);
}}}
This method defines the following argument:
*{{argumentName{initialTime}}} corresponding to the initial time of the simulation;
*{{argumentName{levels}}} modeling all the levels of the simulation that were created by the ''generation profile of the levels''. These levels are accessed by their ''level identifier'' defined as the key of this map;
This method returns an instance of the {{className{[[EnvironmentInitializationData|../api/fr/lgi2a/similar/microkernel/ISimulationModel.EnvironmentInitializationData.html]]}}} class containing the initialized environment of the simulation.
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The value returned this method has to be created using the following constructor:
{{{
public EnvironmentInitializationData(
	IEnvironment4Engine environment
);
}}}
This constructor takes as an argument the initialized environment of the simulation.

The generation of the initialized environment consists in:
*Creating the instance of the environment (an instance of the {{className{IEnvironment4Engine}}} interface);
*Creating the public and private local states of the environment for all the levels that were defined by the ''generation profile of the levels'';
*Adding these states to the environment (for instance with the {{methodName{includeNewLevel(...)}}} method of the {{className{AbstractEnvironment}}} class);
Note that for a cleaner definition of the simulation, the actual value of the parameters used to initialize the public and private local states have to come from the parameters of the simulation. Therefore, a simulation model has to define a field named {{fieldName{parameters}}} containing the simulation parameters being used by the initialization profile.
}}} === +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
For instance, in the context of a wildlife simulation with this [[list of levels|files/simulationModel/highLevel/WildlifeLevelList.java]], if we assume that the environment defines the following local states:
*{{className{EnvPLSInSavannah}}} modeling the public local state of the environment in the "savannah" level. Its constructor is assumed to have the following arguments:
**{{argumentName{initialHumidity}}} modeling the initial humidity of the environment;
**{{argumentName{gridWidth}}} modeling the width of the topology of the environment;
**{{argumentName{gridHeight}}} modeling the height of the topology of the environment;
*{{className{EnvHLSInSavannah}}} modeling a private local state of the environment in the "savannah" level. Its constructor is assumed to have no arguments;
*{{className{EnvPLSInSky}}} modeling the public local state of the environment in the "sky" level. Its constructor is assumed to have the following arguments:
**{{argumentName{gridWidth}}} modeling the width of the topology of the environment;
**{{argumentName{gridHeight}}} modeling the height of the topology of the environment;
*{{className{EnvHLSInSky}}} modeling a private local state of the environment in the "sky" level. Its constructor is assumed to have no arguments;
*{{className{EnvPLSInUnderground}}} modeling the public local state of the environment in the "underground" level. Its constructor is assumed to have the following arguments:
**{{argumentName{gridWidth}}} modeling the width of the topology of the environment;
**{{argumentName{gridHeight}}} modeling the height of the topology of the environment;
*{{className{EnvHLSInUnderground}}} modeling a private local state of the environment in the "underground" level. Its constructor is assumed to have no arguments;
We assume that the environment is implemented as the {{className{WildlifeEnvironment}}} class extending the {{className{AbstractEnvironment}}} class and defining a constructor having no arguments. We also assume that the simulation model defines a field {{fieldName{parameters}}} modeling a parameters class containing the following parameters:
*{{fieldName{envWidth}}} modeling the width of the environment in all the levels;
*{{fieldName{envHeight}}} modeling the height of the environment in all the levels;
*{{fieldName{initialHumidity}}} modeling the initial humidity level in the "Savannah" level;
Then the generation of the environment is made with the following code:
{{{
public EnvironmentInitializationData generateEnvironment( 
	SimulationTimeStamp initialTime, 
	Map<LevelIdentifier, ILevel> levels 
){
	WildlifeEnvironment environment = new WildlifeEnvironment( );
	// First initialize the environment by setting its public and private
	// local states in the various levels of the simulation.
	// 
	// Specify the "Savannah" level.
	ILocalStateOfEnvironment envPls = new EnvPLSInSavannah(
		this.parameters.initialHumidity,
		this.parameters.envWidth,
		this.parameters.envHeight
	);
	environment.includeNewLevel(
		WildlifeLevelList.SAVANNAH,
		envPls ,
		new EnvHLSInSavannah( )
	);
	// Specify the "Sky" level.
	envPls = new EnvPLSInSky(
		this.parameters.envWidth,
		this.parameters.envHeight
	);
	environment.includeNewLevel(
		WildlifeLevelList.SKY,
		envPls ,
		new EnvHLSInSky( )
	);
	// Specify the "Underground" level.
	envPls = new EnvPLSInUnderground(
		this.parameters.envWidth,
		this.parameters.envHeight
	);
	environment.includeNewLevel(
		WildlifeLevelList.UNDERGROUND,
		envPls ,
		new EnvHLSInUnderground( )
	);
	// Then return the environment initialization data.
	return new EnvironmentInitializationData( environment  );
}
}}}
}}} ===
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The access to the initial time of the simulation is defined by the {{methodName{[[getInitialTime()|../api/fr/lgi2a/similar/microkernel/ISimulationModel.html#getInitialTime()]]}}} method.
This method has the following signature:
{{{
public SimulationTimeStamp getInitialTime();
}}}
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Adding a field to the class having the type {{className{SimulationTimeStamp}}};
*Setting its initial value in the constructor of the class;
*Granting access to that field in the appropriate methods (i.e. {{methodName{getInitialTime( )}}}).
}}} ===
+++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The ''generation profile of the levels'' is a method creating the instances of the {{className{ILevel}}} interface modeling the various levels of the simulation. This method is named {{methodName{[[generateLevels(...)|../api/fr/lgi2a/similar/microkernel/ISimulationModel.html#generateLevels(fr.univ_artois.lgi2a.similar.microkernel.SimulationTimeStamp)]]}}} and has the following signature:
{{{
public List<ILevel> generateLevels( 
	SimulationTimeStamp initialTime 
);
}}}
This method defines the following argument:
*{{argumentName{initialTime}}} corresponding to the initial time of the simulation;
This method ''returns the list of levels'' of the simulation.
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
This list return by this method has to contain the levels that will be used in the simulation defined by this profile. These levels have to initialize:
*Their identifier;
*Their out neighborhood in the perception relation graph;
*Their out neighborhood in the influence relation graph;
*The value of the parameters of their reaction process (see [[this step|SMD - Reaction - To regular influences]] of the methodology);
The initialization of the public local states of the environment and the creation and addition of agents is made in other methods.

Note that for a cleaner definition of the simulation, the actual value of the parameters used to initialize the reaction processes of the levels have to come from the parameters of the simulation. Therefore, a simulation model has to define a field named {{fieldName{parameters}}} containing the simulation parameters being used by the initialization profile.
}}} === +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
For instance, in the context of a wildlife simulation defining the following level classes:
*{{className{SavannahLevel}}}, which constructor has the following arguments:
*#the initial time stamp of the simulation;
*#a threshold distance for the eat behavior of predators (see the example of [[this step|SMD - Reaction - To regular influences]] of the methodology);
*{{className{SkyLevel}}}, which constructor has the following arguments:
*#the initial time stamp of the simulation;
*{{className{UndergroundLevel}}}, which constructor has the following arguments:
*#the initial time stamp of the simulation;
*All these constructors are assumed to create the influence and perception relation graphs of the levels;
And if the simulation model defines a field {{fieldName{parameters}}} modeling a parameters class containing the following parameters:
*{{fieldName{eatBehaviorThresholdDistance}}} modeling the maximal distance that can separate a predator from its prey for a "eat" behavior.
Then the generation of the levels is made with the following code:
{{{
public List<ILevel> generateLevels( 
	SimulationTimeStamp initialTime 
){
	List<ILevel> levels = new LinkedList<ILevel>( );
	SavannahLevel savannah = new SavannahLevel( 
		initialTime,
		this.parameters.eatBehaviorThresholdDistance
	);
	levels.add( savannah );
	SkyLevel sky = new SkyLevel( 
		initialTime
	);
	levels.add( sky );
	UndergroundLevel underground = new UndergroundLevel( 
		initialTime
	);
	levels.add( underground );
	return levels;
}
}}}
}}} ===
[>img(55%,)[images/simulationModel/finalStep/simulationModelOutline1.png]]
The initialization profile defined for a simulation model is characterized by:
*Some ''parameters'' coming from the [[parameters class|SMD - Tools preparation - Parameters]] of the simulation; +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
For instance the parameters can define the initial number of a specific type of agents in the simulation.
}}} ===

*The ''initial and final times'' of the simulation;
*The ''levels'' that are lying in the simulation^^//''1''//^^;
*The ''initial specification of the environment'' of the simulation;
*The ''agents initially lying'' in the simulation.
{{clearright{}}}
~~//''__1:__ Note that the same simulation model can be used to run simulations having different complexities, owning to the initialization profiles. Indeed, an initialization profile has not to necessarily use all the levels that were defined in a simulation.''//~~ +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
In the context of a simulation modeling the endogenous and exogenous dynamics of a cell, two levels can be defined: the ''endogenous'' level and the ''exogenous'' level of the simulation. With such a model, different types of simulations can be performed:
*A simulation studying the interaction between the ''exogenous'' and ''endogenous'' middles of the simulation;
*A simulation studying the behavior of the ''endogenous'' middle alone;
*A simulation studying the behavior of the ''exogenous'' middle alone;
Depending on the type of the simulation, a different subset of levels will be used in the simulation.
}}} ===

/%
*When the ''initial and final times'' of the simulation;
*The ''levels'' that are lying in the simulation^^//''1''//^^:
**The specification of the reaction being used in each level (if more than one was specified for a level);
**The parameters being used in such reactions;
*The ''initial specification of the environment'' of the simulation:
**Its initial public and private local states for each level of the simulation;
**The specification of its natural action for each level (if more than one was specified for a level);
*The ''agents initially lying'' in the simulation:
**The number and types of agents lying in the simulation;
**The initialization profile used for each of these agents;
%/
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the skeleton of the levels}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Agents identification]]  |  [[next step >>|SMD - Environment skeleton]]}}}
<html><hr class="topSep"/></html>
After the identification of the levels, the objects modeling them can be created. Note that ''at this stage, these objects are'' mere +++^60em^*@[<strong>skeletons</strong>]<html><h1>Why skeletons?</h1></html>
The simulation design process is rarely straightforward. Indeed, having an overview on all the implementation details of the model is next to impossible. Instead, models are built incrementally, by adding bits of information each time.

The design guidelines of SIMILAR take into consideration this point by creating first the skeleton of all the entities involved in the simulation. After these high-level specifications, the operational code of these classes is included incrementally during the low-level specifications.
===, since the level-related specifications (time model and reaction) are not specified yet.

{{focusemphasisblock{
This step focuses on the creation of a skeleton class for each level that was identified during the [[levels identification|SMD - Levels identification]] step.
}}}
<<tiddler [[SMD - Level skeleton - Structure]]>>
<<tiddler [[SMD - Level skeleton - Implementation]]>>
<<tiddler [[SMD - Level skeleton - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Environment skeleton]]}}}
!Creating a level  skeleton in SIMILAR
The constructor of a level has to comply with the following requirements:
*The most recent consistent state has to be partially initialized:
**The +++^34em^*@[<strong>time stamp</strong> of that state]
More precisely the time stamp of the last consistent state of the level.
=== has to be equal to the initial time stamp of the simulation;
**The remaining initialization of the last consistent state is [[completed later|SMD - Initial state]];
*The most recent transitory state has to be initialized;
*The ''perception relation graph'' of the level has to be initialized and contain at least its own identifier;
*The ''influence relation graph'' of the level has to be initialized and contain at least its own identifier;
The generated class has to:
*Be located in the ''levels.XYZ'' package of the package tree hierarchy, where ''XYZ'' is the identifier of the level;
*Be named explicitly after the level.
The implementation of the methods of the skeleton (see the previous section) has either to be done manually (micro-kernel only approach) or with the {{className{[[AbstractLevel|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractLevel.html]]}}} class (micro-kernel with common libs).

+++?[<a class="exbigbtn">Level skeleton full example</a>]{{exsection {
[>img[images/simulationModel/highLevel/levelSkeletonTree.png]]
This example is a continuation of the previous step where four different levels were identified, and instanciated into the {{className{MyAwesomeLevelList}}} class:
*A "city" level
*A "slums" level
*A "country" level
*A "seashore" level
This step illustrates the creation of a level named "city" such that:
*The perception graph contains the "city" and "slums" levels;
*The influence graph contains the "city", "slums" and "country" levels.
*The source of the class modeling the "City" level is located in the ''levels'' package of the source tree hierarchy (see the image). 
{{clear{}}}
This example illustrates two implementation approaches of this class:
*The micro-kernel only approach is implemented as the {{className{CityLevelSkeleton}}} class +++?[<a class="implsmallbtn">Implementation</a>]
{{implsection {
The following code illustrates the implementation of the environment using only the micro-kernel. These sources are also available in a [[stand alone file|./files/simulationModel/highLevel/CityLevelSkeleton.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/highLevel/CityLevelSkeleton.java' border='0' ></pre></object></html>
}}} ===

*The micro-kernel with common libs approach is implemented as the {{className{CityLevelSkeleton2}}} class +++?[<a class="implsmallbtn">Implementation</a>]
{{implsection {
The following code illustrates the implementation of the environment using both the micro-kernel and the common libs. These sources are also available in a [[stand alone file|./files/simulationModel/highLevel/CityLevelSkeleton2.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/highLevel/CityLevelSkeleton2.java' border='0' ></pre></object></html>
}}} ===

}}}===
!Specifications and implementation instructions
[<img(50%,)[images/simulationModel/highLevel/levelDesignOutline2.png]]
In SIMILAR, levels are modeled as instances of the {{className{[[ILevel|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html]]}}} interface. This interface defines methods providing access to the core elements of a level (identifier, influence and perception relation graphs) and to the core behavior of the levels (time model and reaction).

To facilitate simulation revisions, each core element and behavior is reified as a separate method.

In the first step of the specification of the levels, only subset of the content of each level is specified and implemented. Therefore, the unspecified methods have to throw an {{className{UnsupportedOperationException}}} at this stage.
{{clear{}}}
In this skeleton, the following methods have to be defined:
*The access to the ''identifier'' of the level; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The access to the identifier of the level is defined by the following methods:
*The {{methodName{[[getIdentifier()|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html#getIdentifier()]]}}} method.
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of these methods usually consists in:
*Adding a field to the class having the type {{className{LevelIdentifier }}};
*Setting its initial value in the constructor of the class;
*Granting access to that field in the appropriate methods (//i.e.// {{methodName{getIdentifier( )}}}).
}}} ===

*The access to the ''perception relation graph'' of the level; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
In SIMILAR, the perception relation graph is distributed among the levels. Each level embeds its out neighborhood of the perception relation graph. 

The access to the out neighborhood is defined by the following methods:
*The {{methodName{[[getPerceptibleLevels()|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html#getPerceptibleLevels()]]}}} method.
}}} ===  +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Adding a field to the class having the type {{className{Set<LevelIdentifier>}}};
*Setting its initial value in the constructor of the class;
*Granting access to that field in the appropriate methods (//i.e.// {{methodName{getPerceptibleLevels( )}}}).
}}} === +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
This example is a continuation of the previous step where four different levels were identified, and instanciated into the {{className{MyAwesomeLevelList}}} class:
*A "city" level
*A "slums" level
*A "country" level
*A "seashore" level
It illustrates the implementation of the {{methodName{getPerceptibleLevels(...)}}} method of a "city" level such that:
*The out neighborhood of the level in the perception relation graph contains the "city" and "slums" levels.
!Code
{{{
public class CityLevel implements ILevel {
	[...]
	
	private Set<LevelIdentifier> perceptibleLevels;
	
	[...]

	public CityLevel( 
		[...] 
	){
		[...]
		this.perceptibleLevels = new LinkedHashSet<LevelIdentifier>();
		// First add the identifier of this level to the graph.
		this.perceptibleLevels.add( MyAwesomeLevelList.CITY );
		// Then add to the set the identifier of the perceptible levels.
		this.perceptibleLevels.add( MyAwesomeLevelList.SLUMS );
		[...]
	}

	[...]
	
	public Set<LevelIdentifier> getPerceptibleLevels() {
		return this.perceptibleLevels;
	}
}
}}}
}}} ===

*The access to the ''influence relation graph'' of the level;  +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
In SIMILAR, the influence relation graph is distributed among the levels. Each level embeds its out neighborhood of the influence relation graph. 

The access to the out neighborhood is defined by the following methods:
*The {{methodName{[[getInfluenceableLevels()|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html#getInfluenceableLevels()]]}}} method.
}}} ===  +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Adding a field to the class having the type {{className{Set<LevelIdentifier>}}};
*Setting its initial value in the constructor of the class;
*Granting access to that field in the appropriate methods (//i.e.// {{methodName{getInfluenceableLevels( )}}}).
}}} ===  +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
This example is a continuation of the previous step where four different levels were identified, and instanciated into the {{className{MyAwesomeLevelList}}} class:
*A "city" level
*A "slums" level
*A "country" level
*A "seashore" level
It illustrates the implementation of the {{methodName{getInfluenceableLevels(...)}}} method of a "city" level such that:
*The out neighborhood of the level in the influence relation graph contains the "city", "seashore" and "country" levels.
!Code
{{{
public class CityLevel implements ILevel {
	[...]
	
	private Set<LevelIdentifier> influenceableLevels;
	
	[...]

	public CityLevel( 
		[...] 
	){
		[...]
		this.influenceableLevels = new LinkedHashSet<LevelIdentifier>();
		// First add the identifier of this level to the graph.
		this.influenceableLevels.add( MyAwesomeLevelList.SEASHORE );
		// Then add to the set the identifier of the perceptible levels.
		this.influenceableLevels.add( MyAwesomeLevelList.COUNTRY );
		[...]
	}

	[...]
	
	public Set<LevelIdentifier> getInfluenceableLevels() {
		return this.influenceableLevels;
	}
}
}}}
}}} ===

*The ''most recent consistent dynamic state'' of the level; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The most recent consistent dynamic state models the state of a level the last time it was readable (//i.e.// either the initial one, or its value right after the reaction of the level).
!Specification of the access methods
The access to the most recent consistent dynamic state of the level is done using the following method:
*An accessor reading the value of such a dynamic state ({{methodName{[[getLastConsistentState( )|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html#getLastConsistentState()]]}}} method);
*No setter is defined for this value since it is updated after each transitory state (rather than creating new instances each time).
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Adding a field to the class having the type {{className{ConsistentPublicLocalDynamicState }}};
*Setting its initial value in the constructor of the class;
*Granting access to that field in the appropriate methods (//i.e.// {{methodName{getLastConsistentState( )}}}).
!!Setting the initial value
Contrary to the other elements of the level, the dynamic state requires specific information to be fully initialized:
*A time stamp modeling the time for which this dynamic state is defined;
*The public and private local state of the environment for the level;
In the context of the constructor of a level, these values are the initial ones. At this current step of the methodology, only the initial time stamp will be defined. The definition of the initial local state of the environment is made later.
}}}  ===  +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
This example is a continuation of the previous step where four different levels were identified, and instanciated into the {{className{MyAwesomeLevelList}}} class:
*A "city" level
*A "slums" level
*A "country" level
*A "seashore" level
It illustrates the implementation of the {{methodName{getLastConsistentState(...)}}} method of a "city" level.
!Code
{{{
public class CityLevel implements ILevel {
	[...]
	
	private ConsistentPublicLocalDynamicState  mostRecentConsistentDynamicState;
	
	[...]

	public CityLevel( 
		[...] 
		SimulationTimeStamp initialTime,
		[...] 
	){
		[...]
		this.mostRecentConsistentDynamicState = new ConsistentPublicLocalDynamicState( 
			initialTime, 
			MyAwesomeLevelList.CITY 
		);
		[...]
	}

	[...]
	
public ConsistentPublicLocalDynamicState  getLastConsistentState() {
	return this.mostRecentConsistentDynamicState;
}
}
}}}
}}} ===

*The ''most recent transitory dynamic state'' of the level; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The most recent transitory dynamic state models the state of a level since the last time it was readable (//i.e.// its value between two consecutive reactions of the level).
!Specification of the access methods
The access to the most recent transitory dynamic state of the level is done using the following method:
*An accessor reading the value of such a dynamic state ({{methodName{[[getLastTransitoryState( )|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html#getLastTransitoryState()]]}}} method);
*No setter is defined for this value since it is updated after each reaction (rather than creating new instances each time).
}}} === +++?[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Adding a field to the class having the type {{className{TransitoryPublicLocalDynamicState}}};
*Setting its initial value in the constructor of the class;
*Granting access to that field in the appropriate methods (//i.e.// {{methodName{getLastTransitoryState( )}}}).
!!Setting the initial value
Contrary to the other elements of the level, the dynamic state requires specific information to be fully initialized:
*The consistent dynamic state to which it is attached (this state models the consistent state directly preceding this transitory state);
*A time stamp modeling the moment when the transitory period ends. By default, it is easier to set this value to a maximal time stamp, since the engine will in the end override this value;
The definition of the local state of the environment is unecessary in this constructor, since their value correspond to their value in the most recent consistent dynamic state.
}}}  ===  +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
This example is a continuation of the previous step where four different levels were identified, and instanciated into the {{className{MyAwesomeLevelList}}} class:
*A "city" level
*A "slums" level
*A "country" level
*A "seashore" level
It illustrates the implementation of the {{methodName{getLastTransitoryState(...)}}} method of a "city" level.
!Code
{{{
public class CityLevel implements ILevel {
	[...]
	
	private ConsistentPublicLocalDynamicState  mostRecentConsistentDynamicState;
	
	private TransitoryPublicLocalDynamicState mostRecentTransitoryDynamicState;
	
	[...]

	public CityLevel( 
		[...] 
		SimulationTimeStamp initialTime,
		[...] 
	){
		[...]
		this.mostRecentConsistentDynamicState = new ConsistentPublicLocalDynamicState( 
			initialTime, 
			MyAwesomeLevelList.CITY 
		);
		this.mostRecentTransitoryDynamicState= new TransitoryPublicLocalDynamicState( 
			this.mostRecentConsistentDynamicState
		);
		[...]
	}

	[...]
	
	public TransitoryPublicLocalDynamicState getLastTransitoryState( ) {
		return this.mostRecentTransitoryDynamicState;
	}
}
}}}
}}} ===

{{bigemphasisblock{
Note that the [[common libs|commonLibs/index.html]]<script>place.lastChild.target="_self";</script> of the micro-kernel defines the {{className{[[AbstractLevel|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractLevel.html]]}}} class providing a default implementation of these features.
}}}
!Structure of a level in SIMILAR
[>img(50%,)[images/simulationModel/highLevel/levelDesignOutline1.png]]
In SIMILAR, a level is the sum of the following elements^^''1''^^:
*An ''identifier'', defined during the previous step;
*A part of the ''perception relation graph''^^''2''^^;
*A part of the ''influence relation graph''^^''2''^^;
*The ''dynamic state'' of the level^^''3''^^;
*A ''time model'' defining when the level is consistent;
*A ''reaction to the influences'' aimed at the level:
**A reaction for the ''system influences'';
**A reaction for the ''regular influences''.
{{clear{}}}
\(_{\underline{1:}\text{ See the reference papers on SIMILAR and IRM4MLS for the full description of these elements.}}\)
\(_{\underline{2:}\text{ More precisely, the out neighborhood of the level in that graph.}}\)
\(_{\underline{3:}\text{ In SIMILAR, the model of a level stores the lastly computed consistent state. The management of the transitory states is left to the simulation engines.}}\)
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Identification of the levels}}}
{{guidelinesNavMenu{[[<< previous step|SMD - High level specifications]] | [[next step >>|SMD - Agents identification]]}}}
<html><hr class="topSep"/></html>
The first concrete step in the design of the simulation model is the identification of the levels where the simulation takes place. In this step, no precise knowledge about the levels is necessary. The only important point here is to ''identify the existence of the levels, and give them a unique name''.

Once the levels and their names is known, the user can create a class summing up these information.

{{focusemphasisblock{This step focuses on the creation of a class listing the identifier of all the levels of the simulation.}}}
!Creating the identifier of a level
In SIMILAR, the identifier of a level is modeled as an instance of the {{className{[[LevelIdentifier|../api/fr/lgi2a/similar/microkernel/LevelIdentifier.html]]}}} class. A level identifier is built using the following constructor:
{{{
public LevelIdentifier( String levelName );
}}}
Note that the {{argumentName{levelName}}} argument cannot be null. Moreover, its value has to be different for each level being modeled.

+++?[<span class="exbigbtn">Level identifier creation example</span>]
{{exsection {
This example illustrates the creation of the identifier of a level named "city":
{{{
LevelIdentifier cityLevelIdentifier = new LevelIdentifier( "city" );
}}}
}}} ===
!The level identifiers list
The identifier of a level is unique and does not change over the simulation. To avoid misspelling errors during the implementation, we highly recommend to create an enum-like structure containing the identifier of each level of the simulation. This structure is called the ''"level identifiers list"''.
!!Creating the list of level identifier
[>img[images/simulationModel/highLevel/levelsList_package.png]]
The ''"level identifiers list"'' class is designed to avoid misspelling errors in the simulation. It relies on a specific structure supporting inheritance. Owing to this property, simulation models +++^34em^*@[extending this simulation model]
Simulations which model includes additional features to the model of another simulation like new levels, new agents, new influences, //etc.//
=== can be created.

This class has to:
*Be //public//;
*Define a single //protected// constructor with no arguments;
*Contain as many //public statc final// fields from the {{{LevelIdentifier}}} class as the number of levels in the simulation.
*Be located into the ''"levels''" package.
{{clear{}}}
+++?[<span class="exbigbtn">Level identifiers list creation example</span>]
{{exsection {
This example illustrates the creation of a level identifiers list called {{className{MyAwesomeLevelList }}}. This list contains the "city", "slums", "country", "seashore" levels.

This example is also available in a [[stand alone file|./files/simulationModel/highLevel/MyAwesomeLevelList.java]].
!Code
<html><pre><object width='100%' height="500" type='text/plain' data='./files/simulationModel/highLevel/MyAwesomeLevelList.java' border='0' ></pre></object></html>
}}} ===

!!Using the list of level identifier
Once the class  of the level identifier list is declared, it becomes no longer necessary to create instances of the {{className{[[LevelIdentifier|../api/fr/lgi2a/similar/microkernel/LevelIdentifier.html]]}}} class to have access to the feratures of the simulation. Instead, users have to refer to a static field of the ''"level identifiers list"'' class.

+++?[<span class="exbigbtn">Usage example</span>]
{{exsection {
This example illustrates the use of the "level identifiers list" in replacement to the manual creation of level identifiers, in the context of the retrieval of the public local state in the "city" level of an agent.

Without using the "level identifiers list", the public local state of the agent in the "city" level is retrived with the following instructions:
{{{
IAgent agent = ...;
LevelIdentifier levelId = new LevelIdentifier( "city" );
ILocalStateOfAgent state = agent.getPublicLocalState( levelId  );
}}}
When using the list, the code becomes:
{{{
IAgent agent = ...;
ILocalStateOfAgent state = agent.getPublicLocalState( MyAwesomeLevelList.CITY );
}}}
}}} ===

{{nextButton{[[Go to the next step >>|SMD - Agents identification]]}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Specification of the agents}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Low level specifications]]  |  [[next step >>|SMD - Perception - Plan]]}}}
<html><hr class="topSep"/></html>
The behavior of an agent is defined by three different steps (see the image):
*The ''perception phase'', where the agent decodes the data from the public local dynamic state of the perceptible levels, identifies the relevant data and stores them into a ''perceived data set'';
*The ''global state revision phase'', where the agent revises its global state using the value of its former global state and the recently perceived data;
*The ''decision phase'', where the agent uses its perceived data and its revised global state to determine +++^15em^*@[what it does]//i.e.// create influences and send them to influenceable levels.===;
[img(100%,)[images/simulationModel/lowLevel/agentBehaviorModel.png]]

{{focusemphasisblock{
The next steps of the methodology consist in defining the operational code of the three parts of the behavior of each agent, for each level where they can lie.
}}}
{{bigemphasisblock{
Note that the specification process is not straightforward. It often consists in looping on these three phases:
*First define a basic structure (a skeleton);
*Then write a first specification of the decision process;
*Deduce from it the perceived data and the global state required by the behavior;
*Write the perception model retrieving the perceived data;
*Write the global state revision model updating the global state;
*Write a more precise specification of the decision process;
*//etc.//
}}}
{{nextButton{[[Go to the next step >>|SMD - Perception - Plan]]}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Low-level specifications of the simulation}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Influences skeleton]]  |  [[next step >>|SMD - Low level - Agents intro]]}}}
<html><hr class="topSep"/></html>
The ''high level specifications'' can be written only having a vague overview on the simulation, without knowing its precise inner mechanisms. To the contrary, the ''low level specifications'' phase of the methodology provide the precise implementation and operational code of the behavior of the agents, the natural action of the environment and of the reaction of the levels.

The low level specifications contain the following steps:
*Specification of the [[agents|SMD - Low level - Agents intro]]:
**Specification of the [[perception|SMD - Perception - Plan]] phase of the agents;
**Specification of the [[global state|SMD - Global state - Plan]] of the agents;
**Specification of the [[decision|SMD - Decision]] phase of the agents;
**Specification of the [[agent creation|SMD - Agent creation]] mechanism;
*Specification of the ''environment'':
**Specification of the [[natural action|SMD - Natural]] phase of the environment;
*Specification of the ''levels'':
**Specification of the [[reaction|SMD - Reaction]] phase of the levels;
{{nextButton{[[Go to the next step >>|SMD - Low level - Agents intro]]}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Specification of the environment}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Agent creation]]  |  [[next step >>|SMD - Reaction]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Natural - Intro]]>>
!Structure of the natural action model of the environment
<<tiddler [[SMD - Natural - Structure]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Natural - Specifications]]>>
!Writing the natural action phase of an environment class
<<tiddler [[SMD - Natural - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Reaction]]}}}
The implementation of this method consists in:
*Identifying the level from which the natural action is made;
*Getting the local dynamic state of the relevant perceptible levels;
*Getting and casting the public local state of the environment from the perceptible level, to access their various data;
*Casting the private local state of the environment, to access its various data;
*Getting and casting the public local state of the agents in each level, to access their various data;
*Creating influences based on the read information, and adding them to the {{argumentName{producedInfluences}}} map;
During the redaction of the natural action process, the information required by the natural action can become clearer. Therefore, this step will likely lead to the revision of:
*The data from the [[private local state|SMD - Private local states]] used as a parameter of the natural actions;
*The [[public local state of the perceived agents|SMD - Public local states]];
*The [[public local states of the environment|SMD - Public local states]];
*The [[regular influences|SMD - Influences skeleton]] produced by the decisions: it can lead either to the addition of new metadata to existing regular influences, or the creation of new regular influences;
*The [[influence relation graph|SMD - Level skeleton]]: new levels can be added to the levels that can be influenced by the level from which the decision is made;
+++?*[<span class="exbigbtn ">Natural action process full example</span>]
{{exsection{
<<tiddler [[SMD - Natural - Creation - Example]]>>
}}} ===
[>img[images/simulationModel/lowLevel/naturalTree.png]]
This example illustrates the use of the natural action of the environment in the context of a ''bubble chamber'' simulation.
<<<
//A bubble chamber is a vessel filled with a superheated transparent liquid (most often liquid hydrogen) used to detect electrically charged particles moving through it.
[...]
As particles enter the chamber, a piston suddenly decreases its pressure, and the liquid enters into a superheated, metastable phase. Charged particles create an ionisation track, around which the liquid vaporises, forming microscopic bubbles.//
@@display:block;text-align:right;__Source:__ http://en.wikipedia.org/wiki/Bubble_chamber@@
<<<
In this simulation, agents from the ''particle canon'' category fire ''particles'' in the ''bubble chamber'' level. The behavior of the ''particle'' agents only consists in moving. The environment (//i.e.// the superheated transparent liquid) generates the ''bubbles'' along the path of the ''particles'' with its natural action.

In this example, we focus on the definition of the natural action of the environment from the ''bubble chamber'' level. It creates a bubble at the same location than the ''particle'' agents.
{{clearright{}}}
!Code
This example assumes that:
*The levels identifier list of the simulation is implemented as the {{className{[[BubbleChamberLevelList|files/simulationModel/lowLevel/BubbleChamberLevelList.java]]}}} class;
*The agent categories list of the simulation is implemented as the {{className{[[BubbleChamberAgentCategoriesList|files/simulationModel/lowLevel/BubbleChamberAgentCategoriesList.java]]}}} class;
*The public local state of the particle agents is implemented as the {{className{AgtParticlePLSInChamber}}} class, containing:
**a {{methodName{getLocation()}}} method returning a {{className{Point2D}}} object modeling the location of the particle.
*The factory creating new agents from the ''bubble'' category  is implemented as the {{className{AgtBubbleFactory}}} class and defines the following static method:
**{{methodName{generate(double,double)}}} returning an instance of the {{className{IAgent4Engine}}} interface. Its parameters are the x and y coordinate of the bubble;
The natural action of the environment is implemented in a class named {{className{[[BubbleChamberEnvironment|files/simulationModel/lowLevel/BubbleChamberEnvironment.java]]}}} having the following code:
<html><pre><object width='100%' height='350px' type='text/plain' data='files/simulationModel/lowLevel/BubbleChamberEnvironment.java' border='0' ></pre></object></html>
The behavior of the environment is defined by a ''natural action phase'', where the environment decodes the data from the local dynamic state of the perceptible levels, to determine +++^34em^*@[what it does]//i.e.// create influences and send them to influenceable levels.=== (see the image).

[img(98%,)[images/simulationModel/lowLevel/envBehaviorModel.png]]
{{focusemphasisblock{
This step of the methodology consist in defining the operational code of the natural action of the environment for each level of the simulation.
}}}
[>img(45%,)[images/simulationModel/lowLevel/environmentDesignOutline4.png]]
In the micro-kernel of SIMILAR, the natural action process of the environment is modeled by the following method of the {{className{[[IEnvironment4Engine|../api/fr/lgi2a/similar/microkernel/environment/IEnvironment4Engine.html]]}}} interface:
{{clearright{}}}
{{{
public void natural(
   LevelIdentifier level,
   SimulationTimeStamp timeLowerBound,
   SimulationTimeStamp timeUpperBound,
   Map<LevelIdentifier, ILocalStateOfEnvironment> publicLocalStates,
   ILocalStateOfEnvironment privateLocalState,
   IPublicDynamicStateMap dynamicStates,
   InfluencesMap producedInfluences
);
}}}
This method defines the following parameters:
*{{argumentName{level}}} models the level from which the natural action is made;
*{{argumentName{timeLowerBound}}} models the lower bound of the transitory period for which the natural action is made;
*{{argumentName{timeUpperBound}}} models the upper bound of the transitory period for which the natural action is made; 
*{{argumentName{publicLocalStates}}} models the public local states of the environment in all the perceptible levels;
*{{argumentName{privateLocalState}}} models the private local state of the environment in the level from which the natural action is made;
*{{argumentName{dynamicStates}}} models the dynamic state of the perceptible levels when the natural action is made; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection {
<<tiddler [[IDynamicStateMap - Documentation]]>>
}}} ===

*{{argumentName{producedInfluences}}} models where the influences produced by the natural action of the environment are stored. Basically, it corresponds to the value returned by the application presented above; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection {
<<tiddler [[InfluencesMap - Documentation]]>>
}}} ===

<<tiddler [[System influences - Specifications]]>>
The ''natural action of the environment'' defines the dynamics of a level that are not the fruit of the behavior of the agents:
*The ''natural evolution'' of the ''state of the agents'', without the intervention of their behavior; +++?*[<span class="exsmallbtn">Example</span>]
{{exsection{
In the context of an ecosystem simulation, agents age independently from their behavior. Therefore, //agents aging// comes from the natural action of the environment.
}}}===

*The  ''natural evolution'' of the ''state of the environment''; +++?*[<span class="exsmallbtn">Example</span>]
{{exsection{
In the context of an ecosystem simulation, the behavior of the animals can be influenced by night/day cycles.  The current stage of the cycle is a field of the public local state of the environment. The evolution of that field comes from the natural action of the environment.
}}}===

In SIMILAR, the natural action model can be seen as an ''application'' taking into parameters the ''dynamic state of the perceptible levels'', and returning returning the ''influences'' modeling the actions the environment wishes to perform in the various influenceable levels.

<<tiddler [[System influences - Structure]]>>
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creating the directories and packages tree}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Preparation]]  |  [[next step >>|SMD - Tools preparation]]}}}
<html><hr class="topSep"/></html>
The first step of the design of a simulation model consists in creating the tree hierarchy where the sources are put. We recommend users to use a hierarchy where the source files are split by themes.
!Naming the simulation model
The name of the simulation model has first to be determined. It has to illustrate precisely the nature of the simulation model. Moreover, the name also has to respect the packages naming constraints of java:
#The full name has to start with a locale identification (//e.g.// "fr", "en", "de", //etc.//)
#The full name has then to identify the organization that wrote the model
#Finally the name of the model itself has to be defined.
According to the naming conventions of java, all these name have to be written in lowercase letters, and have to contain only letters or figures (a figure cannot have the leading position).

+++?[<span class="exbigbtn">Naming example</span>]
{{exsection {
A __bubble chamber simulation__ wrote by the __french__ team of the __LGI2A laboratory__ should have a name like:
<<<
//fr.univ_artois.lgi2a.bubblechamber//
<<<
}}}===
!Folders hierarchy
The project where the simulation is written has to use a specific folder hierarchy where sources are separated from binaries. To make to compilation of the simulations easier, we advise users to rely on the following [[Maven|http://maven.apache.org/]]-like hierarchy:

[<img[images/simulationModel/preparation/basicTree.png]]In this hierarchy, the {{{src/main/java}}} folder will contain the ''source files'' of the simulation model. 

The {{{target/bin}}} directory will contain the compiled binary files of the simulation model. 

The {{{README.txt}}} file contains the description of the simulation model: its purpose, its parameters, its output and how to interpret the output.{{clear{}}}

This structure is compatible with the [[Maven|http://maven.apache.org/]] project management and comprehension tool. Therefore, a maven build can be used to compile the simulation model.
!!Simulation model directory layout
Once the main directory hierarchy is installed, a package tree can be installed to facilitate the location and the future modification of the sources of the simulation model. We advise the use of the following distribution of packages:

[>img[images/simulationModel/preparation/basicPackagesTree.png]]This hierarchy uses a root package named after the name of the simulation model (see above). This root package contains:
*The ''engines''  package, containing the simulation engines of the simulation;
*The ''initializations'' package, containing different initial settings of the simulation model;
*The ''model'' package, defining the simulation model. It contains:
**The ''agents'' package containing the model of the agents;
**The ''environment'' package containing the model of the environment;
**The ''influences'' package containing the model of the influences;
**The ''levels'' package containing the model of the levels of the simulation;
*The ''probes'' package containing the observation probes used in the simulation;
*The ''tools'' package containing the miscellaneous tools that were used to implement the simulation.
{{clear{}}}
This structure is obviously not rigid. For instance, if the simulation uses predefined simulation engines and probes, and defines only one initial setting for the simulation, then a simplified package tree can be used.
!!Simulation model declaration
The declaration of the elements of the simulation model usually also creates a model-dependent sub-division of the presented hierarchy:
*The ''agents'' package is sub-divided into packages named after the various types of agents of the simulation;
*The ''environment'' and ''influences'' package are sub-divided into packages named after the various levels of the simulation.
*The ''levels'' package can be sub-divided into packages named after the various levels of the simulation. This happens if there are various implementations of the time model or of the reaction of the levels.

In addition, the package of an agent type is often sub-divided into packages named after the levels where it can lie.

+++?[<span class="exbigbtn">Package hierarchy example</span>]
{{exsection {
[>img[images/simulationModel/preparation/completePackagesTree.png]]
This example illustrates the full directory structure of a plane traffic simulation model where:
*There are two levels named ''Sky'' and ''Ground''
*The simulation contains ''Plane'' agents navigating in the ''Sky'' level and taking off or landing in the ''Ground'' level.
*The simulation contains ''Control tower'' agents telling ''Plane'' agents when they are authorized to land. These agents are only in the ''Ground'' level.
{{clear{}}}
}}}===

{{nextButton{[[Go to the next step >>|SMD - Tools preparation]]}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the perception model}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Perception - Perceived data]]  |  [[next step >>|SMD - Global state - Plan]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Perception - Structure]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Perception - Specifications]]>>
!Writing the perception phase of an agent class
<<tiddler [[SMD - Perception - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Global state - Plan]]}}}
The implementation of this method consists in:
*Identifying the level from which the perception is made;
*Casting the public local state of the agent in the appropriate class, to access its various data;
*Getting the local dynamic state of the relevant levels;
*Getting and casting the public local state of the environment in each level, to access its various data;
*Getting and casting the public local state of the agents in each level, to access their various data;
*Creating the perceived data and initializing its content;
During the redaction of the perception process, the information from the public local states that are required by the perception can become clearer. Therefore, this step will likely lead to the revision of:
*The [[public local state|SMD - Public local states]] of the agent or of the perceived agents;
*The [[public local state|SMD - Public local states]] of the environment;
*The [[private local state|SMD - Private local states]] of the agent in the level from which perception is made;
*The [[perception relation graph|SMD - Level skeleton]]: new levels can be added to the levels that can be perceived by the level from which the perception is made;
+++?*[<span class="exbigbtn ">Perception process full example</span>]
{{exsection{
[>img[images/simulationModel/lowLevel/perceptionTree.png]]
This example is a continuation of the example started in the documentation of the [[perceived data model|SMD - Perception - Perceived data]].
We illustrate the implementation of the perception process of a ''lion'' agent, assuming that:
*The ''Sky'' and ''Savannah'' levels use a 2D grid topology (see [[this page|SMD - Public local states]]);
*The ''Lion'' agent defines a 2D coordinate in the ''Savannah'' level (see [[this page|SMD - Public local states]]);
*The ''Gazelle'' agents define a public local state in the ''Savannah'' level named {{className{AgtGazellePLSInSavannahLevel}}}, where their age can be read using the {{methodName{getAge()}}} method;

The perception process of a ''Lion'' consists in listing the young gazelles (younger than 3 years) agents in a 300 meters square centered on the location of the lion. This implies that the private local state of the "Lion" agent in the "Savannah" level contains two information:
*The ''perception radius'' where the gazelles can be seen (here 300 meters)
*The ''age threshold'' under which gazelles are preyed on (here 3 years).
The {{className{[[AgtLionHLSInSavannahLevel|files/simulationModel/lowLevel/AgtLionHLSInSavannahLevel.java]]}}} class implements such a private local state.
{{clearright{}}}
!Code
The sources of this class are also available in a [[stand alone file|files/simulationModel/lowLevel/AgtLion.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/lowLevel/AgtLion.java' border='0' ></pre></object></html>
}}} ===
The behavior of an agent is defined by three different steps (see the image):
*The ''perception phase'', where the agent decodes the data from the public local dynamic state of the perceptible levels, identifies the relevant data and stores them into a ''perceived data set'';
*The ''global state revision phase'', where the agent revises its global state using the value of its former global state and the recently perceived data;
*The ''decision phase'', where the agent uses its perceived data and its revised global state to determine what it does;
{{focusemphasisblock{
This step of the methology focuses on the creation of both the //perceived data set// and the //perception phase// of each agent, for each level where the agent can lie.
}}}
[img(100%,)[images/simulationModel/lowLevel/agentBehaviorModel_perception.png]]
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the perceived data}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Perception - Plan]]  |  [[next step >>|SMD - Perception]]}}}
<html><hr class="topSep"/></html>
The ''perceived data set'' of an agent from a specific level models the data from the public dynamic state of the perceptible levels that are read by the decision process of the agent. Roughly said, it models //"what the agent sees from the various perceptible level"//.

{{focusemphasisblock{
This step of the methology focuses on the creation of the //perceived data set// of each agent, for each level where the agent can lie.
}}}
!!Structure of the perceived data in SIMILAR
<<tiddler [[SMD - Perception - Perceived data - Structure]]>>
!!Specifications and implementation instructions
<<tiddler [[SMD - Perception - Perceived data - Specifications]]>>
!!Creating a perceived data set in SIMILAR
<<tiddler [[SMD - Perception - Perceived data - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Perception]]}}}
The constructor of the perceived data set has to comply with the following requirements:
*The ''level'' from which the data were perceived has to be set;
*The ''transitory period'' during which the data were perceived has to be set;
The generated class has to:
*Be located in the ''agents.XYZ.ABC'' where ''XYZ'' is the category of the agent performing the perception and ''ABC'' is the identifier of the level from which the perception was made;
*Be named:
**Explicitly after the level from which they were perceived;
**Explicitly after the category of the agent performing the perception;
**Intelligibly named, in order to be readable^^//''1''//^^;
*Either:
**Define {{{public final}}} fields containing the perceived data;
**Define read access methods to the perceived data;
The implementation of the obligatory method of the perceived data (see the previous section) has either to be done manually (micro-kernel only approach) or with the {{className{[[AbstractPerceivedData|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractPerceivedData.html]]}}} class (micro-kernel with common libs approach).
~~//''__1:__ For instance using "PDF" in replacement for "Perceived Data From" and "Agt" for "Agent".''//~~

+++?*[<span class="exbigbtn ">Perceived data set full example</span>]
{{exsection{
[>img[images/simulationModel/lowLevel/perceivedDataTree.png]]
This example illustrates an implementation of the perceived data set of a ''lion'' agent from the ''Savannah'' level, in the context of a ''wildlife'' simulation. In this simulation, the lion takes into consideration the nearby preys it sees in the ''Savannah'' level and the location of neayby vultures in the ''Sky'' level to determine where it will hunt preys.

These perceived data are defined in the {{packageName{agents.lion.savannah}}} package of the model tree hierarchy (see the image).
{{clearright{}}}
!Code
If this model defines a "wildlife" simulation, having specific [[levels identifier list|files/simulationModel/highLevel/WildlifeLevelList.java]] and [[agent categories list|files/simulationModel/highLevel/WildlifeAgentCategoriesList.java]], then the perceived data of the "Lion" agent from the "Savannah" level can be implemented as the following classes:
*As {{className{AgtLionPDFSavannah}}} with the micro-kernel only approach; +++?*[<span class="implsmallbtn ">Implementation</span>]
{{implsection{
The following code illustrates the implementation of the perceived data set using only the micro-kernel. The sources of this class are also available in a [[stand alone file|files/simulationModel/lowLevel/AgtLionPDFSavannah.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/lowLevel/AgtLionPDFSavannah.java' border='0' ></pre></object></html>
}}} ===

*As {{className{AgtLionPDFSavannah2}}} with the micro-kernel with common libs approach; +++?*[<span class="implsmallbtn ">Implementation</span>]
{{implsection{
The following code illustrates the implementation of the perceived data set using only the micro-kernel. The sources of this class are also available in a [[stand alone file|files/simulationModel/lowLevel/AgtLionPDFSavannah2.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/lowLevel/AgtLionPDFSavannah2.java' border='0' ></pre></object></html>
}}} ===

}}} ===
In SIMILAR, a perceived data set is modeled as an instance of the {{className{[[IPerceivedData|../api/fr/lgi2a/similar/microkernel/agents/IPerceivedData.html]]}}} interface. This interface defines accessors to the level from which the perception was made as well as to the transitory period during which the data were perceived. The perceived data themselves are context dependent, and therefore are not explicitly part of this interface. They have to be ''defined as fields'' and have to be ''accessed through read only methods'' in the subclasses of the {{className{IPerceivedData}}} interface.

Each class implementing the {{className{IPerceivedData}}} interface have to define the following methods:
*{{methodName{getLevel()}}} gets the ''level'' from which the data were perceived; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IPerceivedData.html#getLevel()]]}}} +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Adding a field to the class having the type {{className{IPerceivedData}}};
*Setting its value in the constructor of the class;
*Granting access to that field in the appropriate method (//i.e.// {{methodName{getLevel()}}}).
}}} ===

*{{methodName{getTransitoryPeriodMin()}}} gets the time stamp modeling the ''lower bound'' of the ''transitory period'' when the data were perceived; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IPerceivedData.html#getTransitoryPeriodMin()]]}}} +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Adding a field to the class having the type {{className{[[SimulationTimeStamp|../api/fr/lgi2a/similar/microkernel/agents/SimulationTimeStamp.html]]}}};
*Setting its value in the constructor of the class;
*Granting access to that field in the appropriate method (//i.e.// {{methodName{getTransitoryPeriodMin()}}}).
}}} ===

*{{methodName{getTransitoryPeriodMax()}}} gets the time stamp modeling the ''upper bound'' of the ''transitory period'' when the data were perceived; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/IPerceivedData.html#getTransitoryPeriodMax()]]}}} +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Adding a field to the class having the type {{className{[[SimulationTimeStamp|../api/fr/lgi2a/similar/microkernel/agents/SimulationTimeStamp.html]]}}};
*Setting its value in the constructor of the class;
*Granting access to that field in the appropriate method (//i.e.// {{methodName{getTransitoryPeriodMax()}}}).
}}} ===

{{bigemphasisblock{Note that the [[common libraries|./commonlibs/index.html]]<script>place.lastChild.target="_self";</script> of the micro-kernel define the {{className{[[AbstractPerceivedData|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractPerceivedData.html]]}}} abstract class providing a default implementation to this method.}}}
[>img(40%,)[images/simulationModel/lowLevel/perceivedDataOutline.png]]
In SIMILAR, the perceived data set can contain:
*+++^36em^*@[<strong>raw data</strong>]//i.e.// a reference to the data already existing in the dynamic state.=== from the dynamic state; +++?*[<span class="exsmallbtn ">Example</span>]
{{exsection{
The perceived data set can contain a ''reference'' to the public local state of a perceived agent. For instance, in the context of wildlife simulation, a predator can eat a prey. Therefore, the predator has to perceive its potential preys, as a set of public local state of agents.
}}} ===

*+++^36em^*@[<strong>interpreted data</strong>]//i.e.// data that are deducted from the raw data of the dynamic state.=== from the dynamic state. +++?*[<span class="exsmallbtn ">Example</span>]
{{exsection{
In a road traffic simulation, the public local state of an agent embeds its location in the road network. The behavior of most vehicles consist in adapting their acceleration in accordance with the current speed, the acceleration and the distance from the leading vehicle. The distance between two vehicles does not exist in the dynamic state of the simulation: it has to be computed using the absolute location of the vehicles.

Therefore, in the perceived data of a vehicle:
*the current ''speed'' and ''acceleration'' of the leading vehicle are raw data (they already exist in the public local state of the vehicle agents);
*the ''distance from the leading vehicle'' is deducted from the position of the vehicle performing the perception and the position of the leading vehicle: it is an interpretation of the raw data from the dynamic state.
}}} ===

Moreover, since perception is always relative to a level, the perceived data set of an agent always identify ''the level'' from which the perception was made.
{{clearright{}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Specification of the perception}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Low level - Agents intro]]  |  [[next step >>|SMD - Perception - Perceived data]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Perception - Introduction]]>>
!Specifying the perception process of an agent class
The specification of the perception process of an agent relies on the implementation of two distinct elements:
*The model of the data being perceived by the agent, //i.e.// a perceived data model;
*The model determining how the perceived data model is filled with data, using the current state of the agent and of the perceptible levels;
{{nextButton{[[Go to the next step >>|SMD - Perception - Perceived data]]}}}
[>img(40%,)[images/simulationModel/lowLevel/agentDesignOutline4.png]]
In the micro-kernel of SIMILAR, the perception model of an agent from a specific level is modeled as the following method of the {{className{[[IAgent4Engine|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html]]}}} interface:
{{{
public IPerceivedData perceive( 
	LevelIdentifier level,
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound,
	Map<LevelIdentifier, ILocalStateOfAgent> publicLocalStates,
	ILocalStateOfAgent privateLocalState,
	IPublicDynamicStateMap dynamicStates
);
}}}
This method defines the following parameters:
*{{argumentName{level}}} defines the identifier of the level from which perception is made;
*{{argumentName{timeLowerBound}}} identifies the lower bound of the transitory period during which the perception is made;
*{{argumentName{timeUpperBound}}} identifies the upper bound of the transitory period during which the perception is made;
*{{argumentName{publicLocalStates}}} identifies the public local state of the agent in each level;
*{{argumentName{privateLocalState}}} identifies the private local state of the agent in the level from which the perception is made;
*{{argumentName{dynamicStates}}} is a data structure listing the local dynamic state of the perceptible levels from {{argumentName{level}}};  +++?*[<span class="docsmallbtn">Documentation</span>]
{{docsection{
<<tiddler [[IDynamicStateMap - Documentation]]>>
}}} ===

This method returns an instance of the ''perceived data'' that were created during the previous step of the methodology.

{{bigemphasisblock{
The specification of this method implies knowledge about the specifications of the ''local dynamic state of a level''. If the user is not familiar with that concept and its implementation in this API suite, then [[read this documentation|Consistent local dynamic state of a level]].
}}}
In SIMILAR, the perception model can be seen as an ''application'' taking into parameters the ''dynamic state of the perceptible levels'', and returning a ''perceived data set''.

The ''perceived data set'' of an agent from a specific level models the data from the public dynamic state of the perceptible levels that are read by the decision process of the agent. Roughly said, it models //"what the agent sees from the various perceptible levels"//.

{{focusemphasisblock{
This step of the methology focuses on the specification of the //perception phase// of each agent, for each level where the agent can lie.
}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Preparing the design}}}
{{guidelinesNavMenu{[[<< previous step|Simulation models]]  |  [[next step >>|SMD - Package tree]]}}}
<html><hr class="topSep"/></html>
Before heading into the code of the simulation model, we have first to organize and prepare the sources. Indeed, the revision of a model is made easier if the code to update can be identified and located quickly. The first step of the simulation design consists in creating such a source tree structure.

This first main step creates the general structure of the simulation model:
*The [[source tree hierarchy|SMD - Package tree]]
*The [[tools|SMD - Tools preparation]] that are used in many classes of the simulation model:
**The [[random values generation|SMD - Tools preparation - Random]] tool
**The [[parameters management|SMD - Tools preparation - Parameters]] tool
{{nextButton{[[Go to the next step >>|SMD - Package tree]]}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the skeleton of the private states}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Public local states]]  |  [[next step >>|SMD - Influences skeleton]]}}}
<html><hr class="topSep"/></html>
The next step of the methodology consists in identifying the part of the ''local state'' of the agents (and of the environment) that cannot be perceived. Once identified, a ''private local state'' can be created for each of these entities.

{{focusemphasisblock{
This step focuses on the creation of the skeleton of the private local state classes:
*A class for each agent category and for each level where an agent from that category can lie;
*A class for each level where the environment is.
}}}
Note that the content of the private local states is completed during the whole simulation design process. 
!Structure of a private local state in SIMILAR
<<tiddler [[SMD - Private local states - Structure]]>>
!Specifications, implementation and creation instructions
<<tiddler [[SMD - Private local states - Specifications]]>>
{{nextButton{[[Go to the next step >>|SMD - Influences skeleton]]}}}
[>img(47%,)[images/simulationModel/highLevel/environmentDesignOutline3.png]]
In SIMILAR, a private local state of the environment is modeled as an instance of the {{className{[[ILocalStateOfEnvironment|../api/fr/lgi2a/similar/microkernel/environment/ILocalStateOfEnvironment.html]]}}} interface, just like for public local states. Therefore, refer to the [[previous step|SMD - Public local states]] to get the general instructions to implement a private state.

Since ''private'' and ''public'' have the same abbreviation, we recommend to use the word "''Hidden''" in the abbreviation of the name of a private local state. 
For instance {{className{EnvHLSInSavannah}}} for the private local state of the environment in the //"Savannah"// level.
{{clearright{}}}
{{bigemphasisblock{Note that the [[common libraries|./commonlibs/index.html]]<script>place.lastChild.target="_self";</script> of the micro-kernel define the {{className{[[AbstractLocalStateOfEnvironment|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractLocalStateOfEnvironment.html]]}}} abstract class providing a default implementation to this method.}}}
[<img(47%,)[images/simulationModel/highLevel/agentDesignOutline3.png]]
The private local state of the agents has to implement a more specialized interface called {{className{[[ILocalStateOfAgent4Engine|../api/fr/lgi2a/similar/microkernel/agents/ILocalStateOfAgent4Engine.html]]}}}, just like for public local states. Therefore, refer to the [[previous step|SMD - Public local states]] to get the general instructions to implement a private state.

Since ''private'' and ''public'' have the same abbreviation, we recommend to use the word "''Hidden''" in the abbreviation of the name of a private local state. 
For instance //"AgtLionHLSInSavannah"// for the private local state of a //"Lion"// agent in the //"Savannah"// level.
{{clear{}}}
{{bigemphasisblock{Note that the [[common libraries|./commonlibs/index.html]]<script>place.lastChild.target="_self";</script> of the micro-kernel define the {{className{[[AbstractLocalStateOfAgent|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractLocalStateOfAgent.html]]}}} abstract class providing a default implementation to these methods.}}}
In SIMILAR, a ''private local state'' models all the local information used to parameter:
*The [[perception|SMD - Perception]] and [[decision|SMD - Decision]] processes of the agents; +++?[<span class="exsmallbtn">Example</span>]
{{exsection {
The private local state of an agent can define the depth of its perception radius, the destinations it wishes to reach, a threshold triggering the creation of an influence, //etc.//
}}} ===

*The [[natural action process|SMD - Natural]] of the environment; +++?[<span class="exsmallbtn">Example</span>]
{{exsection {
The private local state of the environment can define a threshold triggering the creation of an influence, the ambient temperature evolution speed, //etc.//
}}} ===

[>img(45%,)[images/simulationModel/highLevel/privateLocalStateOutline1.png]]
The ''private local state'' of an agent in a level is the sum of the following elements:
*The ''identifier of the level'' where it lies;
*The ''owner'' of the state, //i.e.// the agent it belongs to;
*The ''non-perceptible data'' of the agent in that level.
{{clearright{}}}
[<img(45%,)[images/simulationModel/highLevel/privateLocalStateOutline2.png]]
The ''private local state'' of the environment in a level is the sum of the following elements:
*The ''identifier of the level'' where it lies;
*The ''non-perceptible data'' of the environment in that level.
{{clearright{}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the public local states}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Time model]]  |  [[next step >>|SMD - Private local states]]}}}
<html><hr class="topSep"/></html>
The next step of the methodology consists in identifying the part of the ''local state'' of the agents (and of the environment) that can be perceived. Once identified, a ''public local state'' can be created for each of these entities. Note that the non-perceptible part, called ''private local state'' uses a similar structure (see the next step).

{{focusemphasisblock{
This step focuses on the creation of public local state classes:
*A class for each agent category and for each level where an agent from that category can lie;
*A class for each level where the environment is.
}}}
Note that the identification of all the perceptible information at this stage is difficult, especially in big models. Consequently, the content of the public local states is completed during the whole simulation design process. Despite this, we highly recommend to identify as much elements as possible at this stage.
!Structure of a public local state in SIMILAR
<<tiddler [[SMD - Public local states - Structure]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Public local states - Implementation]]>>
!Creating public local states in SIMILAR
<<tiddler [[SMD - Public local states - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Private local states]]}}}
The constructor of a public local state has to comply with the following requirements:
*The ''identifier of the level'' of the state has to be set;
*The ''owner'' of the state has to be set (//public local state of agents only//);
*The ''topology'' of the environment has to be created and empty (//public local state of environment only//);
*The ''perceptible data'' of the state have to be initialized, using constructor arguments;
The generated class for a public local state in a level identified by "lvl" has to:
*Be located in the package ''agents.agtCat.lvl'' package, if the local state belongs to an agent which category is "agtCat";
*Be located in the package ''environment.lvl'' package, if the local state belongs to the environment;
*Be named:
**Explictly after the level they are lying in;
**Explicitly after the category of the agent they belong to (//public local state of agents only//);
**Intelligibly named, in order to be readable^^//''2''//^^
*Define accessors to the perceptible data.
The implementation of the generic methods (see the previous section) is either done manually (micro-kernel only approach) or with the {{className{[[AbstractLocalStateOfEnvironment|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractLocalStateOfEnvironment.html]]}}} or {{className{[[AbstractLocalStateOfAgent|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractLocalStateOfAgent.html]]}}} classes (micro-kernel with common libs).
~~//''__2:__ For instance using "PLS" in replacement for "Public Local State of", "Env" for "Environment" or "Agt" for "Agent".''//~~

+++?*[<span class="exbigbtn">Example of a public local state of the environment</span>]
{{exsection{
[>img[images/simulationModel/highLevel/publicLocalStateTree1.png]]
In this example, we illustrate the creation of the ''public local state'' of the environment in a level identified by "Savannah". This state defines the following perceptible data:
*The ambient temperature
*The ambient humidity level
It also defines a "grid" topology, where the public local state of the agents of that level are put.

The created state is named {{className{PLSEnvInSavannahLevel}}}^^//''2''//^^. This class is defined in the context of a "wildlife" simulation. Therefore, it lies in the {{packageName{fr.univ_artois.lgi2a.wildlifesimulation.model.environment.savannah}}} package.
{{clear{}}}
!Code
If the model defines a "wildlife" simulation, having specific [[levels identifier list|files/simulationModel/highLevel/WildlifeLevelList.java]] and [[agent categories list|files/simulationModel/highLevel/WildlifeAgentCategoriesList.java]], then the public local state of the environment can be implemented as the following classes:
*As {{className{PLSEnvInSavannahLevel}}} with the micro-kernel only approach; +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The sources of this class are also available in a [[stand alone file|./files/simulationModel/highLevel/PLSEnvInSavannahLevel.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/highLevel/PLSEnvInSavannahLevel.java' border='0' ></pre></object></html>
}}} ===

*As {{className{PLSEnvInSavannahLevel2}}} with the micro-kernel with common libs approach;  +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The sources of this class are also available in a [[stand alone file|./files/simulationModel/highLevel/PLSEnvInSavannahLevel2.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/highLevel/PLSEnvInSavannahLevel2.java' border='0' ></pre></object></html>
}}} ===

~~//''__2:__ "PLSEnv" stands for "Public Local State of the Environment". The name is purposely shortened to keep readable class names.''//~~
}}} ===


+++?*[<span class="exbigbtn">Example of a public local state of an agent</span>]
{{exsection{
[>img[images/simulationModel/highLevel/publicLocalStateTree2.png]]
In this example, we illustrate the creation of the ''public local state'' of an agent from the category "Lion" in a level identified by "Savannah". This state defines the following perceptible data:
*The coordinates of the lion in the environment;
*The age of the lion.
The created state is named {{{AgtLionPLSInSavannahLevel}}}^^//''3''//^^. This class is defined in the context of a "wildlife" simulation. Therefore, it lies in the {{{fr.univ_artois.lgi2a.wildlifesimulation.model.agents.lion.savannah}}} package.
{{clear{}}}
!Code
If this model defines a "wildlife" simulation, having specific [[levels identifier list|files/simulationModel/highLevel/WildlifeLevelList.java]] and [[agent categories list|files/simulationModel/highLevel/WildlifeAgentCategoriesList.java]], then the public local state of the "Lion" agent in the "Savannah" level can be implemented as the following classes:
*As {{className{AgtLionPLSInSavannahLevel}}} with the micro-kernel only approach; +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The sources of this class are also available in a [[stand alone file|./files/simulationModel/highLevel/AgtLionPLSInSavannahLevel.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/highLevel/AgtLionPLSInSavannahLevel.java' border='0' ></pre></object></html>
}}} ===

*As {{className{AgtLionPLSInSavannahLevel2}}} with the micro-kernel with common libs approach; +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The sources of this class are also available in a [[stand alone file|./files/simulationModel/highLevel/AgtLionPLSInSavannahLevel2.java]]:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/highLevel/AgtLionPLSInSavannahLevel2.java' border='0' ></pre></object></html>
}}} ===

~~//''__3:__ "PLS" stands for "Public Local State". The name is purposely shortened to keep readable class names.''//~~
}}} ===
[>img(47%,)[images/simulationModel/highLevel/environmentDesignOutline3.png]]
In SIMILAR, a public local state of the environment is modeled as an instance of the {{className{[[ILocalStateOfEnvironment|../api/fr/lgi2a/similar/microkernel/environment/ILocalStateOfEnvironment.html]]}}} interface. This interface defines only an access method to the identifier of the level where the state is located. The perceptible data contained in the state are not explicitly specified in the interface, since they can take very different shapes. It is up to the user to define and grant access to them in the implementation of the interface.

Each class implementing the {{className{IPublicLocalState}}} interface have to define the following method:
*{{methodName{getLevel()}}} gets the ''identifier of the level'' where the state is located; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/ILocalState.html#getLevel()]]}}} +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in either:
*Adding a field to the class having the type {{className{LevelIdentifier}}};
*Setting its initial value in the constructor of the class;
*Granting access to that field in the appropriate methods (i.e. {{methodName{getLevel( )}}}).
Or:
*Directly returning a reference to the level identifier defined in the levels identifier list.
}}} ===

{{bigemphasisblock{Note that the [[common libraries|./commonlibs/index.html]]<script>place.lastChild.target="_self";</script> of the micro-kernel define the {{className{[[AbstractLocalStateOfEnvironment|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractLocalStateOfEnvironment.html]]}}} abstract class providing a default implementation to this method.}}}
{{clear{}}}
[<img(47%,)[images/simulationModel/highLevel/agentDesignOutline3.png]]
The public local state of the agents has to implement a more specialized interface called {{className{[[ILocalStateOfAgent4Engine|../api/fr/lgi2a/similar/microkernel/agents/ILocalStateOfAgent4Engine.html]]}}}. This interface specifies:
*an accessor to the level of the state;
*an accessor to the category of the agent owning the state;
*an accessor to the agent owning of the state^^''//1//''^^;
*a method checking if an agent is the owner of the state.
Likely to the public state of the environment, the perceptible data contained in the local state of an agent are not explicitly specified in the interface, since they can take very different shapes. It is up to the user to define and grant access to them in the implementation of the interface.
{{clear{}}}
Each class implementing the {{className{[[ILocalStateOfAgent4Engine|../api/fr/lgi2a/similar/microkernel/agents/ILocalStateOfAgent4Engine.html]]}}} interface have to define the following methods:
*{{methodName{getLevel()}}} gets the ''identifier of the level'' where the state is located (see above);
*{{methodName{getCategory( )}}} gets the ''category of the owner'' of this state; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/ILocalStateOfAgent.html#getCategoryOfAgent()]]}}}  +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Getting the agent owning of the state (i.e. {{methodName{getOwner( )}}});
*Returning the category of that agent (i.e. {{methodName{getCategory( )}}}).
}}} ===

*{{methodName{getOwner()}}} gets the agent ''owning'' the state; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/ILocalStateOfAgent4Engine.html#getOwner()]]}}} +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Adding a field to the class having the type {{className{[[IAgent4Engine|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html]]}}};
*Setting its initial value in the constructor of the class;
*Granting access to that field in the appropriate methods (i.e. {{methodName{getOwner( )}}}).
}}} ===

*{{methodName{isOwnedBy(...)}}} determines if an agent is the owner of the state or not; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/agents/ILocalStateOfAgent.html#isOwnedBy(fr.univ_artois.lgi2a.similar.microkernel.agents.IAgent)]]}}}  +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
The implementation of this method usually consists in:
*Comparing the argument of the method and the value returned by the {{methodName{getOwner()}}} method.
}}} ===

~~//''__1:__ The access to the agent owning the stateis only used in the simulation engines for optimization purposes.''//~~

{{bigemphasisblock{Note that the [[common libraries|./commonlibs/index.html]]<script>place.lastChild.target="_self";</script> of the micro-kernel define the {{className{[[AbstractLocalStateOfAgent|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractLocalStateOfAgent.html]]}}} abstract class providing a default implementation to these methods.}}}
In SIMILAR, we distinguish the ''public local state'' of the agents and of the environment. This distinction is made because during its behavior, an agent might want to perceive only the public local state of agents from a specific category. This implies that the owner of the public local state of an agent can be known.
[>img(45%,)[images/simulationModel/highLevel/publicLocalStateOutline1.png]]
The ''public local state'' of an agent in a level is the sum of the following elements:
*The ''identifier of the level'' where it lies;
*The ''owner'' of the state, //i.e.// the agent it belongs to;
*The ''perceptible data'' about the agent in that level.
{{clearright{}}}
[<img(45%,)[images/simulationModel/highLevel/publicLocalStateOutline2.png]]
The ''public local state'' of the environment in a level is the sum of the following elements:
*The ''identifier of the level'' where it lies;
*The ''perceptible data'' about the environment in that level.
{{clearright{}}}
Note that the perceptible data about the environment contain ''"regular" perceptible data'' (//e.g.// an ambient temperature) and ''topology-related data''. The topology related data can take different shapes, but share the same principle: they offer a data structure facilitating the access to the public local state of all (or a subset of) the agents lying in the level.

+++?*[<span class="exbigbtn">Topology example: an agent grid</span>]
{{exsection{
[>img(25%,)[images/simulationModel/highLevel/netlogo_wolfsheep.png]]
In predatory/prey simulations, it is not unusual to organize the environment in a grid, where each animal has an \((x,y)\) coordinate. In this context, the environment can provide a data structure ensuring a fast access to the animals located in a specific area of the grid (instead of iterating over each animal and checking their coordinates).

If we assume that the level identified by "field" contains the animals, then:
*The public local state of the animal agents in the "field" level specifies the coordinate of the animal in that grid, as a couple of floating point values;
*The public local state of the environment in the "field" level maintains a two dimentionnal array named "grid", where:
**The cell \(grid[x][y]\) contains the public local state of the animals having \((a,b)\) as their current coordinate, where \(a=\lfloor{}x\rfloor{}\) and \(b=\lfloor{}y\rfloor{}\).
The coherence of the "grid" contained in the public local state of the environment is managed during the [[reaction phase|SMD - Reaction]] of the level, when handling different influences:
*The addition of an "animal" agent to the level implies its addition in the corresponding cell of the grid;
*The removal of an "animal" agent from the level implies its removal from the corresponding cell of the grid;
*The modification of the coordinate of an "animal" agent in the level implies its removal from its previous position in the grid and its addition to its new position in the grid;
~~//''* The image comes from the website of the [[netlogo platform|http://ccl.northwestern.edu/netlogo/models/WolfSheepPredation]]''//~~
}}} ===


+++?*[<span class="exbigbtn">Topology example: agents per category</span>]
{{exsection{
In simulations containing many different agent categories and many agents, it becomes more efficient to keep track of the agents according to their category instead of searching systematically for them in the dynamic state of the simulation. In this context, the environment can provide a data structure ensuring a fast access to the agents having a specific category.

In such a simulation, the public local state of the environment in a level can specify a data structure mapping an agent category to the set of public local state of agents having that category.

The coherence of the data structure contained in the public local state of the environment is managed during the [[reaction phase|SMD - Reaction]] of the level, when handling different influences:
*The addition of an agent to the level implies its addition in the data mapping of the environment;
*The removal of an agent from the level implies its removal from the data mapping of the environment;
}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Specification of the reaction of the levels}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Natural]]  |  [[next step >>|SMD - Reaction - To system influences]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Reaction - Intro]]>>
!Structure of the reaction model of a level
<<tiddler [[SMD - Reaction - Structure]]>>
{{nextButton{[[Go to the next step >>|SMD - Reaction - To system influences]]}}}
The side effects on the simulation of the influences created by the behavior of the agents and of the environment are managed through the ''reaction phase'' of the levels (see the image). 

[img(98%,)[images/simulationModel/lowLevel/levelReactionModel.png]]
{{focusemphasisblock{
This step of the methodology consist in defining the operational code of the reaction of each level of the simulation.
}}}
The ''reaction of a level'' determines how the influences are taken into account in the evolution of the simulation. It defines:
*how the ''public or private local state'' of the agents and of the environment ''change'' according to the changes depicted by these influences; +++?*[<span class="exsmallbtn">Example</span>]
{{exsection{
In the wildlife simulation example described in the previous steps of the methodology, a lion agent ages. Since aging does not come from the behavior of the lion, this phenomenon is modeled as an influence coming from the natural action of the environment.
The ''Grow old'' influence sent by the natural action of the environment implies the update of the ''age'' field of the public local state of the ''Lion'' agent in the ''Savannah'' level during the reaction of the ''Savannah'' level.
[img(98%,)[images/simulationModel/lowLevel/reactionExample1.png]]
}}} ===

*if an influence models an actions that has not finished yet. In such a case, the influence ''persists'' in the new consistent dynamic state of the level after the reaction; +++?*[<span class="exsmallbtn">Example</span>]
{{exsection{
For instance, in a road trafic simulation, a vehicle can decide to ''overtake'' another vehicle. The overtaking maneuver is not instantaneous. Therefore, the ''overtake'' influence can persist in the dynamic state of the simulation, so that each reaction moves little by little the vehicle towards its target lane.
}}} ===

*how influences requesting the access to the same resource (''colliding influences'') are managed.  +++?*[<span class="exsmallbtn">Example</span>]
{{exsection{
If the reaction to two individual influences implies writing and reading the same item of a public or private local state, then a ''collision'' occurs between the influences. Depending on the case, the collision can have a great impact on simulation results. Therefore, the reaction has to pay specific attention to them.
!Colliding influences causing a conflict
In the best cases, the colliding influences are mutually exclusive. The reaction has then to determine the influence that has to be taken into account, and the influences that have to be ignored.

This is for instance the case of a predator/prey simulation, where two predators try to eat a prey at the same time (see the image).
[img(98%,)[images/simulationModel/lowLevel/reactionExample2.png]]
!Colliding influences causing an ambiguity
In the worst case, colliding influences are not mutually exclusive. Though they have an effect the one on the other, nor error is caught when such cases appear.

For instance, in a bubble chamber simulation where a magnetic field is applied:
*the natural action of the environment influences the acceleration of particles with its magnetic field;
*the particles decide to move forward in the chamber^^''//1//''^^.
To preserve the consistency of the results, the mangetic field has to be applied either before or after the management of the move of all the particles.
~~''//__1:__ The very same problem happens if the particle agents are not agentified: the natural action of the environment produces different influences that still have to be managed in the reaction.//''~~
[img(98%,)[images/simulationModel/lowLevel/reactionExample3.png]]
}}} ===

In SIMILAR, the reaction model of a level can be seen as an ''application'' taking into parameters both the ''most recent consistent state'' of the level and the ''influences that were recently sent'' to the level, and returning the ''updated value of the consistent state'' of the level.

[<img(65%,)[images/simulationModel/lowLevel/levelReactionAlgorithm.png][images/simulationModel/lowLevel/levelReactionAlgorithm.png]] To include the generic algorithms managing the reaction to the system influences, the reaction process of the levels is performed in five steps:
#The ''engine'' reacts to the ''system influences'' aimed at the levels computing a reaction, to add/remove agents to them;
#The ''simulation model'' can react to the ''system influences'' of the previous step, to update the topology of the environment when an agent is added/removed;
#The ''simulation model'' reacts to the ''regular influences'' aimed at the levels computing a reaction. If agents were to be added/removed during this reaction, then create system influences;
#The ''engine'' reacts to the ''system influences'' produced in the previous step;
#The ''simulation model'' can react to the ''system influences'' of the previous step.
{{clearleft{}}}
{{bigemphasisblock{
Consequently, the model of a level has to specify two parts of the reaction:
*A user-defined reaction to a set of system influences;
*A user-defined reaction to a set of regular influences, possibly producing system influences.
}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Defining the reaction to regular influences}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Reaction - To system influences]]  |  [[next step >>|SMD - Final steps]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Reaction - To regular influences - Intro]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Reaction - To regular influences - Specifications]]>>
!Writing the reaction to regular influences of a level class
<<tiddler [[SMD - Reaction - To regular influences - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Final steps]]}}}
The implementation of this method consists in:
*Iterating over the system influences provided as an argument;
**Checking the category of the influence; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
All the regular influence classes of a simulation have define a {{{public static final}}} field named {{fieldName{CATEGORY}}} corresponding to the category of the regular influence. Therefore, checking the category of the influence consists in comparing the category of the influence to the {{fieldName{CATEGORY}}} field of a regular influence class.
}}} ===

**Cast the influence in the appropriate type;
**Checking if the influence might collide with other influences:
***Storing the influence in a variable to delay its management;
**Else
***Processing its side effects immediately;
***Include the influences that were created as a side effect into the {{argumentName{remainingInfluences}}} argument;
*Grouping the influences by possible collisions;
*Iterating over the groups of collisions:
**Handling the reaction to each collision either by ordering the management of the colliding influences or by ignoring some of them;
During the redaction of the reaction process, the information required by the reaction can become clearer. Therefore, this step will likely lead to the revision of:
*The data from the [[public local state|SMD - Public local states]] of the environment or of the agents;
*The [[regular influences|SMD - Influences skeleton]] produced by the decisions: it can lead either to the addition of new metadata to existing regular influences, or the creation of new regular influences;
*The [[influence relation graph|SMD - Level skeleton]]: new levels can be added to the levels that can be influenced by the level from which the reaction is made;
+++?*[<span class="exbigbtn ">Reaction to regular influences full example</span>]
{{exsection{
[>img[images/simulationModel/lowLevel/reactionTree.png]]
This example illustrates the reaction to regular influences in the context of a wildlife simulation. In this simulation, the ''Savannah'' level defines a grid topology where ''Lion'' and ''Gazelle'' agents can ''move'' towards a designated location by 1 distance unit. In addition, a ''Lion'' agent can ''eat'' a ''Gazelle'', which removes the ''Gazelle'' from the simulation. Finally, the environment triggers the ''aging'' of each ''Lion'' and ''Gazelle''.

We assume that the ''public local state'' of the environment in the ''Savannah'' level defines the following methods:
*{{methodName{addAgent(ILocalStateOfAgent, double, double)}}} adding an agent at the specified coordinates of the grid;
*{{methodName{removeAgent(ILocalStateOfAgent, double, double)}}} removing an agent located at the specified coordinates of the grid;
*{{methodName{getAgentsLocatedAt(int,int)}}} getting the set of agents located in a 1x1 square of the grid which lower left coordinates are specified as an argument of this method.
This public local state can for instance be implemented as the {{className{[[PLSEnvInSavannahLevel|files/simulationModel/highLevel/PLSEnvInSavannahLevel.java]]}}} class.

We also assume that the public local state of the lions and the gazelle agents define both the following methods, embodied into the {{className{IAgtPLSInSavannah}}} interface extending the {{className{ILocalStateOfAgent4Engine}}} interface:
*{{methodName{getCoordinates()}}} getting their coordinates as an instance of the {{className{Point2D}}} class;
*{{methodName{setCoordinates(double,double)}}} setting these coordinates;
*{{methodName{getAge()}}} getting their age expressed as a {{{long}}} value. It relies on a unit proportional to time stamp identifiers;
*{{methodName{setAge(long)}}} setting their age in milliseconds as a {{{long}}} value;
{{clearright{}}}
Finally, we assume that the following influences are defined:
*A {{className{[[RISavannahGrowOlder|files/simulationModel/lowLevel/RISavannahGrowOlder.java]]}}} influence defining the following methods:
**{{methodName{getAgent( )}}} returning the set of agents that have to grow older;
*A {{className{[[RISavannahEat|files/simulationModel/lowLevel/RISavannahEat.java]]}}} influence defining the following methods:
**{{methodName{getPredator()}}} returning the predator wishing to eat a prey;
**{{methodName{getPrey()}}} returning the predator wishing to eat a prey;
*A {{className{[[RISavannahMove|files/simulationModel/lowLevel/RISavannahMove.java]]}}} influence defining the following methods:
**{{methodName{getAgent()}}} returning the agent wishing to move;
**{{methodName{getDesiredX()}}} returning the x coordinate of its desired destination;
**{{methodName{getDesiredY()}}} returning the y coordinate of its desired destination.
In this example, the reaction relies on the following principles:
*The {{className{RISavannahGrowOlder}}} influence causes no collision: we assume that an agent being alive at the beginning of the transitory period has to age;
*The {{className{RISavannahMove}}} influence causes no collision: we assume that a gazelle can move, even if it is targeted by a eat behavior;
*The {{className{RISavannahEat}}} influence causes two types of collision: 
**It collides {{className{RISavannahMove}}} influences: if a gazelle moves, it can get out of reach of the predator. In such a case, it is not eaten;
**It collides {{className{RISavannahEat}}} influences: if the same gazelle is eaten by two predators, only one predator succeeds in eating the prey (the other one does nothing). The succeeding predator is chosen at random;
!Code
If we assume that the agent categories list is defined in the {{className{[[WildlifeAgentCategoriesList|files/simulationModel/highLevel/WildlifeAgentCategoriesList.java]]}}} class, then the code of the ''Savannah'' level can be the following one. Note that the sources of this class are also available in a [[stand alone|files/simulationModel/lowLevel/SavannahLevel2.java]] file:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/lowLevel/SavannahLevel2.java' border='0' ></pre></object></html>{{bigemphasisblock{
Note that the reaction of a level is not necessarily this complex. The complexity here comes from the ''eat'' influence creating collisions between influences.

Note that ''eat'' influences targeting the same gazelle are not necessarily mutually exclusive. Indeed, we can imagine a reaction where two lions eating the same gazelle will share the nutritive properties of the prey rather than having a predator preventing the other from getting any food.
}}}
}}} ===
[>img(37%,)[images/simulationModel/lowLevel/reactionFocusOnRegular.png]]
The model of the reaction of a level in a simulation model is decomposed in two parts:
*A user-defined reaction to a set of ''system influences'';
*A user-defined reaction to a set of ''regular influences''.
The role of the user-defined reaction to the regular influences mainly consists in updating the public and private local state of the agents according to the modifications implied by the metadata of the influences.

@@display:block;width:60%;{{focusemphasisblock{
This step of the methodology consist in defining the operational code of the reaction of each level to a set of regular influences.
}}}@@
{{clearright{}}}
[>img(45%,)[images/simulationModel/lowLevel/levelDesignOutline5.png]]
In the micro-kernel of SIMILAR, the reaction process of a level is modeled by the following methods of the {{className{[[ILevel|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html]]}}} interface:
*{{methodName{makeRegularReaction(...)}}} models the user reaction to the regular influences; {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html#makeRegularReaction(fr.univ_artois.lgi2a.similar.microkernel.SimulationTimeStamp, fr.univ_artois.lgi2a.similar.microkernel.SimulationTimeStamp, fr.univ_artois.lgi2a.similar.microkernel.dynamicstate.ConsistentPublicLocalDynamicState, java.util.Set, fr.univ_artois.lgi2a.similar.microkernel.influences.InfluencesMap)]]}}}
This method has for signature:
{{{
void makeRegularReaction(
   SimulationTimeStamp transitoryTimeMin,
   SimulationTimeStamp transitoryTimeMax,
   ConsistentPublicLocalDynamicState consistentState,
   Set<IInfluence> regularInfluences,
   InfluencesMap remainingInfluences
);
}}}
It defines the following arguments:
*{{argumentName{transitoryTimeMin}}} modeling the lower bound of the transitory period of the level for which this reaction is performed;
*{{argumentName{transitoryTimeMax}}} modeling the upper bound of the transitory period of the level for which this reaction is performed;
*{{argumentName{consistentState}}} modeling the consistent state of the level being progressively updated by the reaction to go from its value at the time {{argumentName{transitoryTimeMin}}} to its value at the time {{argumentName{transitoryTimeMax}}};
*{{argumentName{regularInfluences}}} models the regular influences for which a reaction has to be defined;
*{{argumentName{remainingInfluences}}} models both the set of regular influences persisting in the dynamic state of the level after the reaction, and the system influences that were produced as a side effect of this reaction to regular influences. The side effects of such system influences is applied as soon as possible (either now for the levels computing a reaction, or during the next reaction of the other levels); +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection {
<<tiddler [[InfluencesMap - Documentation]]>>
}}} ===

{{clearright{}}}
<<tiddler [[System influences - Specifications]]>>
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Defining the reaction to system influences}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Reaction]]  |  [[next step >>|SMD - Reaction - To regular influences]]}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Reaction - To system influences - Intro]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Reaction - To system influences - Specifications]]>><html><h1>Writing the reaction to system influences of a level class</h1></html>
<<tiddler [[SMD - Reaction - To system influences - Creation]]>>
{{nextButton{[[Go to the next step >>|SMD - Reaction - To regular influences]]}}}
The implementation of this method consists in:
*Iterating over the system influences provided as an argument;
*Checking the category of the influence; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
All the system influence classes of SIMILAR define a {{{public static final}}} field named {{fieldName{CATEGORY}}} corresponding to the category of the system influence. Therefore, checking the category of the influence consists in comparing the category of the influence to the {{fieldName{CATEGORY}}} field of a system influence class.

The system influence of SIMILAR are currently:
*{{className{[[SystemInfluenceAddAgent|../api/fr/lgi2a/similar/microkernel/influences/system/SystemInfluenceAddAgent.html]]}}}
*{{className{[[SystemInfluenceAddAgentToLevel|../api/fr/lgi2a/similar/microkernel/influences/system/SystemInfluenceAddAgentToLevel.html]]}}}
*{{className{[[SystemInfluenceRemoveAgent|../api/fr/lgi2a/similar/microkernel/influences/system/SystemInfluenceRemoveAgent.html]]}}}
*{{className{[[SystemInfluenceRemoveAgentFromLevel|../api/fr/lgi2a/similar/microkernel/influences/system/SystemInfluenceRemoveAgentFromLevel.html]]}}}
}}} === +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
For instance, retrieving the list of the newly added agents to the levels is made with the following instructions:
{{{
void makeSystemReaction(
	SimulationTimeStamp transitoryTimeMin,
	SimulationTimeStamp transitoryTimeMax,
	ConsistentPublicLocalDynamicState consistentState,
	Collection<IInfluence> systemInfluencesToManage,
	boolean happensBeforeRegularReaction,
	InfluencesMap newInfluencesToProcess
){
	Set<ILocalStateOfAgent> newlyAddedAgents = new LinkedHashSet<ILocalStateOfAgent>();
	for( IInfluence influence : systemInfluencesToManage ){
		if( influence.getCategory( ).equals( SystemInfluenceAddAgentToLevel.CATEGORY ) ){
			// The influence models the addition of an agent to this level.
			SystemInfluenceAddAgentToLevel castedInfluence = 
					(SystemInfluenceAddAgentToLevel) influence;
			newlyAddedAgents.add( castedInfluence.getPublicLocalState( ) );
		}
	}
	// Now "newlyAddedAgents " contains the list of the newly added agents.
}
}}}
}}} ===

*Cast the influence in the appropriate type;
*Get the metadata contained in the influence to build a reaction; +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
For instance, if the environment defines a grid topology, then the addition and removal system influences have to be managed to identify the added/removed agent and its location in the grid and to update the content of the grid.
}}} ===

*Possibly creating influences and adding them to the {{argumentName{newInfluencesToProcess}}} map; +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
For instance, if the addition of an agent from a specific category implies the addition of another agent in the simulation: //e.g.// when a person being haunted by a ghost enters the level, an influence adding the ghost agent to the level has to be created and managed.
}}} ===

During the redaction of the reaction process, the information required by the reaction can become clearer. Therefore, this step will likely lead to the revision of:
*The data from the [[public local state|SMD - Public local states]] of the environment or of the agents;
*The [[regular influences|SMD - Influences skeleton]] produced by the decisions: it can lead either to the addition of new metadata to existing regular influences, or the creation of new regular influences;
*The [[influence relation graph|SMD - Level skeleton]]: new levels can be added to the levels that can be influenced by the level from which the reaction is made;
+++?*[<span class="exbigbtn ">Reaction to system influences full example</span>]
{{exsection{
This example is a continuation of the wildlife simulation described in a [[previous step|SMD - Public local states]] of the methodology. In this simulation, the ''Savannah'' level defines a grid topology where ''Lion'' and ''Gazelle'' agents can move. Therefore, the user-defined reaction to system influences has to make sure that the grid is being updated upon the addition or removal of such agents.

Therefore, we assume that the ''public local state'' of the environment in the ''Savannah'' level defines the following methods:
*{{methodName{addAgent(ILocalStateOfAgent, double, double)}}} adding an agent at the specified coordinates of the grid;
*{{methodName{removeAgent(ILocalStateOfAgent, double, double)}}} removing an agent located at the specified coordinates of the grid;
*{{methodName{getAgentsLocatedAt(int,int)}}} getting the set of agents located in a 1x1 square of the grid which lower left coordinates are specified as an argument of this method.
This public local state can for instance be implemented as the {{className{[[PLSEnvInSavannahLevel|files/simulationModel/highLevel/PLSEnvInSavannahLevel.java]]}}} class.

We also assume that the following public local states are defined:
*Lion agents define the {{className{AgtLionPLSInSavannah}}} public local state in the ''Savannah'' level;
*Gazelle agents define the {{className{AgtGazellePLSInSavannah}}} public local state in the ''Savannah'' level;
*Both of these states define a method {{methodName{getCoordinates()}}} getting their coordinates as an instance of the {{className{Point2D}}} class.
!Code
If we assume that the agent categories list is defined in the {{className{[[WildlifeAgentCategoriesList|files/simulationModel/highLevel/WildlifeAgentCategoriesList.java]]}}} class, then the code of the ''Savannah'' level can be the following one. Note that the sources of this class are also available in a [[stand alone|files/simulationModel/lowLevel/SavannahLevel.java]] file:
<html><pre><object width='100%' height="500" type='text/plain' data='files/simulationModel/lowLevel/SavannahLevel.java' border='0' ></pre></object></html>{{bigemphasisblock{
Note that even if the level is implemented as a sub-class of {{className{[[AbstractLevel|../api/fr/lgi2a/similar/microkernel/libs/abstractimpl/AbstractLevel.html]]}}} in this example, the code of the reaction method remains the same with an implementation based only on the {{className{[[ILevel|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html]]}}} interface.

Moreover, to simplify our example, we kept the public local state of gazelle and lions independent. Ideally, they should have extended a common interface {{className{AgtPLSInSavannah}}} extending the interface {{className{ILocalStateOfAgent}}} and defining the signature of the method accessing their coordinates.
}}}
}}} ===
[>img(37%,)[images/simulationModel/lowLevel/reactionFocusOnSystem.png]]
The model of the reaction of a level in a simulation model is decomposed in two parts:
*A user-defined reaction to a set of ''system influences'';
*A user-defined reaction to a set of ''regular influences''.
The role of the user-defined reaction consists mainly in updating the topology of the environment when agents are added/removed.

@@display:block;width:60%;{{focusemphasisblock{
This step of the methodology consist in defining the operational code of the reaction of each level to a set of system influences.
}}}@@
{{clearright{}}}
[>img(45%,)[images/simulationModel/lowLevel/levelDesignOutline4.png]]
In the micro-kernel of SIMILAR, the reaction process of a level is modeled by the following methods of the {{className{[[ILevel|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html]]}}} interface:
*{{methodName{makeSystemReaction(...)}}} models the user reaction to the system influences;  {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html#makeSystemReaction(fr.univ_artois.lgi2a.similar.microkernel.SimulationTimeStamp, fr.univ_artois.lgi2a.similar.microkernel.SimulationTimeStamp, fr.univ_artois.lgi2a.similar.microkernel.dynamicstate.ConsistentPublicLocalDynamicState, java.util.Collection, boolean, fr.univ_artois.lgi2a.similar.microkernel.influences.InfluencesMap)]]}}}
This method has for signature:
{{{
void makeSystemReaction(
   SimulationTimeStamp transitoryTimeMin,
   SimulationTimeStamp transitoryTimeMax,
   ConsistentPublicLocalDynamicState consistentState,
   Collection<IInfluence> systemInfluencesToManage,
   boolean happensBeforeRegularReaction,
   InfluencesMap newInfluencesToProcess
)
}}}
It defines the following arguments:
*{{argumentName{transitoryTimeMin}}} modeling the lower bound of the transitory period of the level for which this reaction is performed;
*{{argumentName{transitoryTimeMax}}} modeling the upper bound of the transitory period of the level for which this reaction is performed;
*{{argumentName{consistentState}}} modeling the consistent state of the level being progressively updated by the reaction to go from its value at the time {{argumentName{transitoryTimeMin}}} to its value at the time {{argumentName{transitoryTimeMax}}}. Note that this state already includes the side effects of the system influences listed in the {{argumentName{systemInfluencesToManage}}} argument;
*{{argumentName{systemInfluencesToManage}}} models the system influences that were managed by the engine and that might require specific management by the user;
*{{argumentName{happensBeforeRegularReaction}}} determines to which call this method corresponds to: {{{true}}} if it corresponds to the first one (upper one on the image) and {{{false}}} if it corresponds to the second one (lower one on the image);
*{{argumentName{newInfluencesToProcess}}} models the set where the user has to put the influences produced as a side effect of this reaction. +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection {
<<tiddler [[InfluencesMap - Documentation]]>>
}}} ===

{{clearright{}}}
<<tiddler [[System influences - Specifications]]>>
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Execution class of a simulation}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Initial state]]  |  next step >>}}}
<html><hr class="topSep"/></html>
<<tiddler [[SMD - Running the simulation - Intro]]>><html><h1>
Structure of the simulation execution procedure</h1></html>
<<tiddler [[SMD - Running the simulation - Structure]]>><html><h1>
Creating the simulation execution class</h1></html>
<<tiddler [[SMD - Running the simulation - Creation]]>>
{{nextButton{[[Run simulations with the command line|Simulation execution]]}}}
The generated class has to:
*Be located in the ''initializations'' package of the tree hierarchy;
*Provide a javadoc ''documentation'' to that class. This documentation has to describe precisely the purpose of the simulation and how to read its results. This point is of utmost importance when different main classes are defined for a simulation.
+++?[<span class="exbigbtn">Simulation main class example</span>]
{{exsection{
In this example, we describe the simulation execution procedure of a bubble chamber simulation where:
*The simulation is run with the default engine of SIMILAR ({{className{[[EngineMonothreadedDefaultdisambiguation|../api/fr/lgi2a/similar/microkernel/libs/engines/EngineMonothreadedDefaultdisambiguation.html]]}}} from common libs)
*The following observation probes are used:
**A generic probe printing caught exceptions on the standard error stream ({{className{[[ProbeExceptionPrinter|../api/fr/lgi2a/similar/microkernel/libs/probes/ProbeExceptionPrinter.html]]}}} from common libs)
**A generic probe printing the execution trace of the simulation ({{className{[[ProbeExecutionTracker|../api/fr/lgi2a/similar/microkernel/libs/probes/ProbeExecutionTracker.html]]}}} from common libs)
**A probe printing the location of each particle agent over time ({{className{ProbePrintingParticleLocationOverTime}}} class);
*The following agent factories are used:
**The {{className{AgtBubbleFactory}}} agent factory, generating ''bubble'' agents;
**The {{className{AgtCannonFactory}}} agent factory, generating ''particle cannon'' agents;
**The {{className{AgtParticleFactory}}} agent factory, generating ''particle'' agents;
*The {{className{JavaRandomBasedValuesGenerator}}} class is used a random number generation strategy. This strategy takes a number modeling its seed as a constructor argument;
*The simulation parameters are defined as a {{className{BubbleChamberParameters}}} class containing:
**A {{fieldName{initialTime}}} field defining the initial time of the simulation;
**A {{fieldName{finalTime}}} field defining the final time of the simulation;
**A {{fieldName{cannonPower}}} field defining the power of a cannon and therefore the initial speed of the particles it fires;
**A {{fieldName{randomSeed}}} field defining the seed of the random generator being used;
*The simulation model initialization procedure is implemented as the {{className{BubbleChamberSimulation}}}, using a simulation parameters as a constructor argument;
In this example, we define a custom value only for the {{fieldName{initialTime}}}, the {{fieldName{finalTime}}} and {{fieldName{randomSeed}}} parameters. The {{fieldName{cannonPower}}} parameter will use its default value.
!Code
The corresponding main class of the simulation is implemented with the following code. The sources of this class are also available as a [[stand alone|files/simulationModel/finalStep/BubbleChamberMain.java]] file.
<html><pre><object width='100%' height='350px' type='text/plain' data='files/simulationModel/finalStep/BubbleChamberMain.java' border='0' ></pre></object></html>
}}} ===
The final step in the design of a simulation model consists in declaring that model in the context of a ''simulation execution procedure''. This procedure gathers to various parts of a SIMILAR simulation and puts them together as a runnable program. 

{{focusemphasisblock{
This step of the simulation focuses on the creation of the class containing the execution procedure of the simulation.
}}}
The main steps of this procedure are:
#Create an instance of the simulation parameters class, and set the value of its content;
#Initialize the [[random number generator|SMD - Tools preparation - Random]], using a seed declared in the simulation parameters; +++?[<span class="implsmallbtn">Implementation</span>] 
{{implsection{
This part is achied in two steps:
#Create the random numbers generation strategy, and initialize its seed with the simulation parameters;
#Set the generation strategy being used in the random number generation factory, //i.e.// call:
{{{
RandomValueFactory.setStrategy( theStrategyImUsing );
}}}
}}} ===

#Bind the simulation parameters with the [[agent factories|SMD - Agent creation]] being used in the simulation; +++?[<span class="implsmallbtn">Implementation</span>] 
{{implsection{
This step consists in setting the value of the static {{fieldName{simulationParameter}}} field of each factory.
}}} ===

#Create an instance of the [[simulation model initialization profile|SMD - Initial state]] that will be used to run the simulation;
#Create an instance of the ''simulation engine'' that will run the simulation; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The simulation engine used in a simulation can be:
*A ''generic'' engine located in the common libs of the micro-kernel of SIMILAR; {{morelink{[[More|./commonLibs/index.html#SimulationEngines]]}}}
*A ''custom'' engine written by the used using the engine design methodology {{morelink{[[More|Simulation engines]]}}}
}}} ===

#Create the instance of each ''observation probe'' used in the simulation; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection{
The observation probes used in a simulation can be:
*''Generic'' and located in the common libs of the micro-kernel of SIMILAR; {{morelink{[[More|./commonLibs/index.html#Probes]]}}}
*''Simulation dependent'' and designed using the probes design methodology. {{morelink{[[More|Observation probes]]}}}
}}} ===

#Bind the probes to the simulation engine; +++?[<span class="docsmallbtn">Documentation</span>] 
{{docsection{
The binding of probes with a simulation engine is achieved using the {{methodName{[[addProbe(...)|../api/fr/lgi2a/similar/microkernel/ISimulationEngine.html#addProbe(java.lang.String, fr.univ_artois.lgi2a.similar.microkernel.IProbe)]]}}} method of the {{className{[[ISimulationEngine|../api/fr/lgi2a/similar/microkernel/ISimulationEngine.html]]}}} class. This method has the following signature:
{{{
public void addProbe(
	String identifier, 
	IProbe probe 
);
}}}
This method declares the following arguments:
*{{argumentName{identifier}}} modeling a readable identifier of the probe. This parameter is usefull if two instances of the same probe class but with different parameters are used in the same engine. +++?[<span class="exsmallbtn">Example</span>]
{{exsection{
A simulation tracking the execution trace of the simulation on both the standard output and in a file will use two different instances of the {{className{ProbeExecutionTracker}}} probe from the common libs:
*One instance using the {{{System.out}}} print stream;
*One instance using a print stream to a file.
}}} ===

*{{argumentName{probe}}} modeling the probe being binded with the engine. After the call to this method, whenever the engine reaches a point where probes have to be notified, this probe will receive the notification;
}}} ===  +++?[<span class="exsmallbtn">Example</span>] 
{{exsection{
A simulation tracking the execution trace of the simulation on both the standard output and in a file will use two different instances of the {{className{ProbeExecutionTracker}}} probe from the common libs:
*One instance using the {{{System.out}}} print stream;
*One instance using a print stream to a file.
The creation and binding of these probes to the engine is made with the following code:
{{{
ISimulationEngine engine = ...;
ProbeExecutionTracker sysOutTracker = new ProbeExecutionTracker(
	System.out
);
engine.addProbe(
	"Standard output simulation trace tracker",
	sysOutTracker 
);
ProbeExecutionTracker fileTracker = new ProbeExecutionTracker(
	new PrintStream( new File( "simulationLog.txt" ) )
);
engine.addProbe(
	"File simulation trace tracker",
	fileTracker
);
}}}
}}} ===

#Run a simulation with the engine using the simulation model initialization profile. +++?[<span class="docsmallbtn">Documentation</span>] 
{{docsection{
The execution of a simulation is achieved using the {{methodName{[[runNewSimulation(...)|../api/fr/lgi2a/similar/microkernel/ISimulationEngine.html#runNewSimulation(fr.univ_artois.lgi2a.similar.microkernel.ISimulationModel)]]}}} method from the {{className{[[ISimulationEngine|../api/fr/lgi2a/similar/microkernel/ISimulationEngine.html]]}}} interface. This method has the following signature:
{{{
public void runNewSimulation( 
	ISimulationModel simulationModel 
);
}}}
This method defines the following argument:
*{{argumentName{simulationModel }}} modeling the simulation model initialization profile being used to initialize the dynamic state of the simulation.
}}} ===

{{bigemphasisblock{
Note that the execution of a simulation will almost never directly throw an exception, even if an error is met. The exceptions are often intercepted by the simulation engine and forwarded to the probes. Therefore, the observation or errors requires the use of probes.

The {{className{[[ProbeExceptionPrinter|../api/fr/lgi2a/similar/microkernel/libs/probes/ProbeExceptionPrinter.html]]}}} probe from the common libs was defined for this purpose.
}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creation of the time model}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Agents skeleton]]  |  [[next step >>|SMD - Public local states]]}}}
<html><hr class="topSep"/></html>
Once the levels are identified, we have to determine how time moves in each level. This step is fundamental, since it conditions the execution of the behavior of the agents and the environment.

{{focusemphasisblock{
This step focuses on the specification of the time model of each level, inside the skeleton class of each level.
}}}
Managing explicitly the time in a simulation is not necessarily an easy task. Indeed, a simulation often relies on the notion of "time step" whereas simulated phenomena rely on notions like hours/minutes/seconds, seasons, years, etc. Therefore, before going for the kill, we remind the users about the ''time model'' related terminology used in SIMILAR.

{{linkbigbtn center{<html><a target="_blank" href="../README.html#[[Structure - Simulation model - Time model - Time stamps model]]">Read more about the time model</a></html>}}}
!Structure of a time model in SIMILAR
<<tiddler [[SMD - Time model - Structure]]>>
!Specifications and implementation instructions
<<tiddler [[SMD - Time model - Implementation]]>>
!Time model of a level
<<tiddler [[SMD - Time model - Level]]>>
!Time conversion model
<<tiddler [[SMD - Time model - Conversion]]>>
{{nextButton{[[Go to the next step >>|SMD - Public local states]]}}}
In simulations where the behavior is tightly bound with real time, using time stamps is not precise enough to model the behavior of the agents. For instance, in a road traffic simulation, we have to know the real time ellapsed during a transitory period to determine the distance they moved since the last consistent time.

For that purpose, users might have to define a ''time conversion model'', providing two conversion methods:
*A method converting a real time into a time stamp;
*A method converting a time stamp into real time.
Note that since the time stamps are an approximation of real time, the conversion model has to provide heuristics to convert real time into time stamps.

+++?[<span class="exbigbtn">Time conversion example</span>]
{{exsection {
This example illustrates a time conversion class, in which the time ellapsing between two consecutive time stamps (//i.e.// time stamps which identifiers differ by one) equals to 5 milliseconds.
In the case where a time is not a multiple of 5 milliseconds, the floor of that value is used.
!Code
{{{
public class ExampleTimeConvertor {

	public static final double UNIT = 0.005;

	public double convert( SimulationTimeStamp time ) {
		long identifier = time.getIdentifier( );
		return identifier * UNIT;
	}

	public SimulationTimeStamp convert( double time ) {
		double dblIdentifier = time / UNIT;
		if( dblIdentifier >= Long.MAX_VALUE ){
			throw new IllegalArgumentException( "Precision exceeded." );
		} else if( dbldentifier <= Long.MIN_VALUE ){
			throw new IllegalArgumentException( "Precision exceeded." );
		} else {
			return (long) Math.floor( dblIdentifier );
		}
	}
}
}}}
}}} ===
In SIMILAR, the notion of time model is reified with the {{className{[[ITimeModel|../api/fr/lgi2a/similar/microkernel/levels/ITimeModel.html]]}}} interface and the {{className{[[SimulationTimeStamp|../api/fr/lgi2a/similar/microkernel/SimulationTimeStamp.html]]}}} class. The main role of the modeler is to provide an implementation to the methods defined in the {{className{ITimeModel}}} interface.
[img(47%,)[images/simulationModel/highLevel/timeStampOutline.png]] [>img(47%,)[images/simulationModel/highLevel/timeModelDesignOutline.png]]
{{clear{}}}
In SIMILAR, ''time models'' are instances of the {{className{[[ITimeModel|../api/fr/lgi2a/similar/microkernel/levels/ITimeModel.html]]}}} interface. They are characterized by the following methods:
*{{methodName{getNextTime(...)}}} computes the ''successor'' of a time stamp;  {{doclink{[[Method API|../api/fr/lgi2a/similar/microkernel/levels/ITimeModel.html#getNextTime(fr.univ_artois.lgi2a.similar.microkernel.SimulationTimeStamp)]]}}} +++?*[<span class="implsmallbtn">Implementation</span>]
{{implsection{
For simulation consistency reasons, the {{methodName{getNextTime(...)}}} method has to be deterministic: calling twice this method with the same parameter has to produce the same output.

This method consists in determining the identifier of the time stamp succeeding the time stamp in the parameters. Once it is done, then the method returns a new time stamp having that identifier.
}}} === +++?*[<span class="exsmallbtn">Example</span>]
{{exsection{
In this example, the time model uses a period of 5 units.
!Code
{{{
public Period5TimeModel implements ITimeModel {
	
	private final long period = 5;

	@Override
	public SimulationTimeStamp getNextTime( 
		SimulationTimeStamp currentTime 
	) {
		return new SimulationTimeStamp( currentTime, this.period );
	}
}
}}}
}}} ===
[>img(50%,)[images/simulationModel/highLevel/levelDesignOutline3.png]]
In SIMILAR, each level has to define a ''time model''. For this purpose, the {{className{[[ILevel|../api/fr/lgi2a/similar/microkernel/levels/ILevel.html]]}}} interface extends the {{className{[[ITimeModel|../api/fr/lgi2a/similar/microkernel/levels/ITimeModel.html]]}}} interface. Therefore, each instance of a level has to define the successor computation method, using the instructions provided in the previous section.

This step of the design methodology consists in providing the operational code of the {{methodName{getNextTime(...)}}} method of all the levels that were identified so far.

A second part to this step related to the time model is necessary for some simulation. This case is described in the next section.
{{clear{}}}
+++?[<span class="exbigbtn">Level implementation example</span>]
{{exsection {
This section illustrates the specification of the time model in the context of the definition of a level declared into the {{className{CityLevel}}} class.

In this example, the time model uses a period of 5 units.
!Code
{{{
public CityLevel implements ILevel {

	[...]
	
	private final long period = 5;

	[...]

	@Override
	public SimulationTimeStamp getNextTime( 
		SimulationTimeStamp currentTime 
	) {
		long currentId = currentTime.getIdentifier( );
		return new SimulationTimeStamp( currentId + this.period );
	}

	[...]

}
}}}
}}} ===
[>img(50%,)[images/simulationModel/highLevel/timeModelStructure.png]]
To preserve the freedom of defining custom time models, SIMILAR does not impose a specific method to identify the time stamps: a time model is the sum of the following elements^^''1''^^:
*An initial ''time stamp'';
*A method identifying the successor of a ''time stamp'';
{{clear{}}}
\(_{\underline{1:}\text{ See the reference papers on SIMILAR and IRM4MLS for the full description of these elements.}}\)
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Creating the tool classes}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Package tree]]  |  [[next step >>|SMD - Tools preparation - Random]]}}}
<html><hr class="topSep"/></html>
A second preliminary step is necessary before writing the simulation model: the reification of the ''random values generator'' and of the ''parameters of the simulation''.

This step is fundamental in many regards. Yet it is often underestimated and disseminated in the code of the simulation. Their reification as concrete classes is necessary to replace easily the random values generation heuristic or the parameters used within the simulation.
{{nextButton{[[Go to the next step >>|SMD - Tools preparation - Random]]}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Managing the simulation parameters}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Tools preparation - Random]]  |  [[next step >>|SMD - High level specifications]]}}}
<html><hr class="topSep"/></html>
To facilitate the definition of various experiments, the parameters used in the simulation shouldn't be disseminated into the various classes of the project. Otherwise, the modification of the value of a parameter becomes really difficult, since we first have to find where the parameter was declared.

A possible solution to this problem is to define one parameter class (or many classes divided by themes) shared among all the classes of the simulation.
!Structure of the parameters class
The parameters class is a regular java class containing the declaration of a field per simulation parameter. This field:
*Must have a getter and a setter in the class, or has to be public;
*Must have a default value set in the constructor;
These classes are usually put in the ''"model"'' directory of the package hierarchy.

+++?[<span class="exbigbtn">Parameters class example</span>]
{{exsection {
We consider in this example a simulation relying on the following parameters:
*''Initial number of agents'' (default value: 350)
*''Agent initial speed'' (default value: 25)

This example is also available in a [[stand alone file|./files/simulationModel/preparation/MyParametersClass.java]]. The parameter class corresponding to this specification is:
!Code
<html><pre><object width='100%' height='350px' type='text/plain' data='files/simulationModel/preparation/MyParametersClass.java' border='0' ></pre></object></html>
}}} ===
!Usage of the parameters class
The parameter classes are used only in the initialization process of the simulation. Since talking about simulation initialization is premature at this step of the methodology, we defer the description of the usage of this class to a [[later step of the methodology|SMD - Initial state]].
{{nextButton{[[Go to the next step >>|SMD - High level specifications]]}}}
<<tiddler [[Design - Simulation model - menu]]>> {{stepMainTitle{Generation of random values}}}
{{guidelinesNavMenu{[[<< previous step|SMD - Tools preparation]]  |  [[next step >>|SMD - Tools preparation - Parameters]]}}}
<html><hr class="topSep"/></html>
The generation of random values is important in simulation since it provides the means to include noise and heterogeneity in a model. Yet, the production of random values cannot be wild: a simulation has to be +++^34em^*@[reproducible]
Using a set of parameters (including the parameters of the random values generator) twice should produce the same outcomes, even if random values generation is involved in the simulation process.
===. Thus users should have control over the way random values are generated.

The first tool used in a simulation is a random number generator. Since we do not want to depend on a specific implementation of the generator, the following classes have to be included in the project:
*The {{className{IRandomValuesGenerator}}} interface, containing the signature of the random value generation methods (usually one per type of value);
*Implementations of the {{className{IRandomValuesGenerator}}} interface, modeling various values generation strategies;
*The {{className{RandomValueFactory}}} class, embedding one value generation strategy. The generation of random value within the simulation has to be made using the static methods defined in that class.
These classes are usually put in the ''"tools"'' directory of the package hierarchy.
!!Signature of the random values generation methods
There is no specific constraint on the declaration of this interface. It can define as much methods as necessary.

+++?[<span class="exbigbtn">Signature example</span>]
{{exsection {
This example illustrates the implementation of the {{className{IRandomValuesGenerator}}} interface where two generation methods are defined (one for {{{double}}} values, the other for {{{int}}} values).

This example is also available in a [[stand alone file|./files/simulationModel/preparation/IRandomValuesGenerator.java]].
!Code
<html><pre><object width='100%' height='350px' type='text/plain' data='files/simulationModel/preparation/IRandomValuesGenerator.java' border='0' ></pre></object></html>
}}}===
!!Random value generation heuristic
The heuristic used to generate random values has to be written by the user. Its implementation has mainly two constraints:
*If the heuristic requires initialization parameters, these parameters have to be explicitly mentionned to the users;
*Two instances of the same heuristic with the same initialization parameters should produce the same +++^34em^*@[results]
Using the same sequence of method calls in the heuristic should produce the same sequence of values.
===;

+++?[<span class="exbigbtn">Heuristic example</span>]
{{exsection {
This example illustrates the instanciation of the {{className{IRandomValuesGenerator}}} interface described in the previous example. This instanciation is based on the {{className{java.util.Random}}} class\(^1\).

This example is also available in a [[stand alone file|./files/simulationModel/preparation/JavaRandomBasedValuesGenerator.java]].
!Code
<html><pre><object width='100%' height='350px' type='text/plain' data='files/simulationModel/preparation/JavaRandomBasedValuesGenerator.java' border='0' ></pre></object></html>\(_{\underline{1:} \text{This implementation is made for illustration purposes: we are fully aware that using this class is a bad idea since it relies on inappropriate random numbers generation metrics.}}\)
}}}===

!!Random values factory
The two previous classes can be used to specify a random value generation heuristic. To facilitate their use in the simulation, a factory class embeds the strategy currently used in the simulation. 

+++?[<span class="exbigbtn">Factory example</span>]
{{exsection {
This example illustrates the implementation of the {{className{RandomValueFactory}}} random number values factory used in the whole simulation. This implementation uses the java-based generation strategy defined in the examples above.

This example is also available in a [[stand alone file|./files/simulationModel/preparation/RandomValueFactory.java]].
!Code
<html><pre><object width='100%' height='350px' type='text/plain' data='files/simulationModel/preparation/RandomValueFactory.java' border='0' ></pre></object></html>
}}}===

__//Note://__ If the strategy used in the simulation has to be different from the default one, then the first instruction of the simulation should be the setting of that strategy in the factory.
!!Using random values in the simulation
Once the three classes are defined, using random values in the simulation consists in calling the appropriate method of the object embedded in the random value generation factory.

+++?[<span class="exbigbtn">Factory usage example</span>]
{{exsection {
A random double value in the range [0;1[ is obtained by performing the following method call:
!Code
{{{
RandomValueFactory.getStrategy( ).randomDouble( );
}}}
}}}===

__//Note://__ These operations assume that the random value factory exists and is already initialized.
{{nextButton{[[Go to the next step >>|SMD - Tools preparation - Parameters]]}}}
/***
|''Name''|SimpleSearchPlugin|
|''Description''|displays search results as a simple list of matching tiddlers|
|''Authors''|FND|
|''Version''|0.4.1|
|''Status''|stable|
|''Source''|http://devpad.tiddlyspot.com/#SimpleSearchPlugin|
|''CodeRepository''|http://svn.tiddlywiki.org/Trunk/contributors/FND/plugins/SimpleSearchPlugin.js|
|''License''|[[Creative Commons Attribution-ShareAlike 3.0 License|http://creativecommons.org/licenses/by-sa/3.0/]]|
|''Keywords''|search|
!Revision History
!!v0.2.0 (2008-08-18)
* initial release
!!v0.3.0 (2008-08-19)
* added Open All button (renders Classic Search option obsolete)
* sorting by relevance (title matches before content matches)
!!v0.4.0 (2008-08-26)
* added tag matching
!To Do
* tag matching optional
* animations for container creation and removal
* when clicking on search results, do not scroll to the respective tiddler (optional)
* use template for search results
!Code
***/
//{{{
if(!version.extensions.SimpleSearchPlugin) { //# ensure that the plugin is only installed once
version.extensions.SimpleSearchPlugin = { installed: true };

if(!config.extensions) { config.extensions = {}; }

config.extensions.SimpleSearchPlugin = {
	heading: "Search Results",
	containerId: "searchResults",
	btnCloseLabel: "close",
	btnCloseTooltip: "dismiss search results",
	btnCloseId: "search_close",
	btnOpenLabel: "Open all",
	btnOpenTooltip: "open all search results",
	btnOpenId: "search_open",

	displayResults: function(matches, query) {
		story.refreshAllTiddlers(true); // update highlighting within story tiddlers
		var el = document.getElementById(this.containerId);
		query = '"""' + query + '"""'; // prevent WikiLinks
		if(el) {
			removeChildren(el);
		} else { //# fallback: use displayArea as parent
			var container = document.getElementById("displayArea");
			el = document.createElement("div");
			el.id = this.containerId;
			el = container.insertBefore(el, container.firstChild);
		}
		var msg = "!" + this.heading + "\n";
		if(matches.length > 0) {
			msg += "''" + config.macros.search.successMsg.format([matches.length.toString(), query]) + ":''\n";
			this.results = [];
			for(var i = 0 ; i < matches.length; i++) {
				this.results.push(matches[i].title);
				msg += "* [[" + matches[i].title + "]]\n";
			}
		} else {
			msg += "''" + config.macros.search.failureMsg.format([query]) + "''"; // XXX: do not use bold here!?
		}
		createTiddlyButton(el, this.btnCloseLabel, this.btnCloseTooltip, config.extensions.SimpleSearchPlugin.closeResults, "button", this.btnCloseId);
		wikify(msg, el);
		if(matches.length > 0) { // XXX: redundant!?
			createTiddlyButton(el, this.btnOpenLabel, this.btnOpenTooltip, config.extensions.SimpleSearchPlugin.openAll, "button", this.btnOpenId);
		}
	},

	closeResults: function() {
		var el = document.getElementById(config.extensions.SimpleSearchPlugin.containerId);
		removeNode(el);
		config.extensions.SimpleSearchPlugin.results = null;
		highlightHack = null;
	},

	openAll: function(ev) {
		story.displayTiddlers(null, config.extensions.SimpleSearchPlugin.results);
		return false;
	}
};

config.shadowTiddlers.StyleSheetSimpleSearch = "/*{{{*/\n" +
	"#" + config.extensions.SimpleSearchPlugin.containerId + " {\n" +
	"\toverflow: auto;\n" +
	"\tpadding: 5px 1em 10px;\n" +
	"\tbackground-color: [[ColorPalette::TertiaryPale]];\n" +
	"}\n\n" +
	"#" + config.extensions.SimpleSearchPlugin.containerId + " h1 {\n" +
	"\tmargin-top: 0;\n" +
	"\tborder: none;\n" +
	"}\n\n" +
	"#" + config.extensions.SimpleSearchPlugin.containerId + " ul {\n" +
	"\tmargin: 0.5em;\n" +
	"\tpadding-left: 1.5em;\n" +
	"}\n\n" +
	"#" + config.extensions.SimpleSearchPlugin.containerId + " .button {\n" +
	"\tdisplay: block;\n" +
	"\tborder-color: [[ColorPalette::TertiaryDark]];\n" +
	"\tpadding: 5px;\n" +
	"\tbackground-color: [[ColorPalette::TertiaryLight]];\n" +
	"}\n\n" +
	"#" + config.extensions.SimpleSearchPlugin.containerId + " .button:hover {\n" +
	"\tborder-color: [[ColorPalette::SecondaryMid]];\n" +
	"\tbackground-color: [[ColorPalette::SecondaryLight]];\n" +
	"}\n\n" +
	"#" + config.extensions.SimpleSearchPlugin.btnCloseId + " {\n" +
	"\tfloat: right;\n" +
	"\tmargin: -5px -1em 5px 5px;\n" +
	"}\n\n" +
	"#" + config.extensions.SimpleSearchPlugin.btnOpenId + " {\n" +
	"\tfloat: left;\n" +
	"\tmargin-top: 5px;\n" +
	"}\n" +
	"/*}}}*/";
store.addNotification("StyleSheetSimpleSearch", refreshStyles);

// override Story.search()
Story.prototype.search = function(text, useCaseSensitive, useRegExp) {
	highlightHack = new RegExp(useRegExp ? text : text.escapeRegExp(), useCaseSensitive ? "mg" : "img");
	var matches = store.search(highlightHack, null, "excludeSearch");
	var q = useRegExp ? "/" : "'";
	config.extensions.SimpleSearchPlugin.displayResults(matches, q + text + q);
};

// override TiddlyWiki.search() to sort by relevance
TiddlyWiki.prototype.search = function(searchRegExp, sortField, excludeTag, match) {
	var candidates = this.reverseLookup("tags", excludeTag, !!match);
	var primary = [];
	var secondary = [];
	var tertiary = [];
	for(var t = 0; t < candidates.length; t++) {
		if(candidates[t].title.search(searchRegExp) != -1) {
			primary.push(candidates[t]);
		} else if(candidates[t].tags.join(" ").search(searchRegExp) != -1) {
			secondary.push(candidates[t]);
		} else if(candidates[t].text.search(searchRegExp) != -1) {
			tertiary.push(candidates[t]);
		}
	}
	var results = primary.concat(secondary).concat(tertiary);
	if(sortField) {
		results.sort(function(a, b) {
			return a[sortField] < b[sortField] ? -1 : (a[sortField] == b[sortField] ? 0 : +1);
		});
	}
	return results;
};

} //# end of "install only once"
//}}}
{{stepMainTitle{Creating simulation engines for SIMILAR}}}

<html><hr class="topSep"/></html>
{{center{[img(98%,)[images/workInProgress.png]]}}}
{{stepMainTitle{Runnnig a simulation with SIMILAR}}}

<html><hr class="topSep"/></html>
<<tiddler [[Simulation execution - Intro]]>><html>
<h1>Requirements</h1></html>
<<tiddler [[Simulation execution - Requirements]]>><html>
<h1>Compiling and running simulations</h1></html>
<<tiddler [[Simulation execution - Compile and run]]>>
One of the best approaches to perform simulation is to use building tools like ''Maven'' or ''Ant''. Since maven has a steep learning curve, we only describe here how to use ant.

{{bigemphasisblock{
We assume that apache ant is already installed on the machine, and that the path to the ant binary is added to the PATH environment variable.
}}}
[>img[images/execution/executionTreeExample_ant.png]]
The main task in ant consist in defining the ''build script'' that will run the simulation. Such a script usually takes the form of a "{{{build.xml}}}" file located at the root of the directory where the simulation is defined.

Assuming that the SIMILAR binaries are located in a "{{{/home/binaries/similar/}}}" directory, then the image provides an illustration of what the tree hierarchy should look like, and where the ''build.xml'' file should be.
{{clearright{}}}
The build can be written as the following file. Note that this file is also available as a [[stand alone file|files/execution/build.xml]].
<html><pre><object width='100%' height='350px' type='text/plain' data='files/execution/build.txt' border='0' ></pre></object></html>
!Compilation and execution commands
Using this script, the simulation is performed by running one of the following commands.

__Compiling the simulation:__
{{{
ant compile
}}}
__Running the simulation without compiling:__
{{{
ant run
}}}
__Compiling and then running the simulation:__
{{{
ant all
}}}
The latter command will produce the following output in the command shell:
{{{
/home/me/projects/mysimulation>ant all
Buildfile: /home/me/projects/mysimulation/build.xml

clean:

compile:
    [javac] Compiling 2 source files to /home/me/projects/mysimulation/bin

run:
     [java] Running the simulation...
     [java] Simulation done !

all:

BUILD SUCCESSFUL
Total time: 1 second

/home/me/projects/mysimulation>
}}}
{{clearright{}}}
Using the command line, the simulation is compiled using a ''javac'' like command and is performed using the ''java'' command.

{{bigemphasisblock{
We assume that a JavaSE JDK or SDK is already installed on the machine, and than the path to the java binaries is added to the PATH environment variable.
}}}<html>
<h1>Compilation</h1></html>
The compilation of the simulation is made using the following command line:
{{{
/home/me/projects/mysimulation>
javac -d target/bin -classpath "/home/binaries/similar/similarLib/similar-distribution-0.2.1.jar" ALLJAVACLASSES
}}}
In this command, ALLJAVACLASSES is a space separated list of all the java classes that have to be compiled. In some environments, like Linux Bash, it is possible to use wildcards to simplify the command:
{{{
/home/me/projects/mysimulation>
shopt -s globstar
/home/me/projects/mysimulation>
javac -d target/bin -classpath "/home/binaries/similar/similarLib/similar-distribution-0.2.1.jar" /home/me/projects/mysimulation/src/main/java/**/*.java
}}}
!Execution
The execusion of the simulation is made using the following command line:
{{{
/home/me/projects/mysimulation>
java -cp "/home/binaries/similar/similarLib/similar-distribution-0.2.1.jar:target/bin" fr.univ_artois.lgi2a.similar.custom.mysimulation.SimulationMain
}}}
Various approaches can be used to compile and run java classes. In this section, we do not intend to list them all. Instead, we present two kinds of approaches:
*A ''pure command line approach'', where the user has to specify everything; +++?[<span class="implsmallbtn">More</span>]
{{implsection{
<<tiddler [[Simulation execution - Command line]]>>
}}} ===

*A ''script based approach'', where the user has to specify only the path to directories of the project and the name of the main class of the simulation; +++?[<span class="implsmallbtn">More</span>]
{{implsection{
<<tiddler [[Simulation execution - Ant]]>>
}}} ===
{{focusemphasisblock{
This part of the documentation is dedicated to the execution of an existing simulation designed with SIMILAR.
}}}
To run simulations with SIMILAR, the various elements have to be previously defined. These elements can either be designed by the user, or come from existing classes of the [[common libraries|./commonLibs/index.html]] of SIMILAR:
*A ''simulation model'', describing the initial state and the mechanics of the simulation; {{morelink{[[How to create|Simulation models]]}}}
*''Observation probes'', describing how to retrieve the results of the simulation; {{morelink{[[How to create|Observation probes]]}}} {{morelink{[[Use libraries|./commonLibs/index.html#Probes]]}}}
*A ''simulation engine'' defining the java algorithms used in the simulation; {{morelink{[[How to create|Observation probes]]}}} {{morelink{[[Use libraries|./commonLibs/index.html#SimulationEngines]]}}}
Assuming that all these items are whether defined in the source directory of the simulation or within the libraries, then running a simulation consists in:
#Compiling the sources of the simulation, using a //''javac''// like command;
#Running the main class of the simulation, using the //''java''// command.
[>img[images/execution/similarBinariesTree.png]]
@@display:block;width:60%;{{bigemphasisblock{
The instructions described in this part of the documentation assumes that the user did not change the directory tree of the SIMILAR binaries nor the files it contains (see image).
}}}@@

For both compilation and execution operations, the {{{javac}}} and {{{java}}} command lines have to include the binaries of SIMILAR within their classpath. To facilitate the work of designers, only the jar file whose name starts with {{{similar-distribution-}}} (on the image {{{similar-distribution-0.2.1.jar}}}) has to be mentionned in the classpath. This jar links automatically all the binaries of SIMILAR.
[<img[images/execution/executionTreeExample.png]]

In this section, we illustrate how to compile and to run a simulation on an example assuming that the simulation has the following properties. These properties are summed up in the image displayed to the left:
*The binaries of SIMILAR are located in a "{{{/home/binaries/similar/}}}" directory;
*The simulation is declared in the "{{{/home/me/projects/mysimulation/}}}" directory;
*The sources of the simulation are located in the {{{src/main/java/}}} directory of the simulation directory;
*The main class of the simulation is the {{className{SimulationMain}}} class from the {{packageName{fr.univ_artois.lgi2a.similar.custom.mysimulation}}} package.
Note that the binaries of similar or the directory where the simulation is declared can be placed in any other directory. In such cases, pay attention to replace the corresponding directory name in the examples provided below.
{{clear{}}}
<<tiddler [[Design - Simulation model - menu]]>>{{stepMainTitle{Simulation model design}}}
{{guidelinesNavMenu{&lt;&lt; previous step | [[next step >>|SMD - Preparation]]}}}
<html><hr class="topSep"/></html>
{{focusemphasisblock{
This part of the documentation is dedicated to the design and the implementation of SIMILAR simulation models using the micro-kernel only. At the same time, it describes best practices facilitating the organization of the implementation of the simulation. 
}}}
Note that the guidelines provided here are not absolute rules. They only make the design of simulations either easier, or more robust to model revisions.
!Foreword
<<tiddler [[Simulation models - Foreword]]>>
{{nextButton{[[Start the creation of a new model!|SMD - Preparation]]}}}
One of the most important features in complex system design is the ability to reproduce simulations, as long as the simulation paramerters are the same. This point is especially important to assert the correct behavior of the simulation, as well as reproduce implementation errors to identify their origin and correct them.

To ensure this reproducibility, please ensure that:
*The sequence of numbers being generated by the random number generator of the simulation has to be reproducible. This usually means that:
**The ''seed'' that was used to initialize the random number generator has to be known;
**The initialization of the random number generator has to take place right before the beginning of a simulation;
*Particular attention has to be paid on threading:
**Threads should not be used in the general case, since they can arbitrarily change the invocation context of the random number generation methods;
**If threads are needed, each thread should define its own random generation heuristic, with its own seed;
*The iteration order over data structures like {{className{Collection}}} or {{className{Map}}} objects has to be predictible. This implies that:
**The {{className{LinkedHashSet}}} class should be used instead of the {{className{HashSet}}} class to implement the java {{className{Set}}} interface;
**The {{className{LinkedHashMap}}} class should be used instead of the {{className{HashMap}}} class to implement the java {{className{Map}}} interface;
/***
|Name|SinglePageModePlugin|
|Source|http://www.TiddlyTools.com/#SinglePageModePlugin|
|Documentation|http://www.TiddlyTools.com/#SinglePageModePluginInfo|
|Version|2.9.7|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|plugin|
|Description|Show tiddlers one at a time with automatic permalink, or always open tiddlers at top/bottom of page.|
This plugin allows you to configure TiddlyWiki to navigate more like a traditional multipage web site with only one tiddler displayed at a time.
!!!!!Documentation
>see [[SinglePageModePluginInfo]]
!!!!!Configuration
<<<
<<option chkSinglePageMode>> Display one tiddler at a time
><<option chkSinglePagePermalink>> Automatically permalink current tiddler
><<option chkSinglePageKeepFoldedTiddlers>> Don't close tiddlers that are folded
><<option chkSinglePageKeepEditedTiddlers>> Don't close tiddlers that are being edited
<<option chkTopOfPageMode>> Open tiddlers at the top of the page
<<option chkBottomOfPageMode>> Open tiddlers at the bottom of the page
<<option chkSinglePageAutoScroll>> Automatically scroll tiddler into view (if needed)

Notes:
* The "display one tiddler at a time" option can also be //temporarily// set/reset by including a 'paramifier' in the document URL: {{{#SPM:true}}} or {{{#SPM:false}}}.
* If more than one display mode is selected, 'one at a time' display takes precedence over both 'top' and 'bottom' settings, and if 'one at a time' setting is not used, 'top of page' takes precedence over 'bottom of page'.
* When using Apple's Safari browser, automatically setting the permalink causes an error and is disabled.
<<<
!!!!!Revisions
<<<
2010.11.30 2.9.7 use story.getTiddler()
2008.10.17 2.9.6 changed chkSinglePageAutoScroll default to false
| Please see [[SinglePageModePluginInfo]] for previous revision details |
2005.08.15 1.0.0 Initial Release.  Support for BACK/FORWARD buttons adapted from code developed by Clint Checketts.
<<<
!!!!!Code
***/
//{{{
version.extensions.SinglePageModePlugin= {major: 2, minor: 9, revision: 7, date: new Date(2010,11,30)};
//}}}
//{{{
config.paramifiers.SPM = { onstart: function(v) {
	config.options.chkSinglePageMode=eval(v);
	if (config.options.chkSinglePageMode && config.options.chkSinglePagePermalink && !config.browser.isSafari) {
		config.lastURL = window.location.hash;
		if (!config.SPMTimer) config.SPMTimer=window.setInterval(function() {checkLastURL();},1000);
	}
} };
//}}}
//{{{
if (config.options.chkSinglePageMode==undefined)
	config.options.chkSinglePageMode=false;
if (config.options.chkSinglePagePermalink==undefined)
	config.options.chkSinglePagePermalink=true;
if (config.options.chkSinglePageKeepFoldedTiddlers==undefined)
	config.options.chkSinglePageKeepFoldedTiddlers=false;
if (config.options.chkSinglePageKeepEditedTiddlers==undefined)
	config.options.chkSinglePageKeepEditedTiddlers=false;
if (config.options.chkTopOfPageMode==undefined)
	config.options.chkTopOfPageMode=false;
if (config.options.chkBottomOfPageMode==undefined)
	config.options.chkBottomOfPageMode=false;
if (config.options.chkSinglePageAutoScroll==undefined)
	config.options.chkSinglePageAutoScroll=false;
//}}}
//{{{
config.SPMTimer = 0;
config.lastURL = window.location.hash;
function checkLastURL()
{
	if (!config.options.chkSinglePageMode)
		{ window.clearInterval(config.SPMTimer); config.SPMTimer=0; return; }
	if (config.lastURL == window.location.hash) return; // no change in hash
	var tids=decodeURIComponent(window.location.hash.substr(1)).readBracketedList();
	if (tids.length==1) // permalink (single tiddler in URL)
		story.displayTiddler(null,tids[0]);
	else { // restore permaview or default view
		config.lastURL = window.location.hash;
		if (!tids.length) tids=store.getTiddlerText("DefaultTiddlers").readBracketedList();
		story.closeAllTiddlers();
		story.displayTiddlers(null,tids);
	}
}


if (Story.prototype.SPM_coreDisplayTiddler==undefined)
	Story.prototype.SPM_coreDisplayTiddler=Story.prototype.displayTiddler;
Story.prototype.displayTiddler = function(srcElement,tiddler,template,animate,slowly)
{
	var title=(tiddler instanceof Tiddler)?tiddler.title:tiddler;
	var tiddlerElem=story.getTiddler(title); // ==null unless tiddler is already displayed
	var opt=config.options;
	var single=opt.chkSinglePageMode && !startingUp;
	var top=opt.chkTopOfPageMode && !startingUp;
	var bottom=opt.chkBottomOfPageMode && !startingUp;
	if (single) {
		story.forEachTiddler(function(tid,elem) {
			// skip current tiddler and, optionally, tiddlers that are folded.
			if (	tid==title
				|| (opt.chkSinglePageKeepFoldedTiddlers && elem.getAttribute("folded")=="true"))
				return;
			// if a tiddler is being edited, ask before closing
			if (elem.getAttribute("dirty")=="true") {
				if (opt.chkSinglePageKeepEditedTiddlers) return;
				// if tiddler to be displayed is already shown, then leave active tiddler editor as is
				// (occurs when switching between view and edit modes)
				if (tiddlerElem) return;
				// otherwise, ask for permission
				var msg="'"+tid+"' is currently being edited.\n\n";
				msg+="Press OK to save and close this tiddler\nor press Cancel to leave it opened";
				if (!confirm(msg)) return; else story.saveTiddler(tid);
			}
			story.closeTiddler(tid);
		});
	}
	else if (top)
		arguments[0]=null;
	else if (bottom)
		arguments[0]="bottom";
	if (single && opt.chkSinglePagePermalink && !config.browser.isSafari) {
		window.location.hash = encodeURIComponent(String.encodeTiddlyLink(title));
		config.lastURL = window.location.hash;
		document.title = wikifyPlain("SiteTitleText") + " - " + title;
		if (!config.SPMTimer) config.SPMTimer=window.setInterval(function() {checkLastURL();},1000);
	}
	if (tiddlerElem && tiddlerElem.getAttribute("dirty")=="true") { // editing... move tiddler without re-rendering
		var isTopTiddler=(tiddlerElem.previousSibling==null);
		if (!isTopTiddler && (single || top))
			tiddlerElem.parentNode.insertBefore(tiddlerElem,tiddlerElem.parentNode.firstChild);
		else if (bottom)
			tiddlerElem.parentNode.insertBefore(tiddlerElem,null);
		else this.SPM_coreDisplayTiddler.apply(this,arguments); // let CORE render tiddler
	} else
		this.SPM_coreDisplayTiddler.apply(this,arguments); // let CORE render tiddler
	var tiddlerElem=story.getTiddler(title);
	if (tiddlerElem&&opt.chkSinglePageAutoScroll) {
		// scroll to top of page or top of tiddler
		var isTopTiddler=(tiddlerElem.previousSibling==null);
		var yPos=isTopTiddler?0:ensureVisible(tiddlerElem);
		// if animating, defer scroll until after animation completes
		var delay=opt.chkAnimate?config.animDuration+10:0;
		setTimeout("window.scrollTo(0,"+yPos+")",delay); 
	}
}

if (Story.prototype.SPM_coreDisplayTiddlers==undefined)
	Story.prototype.SPM_coreDisplayTiddlers=Story.prototype.displayTiddlers;
Story.prototype.displayTiddlers = function() {
	// suspend single/top/bottom modes when showing multiple tiddlers
	var opt=config.options;
	var saveSPM=opt.chkSinglePageMode; opt.chkSinglePageMode=false;
	var saveTPM=opt.chkTopOfPageMode; opt.chkTopOfPageMode=false;
	var saveBPM=opt.chkBottomOfPageMode; opt.chkBottomOfPageMode=false;
	this.SPM_coreDisplayTiddlers.apply(this,arguments);
	opt.chkBottomOfPageMode=saveBPM;
	opt.chkTopOfPageMode=saveTPM;
	opt.chkSinglePageMode=saveSPM;
}
//}}}
/***
|Name|SinglePageModePluginInfo|
|Source|http://www.TiddlyTools.com/#SinglePageModePlugin|
|Documentation|http://www.TiddlyTools.com/#SinglePageModePluginInfo|
|Version|2.9.6|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|documentation|
|Description|Documentation for SinglePageModePlugin|
Normally, as you click on the links in TiddlyWiki, more and more tiddlers are displayed on the page. The order of this tiddler display depends upon when and where you have clicked. Some people like this non-linear method of reading the document, while others have reported that when many tiddlers have been opened, it can get somewhat confusing.  SinglePageModePlugin allows you to configure TiddlyWiki to navigate more like a traditional multipage web site with only one item displayed at a time.
!!!!!Usage
<<<
When the plugin is enabled, only one tiddler will be displayed at a time and the browser window's titlebar is updated to include the current tiddler title.  The browser's location URL is also updated with a 'permalink' for the current tiddler so that it is easier to create a browser 'bookmark' for the current tiddler.  Alternatively, even when displaying multiple tiddlers //is// permitted, you can still reduce the potential for confusion by forcing  tiddlers to always open at the top (or bottom) of the page instead of being displayed following the tiddler containing the link that was clicked.
<<<
!!!!!Configuration
<<<
<<option chkSinglePageMode>> Display one tiddler at a time
><<option chkSinglePagePermalink>> Automatically permalink current tiddler
><<option chkSinglePageKeepFoldedTiddlers>> Don't close tiddlers that are folded
><<option chkSinglePageKeepEditedTiddlers>> Don't close tiddlers that are being edited
<<option chkTopOfPageMode>> Open tiddlers at the top of the page
<<option chkBottomOfPageMode>> Open tiddlers at the bottom of the page
<<option chkSinglePageAutoScroll>> Automatically scroll tiddler into view (if needed)

Notes:
* {{block{
The "display one tiddler at a time" option can also be //temporarily// set/reset by including a 'paramifier' in the document URL: {{{#SPM:true}}} or {{{#SPM:false}}}. You can also use {{{SPM:expression}}}, where 'expression' is any javascript statement that evaluates to true or false.  This allows you to create hard-coded links in other documents that can selectively enable/disable the use of this option based on various programmatic conditions, such as the current username. For example, using
&nbsp;&nbsp;&nbsp;{{{#SPM:config.options.txtUserName!="SomeName"}}}
enables 'one tiddler at a time' display for all users //other than// "~SomeName")}}}
* If more than one display mode is selected, 'one at a time' display takes precedence over both 'top' and 'bottom' settings, and if 'one at a time' setting is not used, 'top of page' takes precedence over 'bottom of page'.
* When using Apple's Safari browser, automatically setting the permalink causes an error and is disabled.
<<<
!!!!!Revisions
<<<
2008.10.17 2.9.6 changed chkSinglePageAutoScroll default to false
2008.06.12 2.9.5 corrected 'scroll to top of page' logic in auto-scroll handling
2008.06.11 2.9.4 added chkSinglePageKeepEditedTiddlers option
2008.06.05 2.9.3 in displayTiddler(), bypass single/top/bottom mode handling if startingUp.  Allows multiple tiddlers to be displayed during startup processing (e.g., #story:DefaultTiddlers), even if single/top/bottom mode is enabled.
2008.04.18 2.9.2 in displayTiddler() and checkLastURL(), handling for Unicode in tiddler titles (remove explicit conversion between Unicode and UTF, as this is apparently done automatically by encode/decodeURIComponent, resulting in double-encoding!
2008.04.08 2.9.1 don't automatically add options to AdvancedOptions shadow tiddler
2008.04.02 2.9.0 in displayTiddler(), when single-page mode is in use and a tiddler is being edited, ask for permission to save-and-close that tiddler, instead of just leaving it open.
2008.03.29 2.8.3 in displayTiddler(), get title from tiddler object (if needed).  Fixes errors caused when calling function passes a tiddler *object* instead of a tiddler *title*
2008.03.14 2.8.2 in displayTiddler(), if editing specified tiddler, just move it to top/bottom of story *without* re-rendering (prevents discard of partial edits).
2008.03.06 2.8.1 in paramifier handler, start 'checkURL' timer if chkSinglePageMode is enabled
2008.03.06 2.8.0 added option, {{{config.options.chkSinglePageKeepFoldedTiddlers}}}, so folded tiddlers won't be closed when using single-page mode.  Also, in checkURL(), if hash is a ''permaview'' (e.g., "#foo bar baz"), then display multiple tiddlers rather than attempting to display "foo bar baz" as a single tiddler
2008.03.05 2.7.0 added support for "SPM:" URL paramifier
2008.03.01 2.6.0 in hijack of displayTiddler(), added 'title' argument to closeAllTiddlers() so that target tiddler isn't closed-and-reopened if it was already displayed.  Also, added config.options.chkSinglePageAutoScrolloption to bypass automatic 'scroll into view' logic (note: core still does it's own ensureVisible() handling)
2007.12.22 2.5.3 in checkLastURL(), use decodeURIComponent() instead of decodeURI so that tiddler titles with commas (and/or other punctuation) are correctly handled.
2007.10.26 2.5.2 documentation cleanup
2007.10.08 2.5.1 in displayTiddler(), when using single-page or top-of-page mode, scrollTo(0,0) to ensure that page header is in view.
2007.09.13 2.5.0 for TPM/BPM modes, don't force tiddler to redisplay if already shown.  Allows transition between view/edit or collapsed/view templates, without repositioning displayed tiddler.
2007.09.12 2.4.0 added option to disable automatic permalink feature.  Also, Safari is now excluded from permalinking action to avoid bug where tiddlers don't display after hash is updated.
2007.03.03 2.3.1 fix typo when adding BPM option to AdvancedOptions (prevented checkbox from appearing)
2007.03.03 2.3.0 added support for BottomOfPageMode (BPM) based on request from DaveGarbutt
2007.02.06 2.2.3 in Story.prototype.displayTiddler(), use convertUnicodeToUTF8() for correct I18N string handling when creating URL hash string from tiddler title (based on bug report from BidiX)
2007.01.08 2.2.2 use apply() to invoke hijacked core functions
2006.07.04 2.2.1 in hijack for displayTiddlers(), suspend TPM as well as SPM so that DefaultTiddlers displays in the correct order.
2006.06.01 2.2.0 added chkTopOfPageMode (TPM) handling
2006.02.04 2.1.1 moved global variable declarations to config.* to avoid FireFox 1.5.0.1 crash bug when assigning to globals
2005.12.27 2.1.0 hijack displayTiddlers() so that SPM can be suspended during startup while displaying the DefaultTiddlers (or #hash list).  Also, corrected initialization for undefined SPM flag to "false", so default behavior is to display multiple tiddlers
2005.12.27 2.0.0 Update for TW2.0
2005.11.24 1.1.2 When the back and forward buttons are used, the page now changes to match the URL.  Based on code added by Clint Checketts
2005.10.14 1.1.1 permalink creation now calls encodeTiddlyLink() to handle tiddler titles with spaces in them
2005.10.14 1.1.0 added automatic setting of window title and location bar ('auto-permalink').  feature suggestion by David Dickens.
2005.10.09 1.0.1 combined documentation and code in a single tiddler
2005.08.15 1.0.0 Initial Release
<<<
Micro-kernel documentation
[img(50%,)[SIMILAR API suite|../images/similarLogo.png]] [>img[images/structure_thumb.png]]
Similar API suite
/*{{{*/
/*Haemoglobin Theme for TiddlyWiki*/
/*Design and CSS by Saq Imtiaz*/
/*Version 1.0*/
/*}}}*/
/*{{{*/
#leftMenu {position:relative; float:left; display:inline;margin:0 0.5em 0 0.5em;}
#displayArea{margin:0.5em 0.5em 2em 0.5em;}
#tiddlerDisplay, #tiddlersBar {margin-left:17em;}
#tiddlerDisplay {margin-left:17em;}





#sidebarTabs {font-family:arial,helvetica;}

body
{background:#fefefe;}

#contentWrapper {
	font-family: Verdana, Arial, Tahoma, Sans-Serif;
	color: #555555;
margin:1.9em auto 1em ; width:1024px;}

#header {background:#fefefe;}

.headerShadow {	padding: 1.4em 0em 0.5em 1em; }

.siteTitle {
			font-family: 'Trebuchet MS' sans-serif;
			font-weight: bold;
			font-size: 36px;
			color: #BF2323;
			background-color: #FFF;
}

.siteSubtitle {
	font-size: 1.0em;
        display: block;
        margin: .5em 3em; color: #999;
}

.clearAll {clear:both;}
.tagClear {clear:none;}
#sidebar {position:relative; float:right; display:inline; right:0;}

a{
color:#BF2323;
text-decoration: none; font-weight:normal;
}

a:hover{
color:#BF2323;
background-color: #fefefe;
border-bottom:1px solid #BF2323;
}

.viewer .button, .editorFooter .button{
color: #555;
border: 1px solid #BF2323;
}

.viewer .button:hover,
.editorFooter .button:hover{
color: #fff;
background: #BF2323;
border-color: #BF2323;
}

.viewer .button:active, .viewer .highlight,.editorFooter .button:active, .editorFooter .highlight{color:#fff; background:#9F1313;border-color:#9F1313;}

#topMenu br {display:none;}

#topMenu {padding:0.45em 1em; background:#BF2323;}

#topMenu a, #topMenu .tiddlyLink, #topMenu .button {color:#f1f1f1; padding:0.3em 0.45em; margin:0 4px;font-size:120%;font-weight:normal;font-variant: small-caps; border:none; background:#BF2323; text-decoration:none; }

#topMenu a:hover, #topMenu .tiddlyLink:hover, #topMenu .button:hover, #topMenu .button:active, #topMenu .highlight {color:#fff;text-decoration:none; background:#9F1313; }

.title {color:#BF2323; border-bottom:1px solid#BF2323; }
.subtitle, .subtitle a { color: #999999; font-size: 1.0em;margin:0.2em;}
.shadow .title{color:#999;}

.toolbar {font-size:85%;}
.selected .toolbar a {color:#999999;}
.selected .toolbar a:hover {color:#333; background:transparent;border:1px solid #fff;}

.toolbar .button:hover, .toolbar .highlight, .toolbar .marked, .toolbar a.button:active{color:#333; background:transparent;border:1px solid #fff;}

    *  html .viewer pre {

margin-left: 0em;
}

    * html .editor textarea, * html .editor input {

width: 98%;
}


.tabSelected{color:#fefefe; background:#999;}



 .tabSelected, .tabSelected:hover {
 color: #555;
 background: #fefefe;
 border: solid 1px #ccc;

}

#sidebarTabs .tabUnselected:hover { border-bottom: none;padding-bottom:3px;color:#999;}

 .tabUnselected {
 color: #999;
 background: #eee;
 border: solid 1px #ccc;

}

.tabUnselected:hover {text-decoration:none; border:1px solid #ccc;}

#sidebarTabs .tabUnselected { border-bottom: none;padding-bottom:3px;}
#sidebarTabs .tabSelected{padding-bottom:3px;}

#sidebarOptions .sliderPanel {
	background: #eee; border:1px solid#ccc;
	font-size: .9em;
}

#sidebarOptions .sliderPanel input {border:1px solid #999;}
#sidebarOptions .sliderPanel .txtOptionInput {border:1px solid #999;width:9em;}

#sidebarOptions .sliderPanel a {font-weight:normal; color:#555;background-color: #eee; border-bottom:1px dotted #333;}


#sidebarOptions .sliderPanel a:hover {
color:#111;
background-color: #eee;
border:none;
border-bottom:1px dotted #111;
}

.tabContents {background:#fefefe;}




.tagging, .tagged {
border: 1px solid #eee;
background-color: #F7F7F7;
}

.selected .tagging, .selected .tagged {
background-color: #f7f7f7;
border: 1px solid #ccc;
}

.tagging .listTitle, .tagged .listTitle {
color: #bbb;
}

.selected .tagging .listTitle, .selected .tagged .listTitle {
color: #666;
}

.tagging .button, .tagged .button {
color:#ccc;
}
.selected .tagging .button, .selected .tagged .button {
color:#aaa;
}

.highlight, .marked {background:transparent; color:#111; border:none; text-decoration:underline;}

.tagging .button:hover, .tagged .button:hover, .tagging .button:active, .tagged .button:active {
border: none; background:transparent; text-decoration:underline; color:#333;
}

.popup {
background: #BF2323;
border: 1px solid #BF2323;
}

.popup li.disabled {
color: #000;
}

.popup li a, .popup li a:visited {
color: #eee;
border: none;
}

.popup li a:hover {
background: #bf1717;
color: #fff;
border: none;
}



   #messageArea {

border: 4px solid #BF2323;
background: #fefefe;
color: #555;
font-size:90%;
}

   #messageArea a:hover { background:#f5f5f5; border:none;}


   #messageArea .button{
color: #666;
border: 1px solid #BF2323;
}

   #messageArea .button:hover {
color: #fff;
background: #BF2323;
border-color: #BF2323;
}

   #contentFooter {background:#BF2323; color:#DF7D7D; clear: both; padding: 0.5em 1em; }


#contentFooter a {
color: #DF7D7D;
border-bottom: 1px dotted #DF7D7D; font-weight:normal;text-decoration:none;
}



#contentFooter a:hover {
color: #FFFFFF;
background-color:transparent;
border-bottom: 1px dotted #fff; text-decoration:none;
}




.searchBar {float:right;font-size: 1.0em;position:relative; margin-top:1.3em;}
.searchBar .button {color:#999;display:block;}
.searchBar .button:hover {border:1px solid #fefefe;color:#4F4B45;}
.searchBar input {			
                        background-color: #fefefe;
			color: #999999;
			border: 1px solid #CCC;		margin-right:3px;
}

.tiddler {padding-bottom:10px;}

.viewer blockquote {
border-left: 5px solid #BF2323;
}

.viewer table, .viewer td {
border: 1px solid #BF2323;
}

.viewer th, thead td {
background: #BF2323;
border: 1px solid #BF2323;
color: #fff;
}
.viewer pre {
	border: 1px solid #ccc;
	background: #f5f5f5;
}

.viewer code {
color: #111; background:#f5f5f5;
}

.viewer hr {
border-top: dashed 1px #555;
}

.editor input {
border: 1px solid #888; margin-top:5px;
}

.editor textarea {
border: 1px solid #888;
}

h1,h2,h3,h4,h5 { color: #BF2323; background: transparent; padding-bottom:2px; font-family: Arial, Helvetica, sans-serif; }
h1 {font-size:18px;}
h2 {font-size:16px;}
h3 {font-size: 14px;}
/*}}}*/
[[StyleSheetCustomization]]
[[StyleSheetCustomization - DefaultStyles]]
[[StyleSheetCustomization - Buttons]]
[[StyleSheetCustomization - Collapse buttons]]
[[StyleSheetCustomization - Generic styles]]
[[StyleSheetCustomization - Wikispecific]]

[[StyleSheetCustomization - NestedSlidersPlugin]]
/*{{{*/
/* ********************************************************
 * This tiddler contains the CSS rules for the button
 * displaying a big link on screen.
 ******************************************************** */
/*}}}*/

/*{{{*/
.linkbigbtn a {
	-moz-box-shadow:inset 0px 1px 0px 0px #f29c93;
	-webkit-box-shadow:inset 0px 1px 0px 0px #f29c93;
	box-shadow:inset 0px 1px 0px 0px #f29c93;
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #fe1a00), color-stop(1, #ce0100) );
	background:-moz-linear-gradient( center top, #fe1a00 5%, #ce0100 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fe1a00', endColorstr='#ce0100');
	background-color:#fe1a00;
	-webkit-border-top-left-radius:20px;
	-moz-border-radius-topleft:20px;
	border-top-left-radius:20px;
	-webkit-border-top-right-radius:20px;
	-moz-border-radius-topright:20px;
	border-top-right-radius:20px;
	-webkit-border-bottom-right-radius:20px;
	-moz-border-radius-bottomright:20px;
	border-bottom-right-radius:20px;
	-webkit-border-bottom-left-radius:20px;
	-moz-border-radius-bottomleft:20px;
	border-bottom-left-radius:20px;
	text-indent:0;
	border:1px solid #d83526;
	display:inline-block;
	color:#ffffff;
	font-family:Arial;
	font-size:22px;
	font-weight:bold;
	font-style:normal;
	height:50px;
	line-height:50px;
	text-decoration:none;
	text-align:center;
	text-shadow:1px 1px 0px #b23e35;
	padding-left: 3em;
	padding-right: 3em;
}
.linkbigbtn a:hover {
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ce0100), color-stop(1, #fe1a00) );
	background:-moz-linear-gradient( center top, #ce0100 5%, #fe1a00 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ce0100', endColorstr='#fe1a00');
	background-color:#ce0100;
	text-decoration: none;
}
.linkbigbtn a:active {
	position:relative;
	top:1px;
}
/* This button was generated using CSSButtonGenerator.com */
/*}}}*/
/*{{{*/
/* ********************************************************
 * This tiddler contains the CSS rules for the buttons
 * used to expand or collapse a block, using the nested
 * sliders plugin.
 * It also defines the CSS rules of the expanded blocks.
 ******************************************************** */
/*}}}*/

/*{{{*/
/* ********************************************************
 * Buttons common features
 ******************************************************** */
.docsmallbtn, .implsmallbtn, .exsmallbtn, .moresmallbtn, .implbigbtn, .docbigbtn, .exbigbtn , .morebigbtn, .doclink a, .morelink a {
	text-indent:0;
	display:inline-block;
	color:#ffffff;
	font-family:Arial;
	font-size:15px;
	font-weight:bold;
	font-style:normal;
	text-decoration:none;
	margin-top: 1px ;
	margin-bottom: 1px ;
}
.docsmallbtn:hover, .implsmallbtn.hover, .exsmallbtn:hover, .moresmallbtn:hover, .implbigbtn:hover, .docbigbtn:hover, .exbigbtn:hover, .morebigbtn:hover, .morelink a:hover, .doclink a:hover {
	color: #FFFFFF;
	text-decoration: none;
}
.docsmallbtn:active, .implsmallbtn:active, .exsmallbtn:active, .moresmallbtn:active, .implbigbtn:active, .docbigbtn:active, .exbigbtn:active, .morebigbtn:active, .morelink a:active, .doclink a:active {
	position:relative;
	top:1px;
}
/* ********************************************************
 * Small buttons common features
 ******************************************************** */
.docsmallbtn, .implsmallbtn, .exsmallbtn, .moresmallbtn, .morelink a, .doclink a {
	-webkit-border-top-left-radius:20px;
	-moz-border-radius-topleft:20px;
	border-top-left-radius:20px;
	-webkit-border-top-right-radius:20px;
	-moz-border-radius-topright:20px;
	border-top-right-radius:20px;
	-webkit-border-bottom-right-radius:20px;
	-moz-border-radius-bottomright:20px;
	border-bottom-right-radius:20px;
	-webkit-border-bottom-left-radius:20px;
	-moz-border-radius-bottomleft:20px;
	border-bottom-left-radius:20px;
	line-height:24px;
	height:24px;
	text-align:center;
	width:120px;
}
/* ********************************************************
 * Big buttons common features
 ******************************************************** */
.implbigbtn, .docbigbtn, .exbigbtn, .morebigbtn {
	-webkit-border-top-left-radius:0px;
	-moz-border-radius-topleft:0px;
	border-top-left-radius:0px;
	-webkit-border-top-right-radius:11px;
	-moz-border-radius-topright:11px;
	border-top-right-radius:11px;
	-webkit-border-bottom-right-radius:0px;
	-moz-border-radius-bottomright:0px;
	border-bottom-right-radius:0px;
	-webkit-border-bottom-left-radius:0px;
	-moz-border-radius-bottomleft:0px;
	border-bottom-left-radius:0px;
	height:40px;
	line-height:40px;
	padding-left: 2.5em;
	width:75%;
}
/*}}}*/

/*{{{*/
/* ********************************************************
 * Common features of blocks following a big or small button
 ******************************************************** */
.implsection, .exsection, .docsection, .docsubsection, .moresection {
	display:block;
	padding: 0.5em;
	margin-top:0.25em;
	margin-bottom:0.25em;
}
/*}}}*/

/*{{{*/
/* ********************************************************
 * Implementation-related declarations
 ******************************************************** */
/*}}}*/
/*{{{*/
/* Definition of the common features of the small 
 * and big buttons that can be put 
 * in a line to display the implementation */
/* This button was generated using CSSButtonGenerator.com */
.implsmallbtn, .implbigbtn {
	-moz-box-shadow:inset 0px 1px 0px 0px #c1ed9c;
	-webkit-box-shadow:inset 0px 1px 0px 0px #c1ed9c;
	box-shadow:inset 0px 1px 0px 0px #c1ed9c;
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #9dce2c), color-stop(1, #8cb82b) );
	background:-moz-linear-gradient( center top, #9dce2c 5%, #8cb82b 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#9dce2c', endColorstr='#8cb82b');
	background-color:#9dce2c;
	border:1px solid #83c41a;
	text-shadow:1px 1px 0px #689324;
}
.implsmallbtn:hover, .implbigbtn:hover {
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #8cb82b), color-stop(1, #9dce2c) );
	background:-moz-linear-gradient( center top, #8cb82b 5%, #9dce2c 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#8cb82b', endColorstr='#9dce2c');
	background-color:#8cb82b;
}
/* Definition of the block under the button displaying the implementation */
.implsection {
	border:1px solid #30BF30;
	background-color: #C3FFC3;
}
/* Change the color of the titles inside an implementation section. */
.implsection h1, .implsection h2, .implsection h3, .implsection h4, .implsection h5 {
	color: #30BF30;
}
/*}}}*/

/*{{{*/
/* ********************************************************
 * Documentation-related declarations
 ******************************************************** */
/*}}}*/
/*{{{*/
/* Definition of the common features of the small 
 * and big buttons that can be put 
 * in a line to display the documentation */
/* This button was generated using CSSButtonGenerator.com */
.docsmallbtn, .docbigbtn, .doclink a {
	-moz-box-shadow:inset 0px 1px 0px 0px #bbdaf7;
	-webkit-box-shadow:inset 0px 1px 0px 0px #bbdaf7;
	box-shadow:inset 0px 1px 0px 0px #bbdaf7;
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #79bbff), color-stop(1, #378de5) );
	background:-moz-linear-gradient( center top, #79bbff 5%, #378de5 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#79bbff', endColorstr='#378de5');
	background-color:#79bbff;
	border:1px solid #84bbf3;
	text-shadow:1px 1px 0px #528ecc;
}
.docsmallbtn:hover, .docbigbtn:hover, .doclink a:hover {
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #378de5), color-stop(1, #79bbff) );
	background:-moz-linear-gradient( center top, #378de5 5%, #79bbff 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#378de5', endColorstr='#79bbff');
	background-color:#378de5;
}

/* Definition of the block under the button displaying the documentation */
.docsection {
	border:1px solid #528fcc;
	background-color: #d6eafc;
}
.docsubsection {
	border:1px solid #528fcc;
	background-color: #96d9f5;
}
/* Change the color of the titles inside a document section. */
.docsection h1, .docsection h2, .docsection h3, .docsection h4, .docsection h5 {
	color: #528fcc;
}

/* Definition of a title style for the javadoc */
.javadoctitle {
	display: block;
	font-weight: bold;
	font-size:130%;
	text-decoration: underline;
	color: #528fcc;
	margin-top: 1em;
}

/* Definition of a block displaying the javadoc */
.javadocsection {
	display: block;
	border:1px solid #528fcc;
	padding: 0.5em;
	background: #FFFFFF;
	margin-top:-1em;
	margin-bottom:0.25em;
	margin-left: 1em;
}
/*}}}*/


/*{{{*/
/* ********************************************************
 * Example-related declarations
 ******************************************************** */
/*}}}*/
/*{{{*/
/* Definition of the common features of the small 
 * and big buttons that can be put 
 * in a line to display an example */
/* This button was generated using CSSButtonGenerator.com */
.exsmallbtn, .exbigbtn {
	-moz-box-shadow:inset 0px 1px 0px 0px #fed897;
	-webkit-box-shadow:inset 0px 1px 0px 0px #fed897;
	box-shadow:inset 0px 1px 0px 0px #fed897;
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #f6b33d), color-stop(1, #d29105) );
	background:-moz-linear-gradient( center top, #f6b33d 5%, #d29105 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f6b33d', endColorstr='#d29105');
	background-color:#f6b33d;
	border:1px solid #eda933;
	text-shadow:1px 1px 0px #cd8a15;
}
.exsmallbtn:hover, .exbigbtn:hover {
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #d29105), color-stop(1, #f6b33d) );
	background:-moz-linear-gradient( center top, #d29105 5%, #f6b33d 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#d29105', endColorstr='#f6b33d');
	background-color:#d29105;
}
/* Definition of the block under the button displaying the example */
.exsection {
	border:1px solid #eda933;
	background-color: #fae4bd;
}
/* Change the color of the titles inside an example section. */
.exsection h1, .exsection h2, .exsection h3, .exsection h4, .exsection h5 {
	color: #eda933;
}
/*}}}*/

/*{{{*/
/* ********************************************************
 * Read more-related declarations
 ******************************************************** */
/*}}}*/
/*{{{*/
/* Definition of the common features of the small 
 * and big buttons that can be put 
 * in a line to display more information*/
/* This button was generated using CSSButtonGenerator.com */
.moresmallbtn, .morebigbtn, .morelink a {
	-moz-box-shadow:inset 0px 1px 0px 0px #f29c93;
	-webkit-box-shadow:inset 0px 1px 0px 0px #f29c93;
	box-shadow:inset 0px 1px 0px 0px #f29c93;
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #fe1a00), color-stop(1, #ce0100) );
	background:-moz-linear-gradient( center top, #fe1a00 5%, #ce0100 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fe1a00', endColorstr='#ce0100');
	background-color:#fe1a00;
	border:1px solid #d83526;
	text-shadow:1px 1px 0px #b23e35;
}
.moresmallbtn:hover, .morebigbtn:hover, .morelink a:hover {
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ce0100), color-stop(1, #fe1a00) );
	background:-moz-linear-gradient( center top, #ce0100 5%, #fe1a00 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ce0100', endColorstr='#fe1a00');
	background-color:#ce0100;
}
/* Definition of the block under the button displaying the additional information */
.moresection {
	border:1px solid #dcdcdc;
	background-color: #f9f9f9;
}
/* Change the color of the titles inside additional information. */
.moresection h1, .moresection h2, .moresection h3, .moresection h4, .moresection h5 {
	color: #ce0100;
}
/*}}}*/
/*{{{*/
/* ********************************************************
 * This tiddler contains the CSS rules for the custom 
 * default behavior of some HTML tags of the wiki.
 ******************************************************** */
/*}}}*/

/*{{{*/
/* Put an image before the "back to parent" link. */
.toparent a:before {
	content:url(images/arrow.png);
	margin-right: 0.5em;
}
.toparent {
	display:block;
	margin-bottom: -0.5em;
}
/*}}}*/

/*{{{*/
/* Justify text by default */

body {
	text-align: justify;
}
/*}}}*/
/*{{{*/
/* Put a border around images by default */

#tiddlerDisplay img {
	border:1px solid #A60000;
	padding: 0.25em;
	margin: 0.25em;
}
/*}}}*/
/*{{{*/
/* Prevent bullets from overlapping a floating block */

ul, ol {
	overflow: hidden;
}
/*}}}*/
/*{{{*/
/* Set the caption of images as bold. */

span.center.caption {
	font-family: Impact;
	font-style: italic;
	font-size: 130%;
}
/*}}}*/
/*{{{*/
/* Use the same style for internal and external links. */
.externalLink {
	font-weight: bold;
	text-decoration: none;
}
/*}}}*/
/*{{{*/
/* ********************************************************
 * This tiddler contains the CSS rules for the classes
 * that are used in any wiki of this documentation.
 ******************************************************** */
/*}}}*/
/*{{{*/
/* Image flush command */
.clear {
	display:block;
	clear:both;
	margin-bottom:-1em;
}
.clearright {
	display:block;
	clear:right;
	margin-bottom:-1em;
}
.clearleft {
	display:block;
	clear:right;
	margin-bottom:-1em;
}
/*}}}*/
/*{{{*/
/* alignment commands */

.center {
	display:block;
	text-align:center;
}
/*}}}*/
/*{{{*/
/* figure related commands */
.caption{
	display:block;
	text-align:center;
	font-family: Impact;
	font-style: italic;
	font-size: 130%;
}
/*}}}*/
/*{{{*/
/* Java classes related commands */
.className {
	font-family: cursive;
	font-weight: bold;
}
.methodName {
	font-family: cursive;
	font-weight: bold;
	font-style: italic;
}
.fieldName {
	font-family: cursive;
	font-weight: bold;
}
.argumentName {
	font-family: cursive;
	font-weight: bold;
}
.packageName {
	font-family: cursive;
	font-style: italic;
	font-weight: bold;
}
.packageName:before, .packageName:after, .methodName:before, .methodName:after {
	content: '"';
}
/*}}}*/
/*{{{*/
/* Block putting a big emphasis on text. */

.focusemphasisblock{
	display:block;
	border:1px solid #008000;
	background-color: #DEFEDE;
	padding: 1.5em;
	font-weight: bold;
	color: #008000;
}
/*}}}*/
/*{{{*/
/* Block putting a strong emphasis on text. */

.bigemphasisblock {
	display:block;
	border:1px solid #A60000;
	background-color: #FF7373;
	padding: 1.5em;
	font-weight: bold;
	color: #FEFEFE;
}
/*}}}*/
/*{{{*/
/* *********************************************
The small button used by the nested slider plugin 
when the "+ + +" maccro is used without a text between "[ ]".
********************************************* */
/*}}}*/
/*{{{*/
.expandbutton {
	-moz-box-shadow:inset 0px 1px 0px 0px #f29c93;
	-webkit-box-shadow:inset 0px 1px 0px 0px #f29c93;
	box-shadow:inset 0px 1px 0px 0px #f29c93;
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #fe1a00), color-stop(1, #ce0100) );
	background:-moz-linear-gradient( center top, #fe1a00 5%, #ce0100 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fe1a00', endColorstr='#ce0100');
	background-color:#fe1a00;
	-webkit-border-top-left-radius:16px;
	-moz-border-radius-topleft:16px;
	border-top-left-radius:16px;
	-webkit-border-top-right-radius:16px;
	-moz-border-radius-topright:16px;
	border-top-right-radius:16px;
	-webkit-border-bottom-right-radius:16px;
	-moz-border-radius-bottomright:16px;
	border-bottom-right-radius:16px;
	-webkit-border-bottom-left-radius:16px;
	-moz-border-radius-bottomleft:16px;
	border-bottom-left-radius:16px;
	text-indent:0px;
	border:1px solid #d83526;
	display:inline-block;
	color:#ffffff;
	font-family:Arial;
	font-size:14px;
	font-weight:bold;
	font-style:normal;
	height:20px;
	line-height:20px;
	text-decoration:none;
	text-align:center;
	padding-left: 0.4em;
	padding-right: 0.4em;
}
.expandbutton:hover {
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ce0100), color-stop(1, #fe1a00) );
	background:-moz-linear-gradient( center top, #ce0100 5%, #fe1a00 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ce0100', endColorstr='#fe1a00');
	background-color:#ce0100;
}
.expandbutton:active {
	position:relative;
	top:1px;
}
/* This button was generated using CSSButtonGenerator.com */
/*}}}*/
/*{{{*/
/* ********************************************************
 * This tiddler contains the CSS rules for the classes
 * that are specific to this wiki.
 ******************************************************** */
/*}}}*/
[[StyleSheetCustomization - Wikispecific - GuidelinesNavMenu]]
/*{{{*/
/* ********************************************************
 * This tiddler contains the CSS rules for the classes
 * used in the navigation menu of the guidelines.
 ******************************************************** */
/*}}}*/
/*{{{*/
/* Style of the bar under the navigation buttons */
.guidelinesNavMenu {
	display:block;
	text-align:center;
	margin-top: 5px;
	margin-bottom: 5px;
}
hr.topSep, hr.botSep {
	margin-bottom: -0.5em;
	width: 100%;
	height: 2px;
	border: 0;
	background: -webkit-linear-gradient(left,  rgba(198,0,3,0) 0%,rgba(198,0,3,0.9) 50%,rgba(198,0,3,0) 100%);
	background: -o-linear-gradient(left,  rgba(198,0,3,0) 0%,rgba(198,0,3,0.9) 50%,rgba(198,0,3,0) 100%);
	background: -ms-linear-gradient(left,  rgba(198,0,3,0) 0%,rgba(198,0,3,0.9) 50%,rgba(198,0,3,0) 100%); 
	background: linear-gradient(to right,  rgba(198,0,3,0) 0%,rgba(198,0,3,0.9) 50%,rgba(198,0,3,0) 100%); 
}
hr.topSep {
	margin-top: -1em;
}
/*}}}*/
/*{{{*/
/* Style of the title displayed in the design guidelines */
.stepMainTitle {
	color: rgb(191,35,35);
	text-align: center;
	font-family: Impact;
	font-size: 300%;
	font-weight: bold;
	text-align: center;
	letter-spacing:2px;
	display:block;
	margin-top: 0.5em;
}
/*}}}*/
/*{{{*/
/* Style of the button displayed at the bottom of the design guidelines */
.nextButton {
	display:block;
	text-align:center;
	margin-top: 1em;
}
.nextButton a, .nextButton a:hover {
	width:100%;
	text-indent:0;
	border: 0;
	display:inline-block;
	font-family:Arial;
	font-size:22px;
	font-weight:bold;
	font-style:normal;
	height:50px;
	line-height:50px;
	color:#ffffff;
	text-align:center;
	background: -webkit-linear-gradient(left,  rgba(198,0,3,0) 0%,rgba(198,0,3,0.9) 50%,rgba(198,0,3,0) 100%);
	background: -o-linear-gradient(left,  rgba(198,0,3,0) 0%,rgba(198,0,3,0.9) 50%,rgba(198,0,3,0) 100%);
	background: -ms-linear-gradient(left,  rgba(198,0,3,0) 0%,rgba(198,0,3,0.9) 50%,rgba(198,0,3,0) 100%); 
	background: linear-gradient(to right,  rgba(198,0,3,0) 0%,rgba(198,0,3,0.9) 50%,rgba(198,0,3,0) 100%); 
}
.nextButton a {
	text-decoration:none;
}
.nextButton a:hover {
	text-decoration:underline;
}
.nextButton a:active {
	position:relative;
}
/*}}}*/
[[StyleSheetDropDownMenuPlugin]]
/*{{{*/
/***** LAYOUT STYLES -  DO NOT EDIT! *****/
ul.suckerfish, ul.suckerfish ul {
	margin: 0;
	padding: 0;
	list-style: none;
	line-height:1.4em;
}

ul.suckerfish  li {
	display: inline-block; 
	display: block;
	float: left; 
}

ul.suckerfish li ul {
	position: absolute;
	left: -999em;
}

ul.suckerfish li:hover ul, ul.suckerfish li.sfhover ul {
	left: auto;
}

ul.suckerfish ul li {
	float: none;
	border-right: 0;
	border-left:0;
}

ul.suckerfish a, ul.suckerfish a:hover {
	display: block;
}

ul.suckerfish li a.tiddlyLink, ul.suckerfish li a, #mainMenu ul.suckerfish li a {font-weight:bold;}
/**** END LAYOUT STYLES *****/


/**** COLORS AND APPEARANCE - DEFAULT *****/
ul.suckerfish li a {
	padding: 0.5em 1.5em;
	font-weight:bold;
	border-bottom: 0;
	-moz-box-shadow:inset 0px 1px 0px 0px #f29c93;
	-webkit-box-shadow:inset 0px 1px 0px 0px #f29c93;
	box-shadow:inset 0px 1px 0px 0px #f29c93;
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #fe1a00), color-stop(1, #ce0100) );
	background:-moz-linear-gradient( center top, #fe1a00 5%, #ce0100 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fe1a00', endColorstr='#ce0100');
	background-color:#fe1a00;
	color:#ffffff;
}

ul.suckerfish li:hover a, ul.suckerfish li.sfhover a{
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ce0100), color-stop(1, #fe1a00) );
	background:-moz-linear-gradient( center top, #ce0100 5%, #fe1a00 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ce0100', endColorstr='#fe1a00');
	background-color:#ce0100;
}

ul.suckerfish li:hover ul a, ul.suckerfish li.sfhover ul a{
	color: #d83526;
	background: #ffeeee;
}

ul.suckerfish ul li a:hover {
	background: #ffdddd;
}

ul.suckerfish li a{
	width:9.5em;
}

ul.suckerfish ul li a, ul.suckerfish ul li a:hover{
	display:inline-block;
	width:9.5em;
}

ul.suckerfish li {
	border:1px solid #d83526;
}

ul.suckerfish li ul li a {
	border-style: solid;
	border-color: #d83526;
	border-top-width: 0px;
	border-bottom-width: 1px;
	border-left-width: 1px;
	border-right-width: 1px;
}
/***** END COLORS AND APPEARANCE - DEFAULT *****/


/***** LAYOUT AND APPEARANCE: VERTICAL *****/
ul.suckerfish.vertical li{
	width:10em;
	border-left: 0px solid #00558f;
}

ul.suckerfish.vertical ul li, ul.suckerfish.vertical li a, ul.suckerfish.vertical li:hover a, ul.suckerfish.vertical li.sfhover a {
	border-left: 0.8em solid #00558f;
}

ul.suckerfish.vertical li a, ul.suckerfish.vertical li:hover a, ul.suckerfish.vertical li.sfhover a,  ul.suckerfish.vertical li.sfhover a:hover{
	width:8em;
}

ul.suckerfish.vertical {
	width:10em; text-align:left;
	float:left;
}

ul.suckerfish.vertical li a {
	padding: 0.5em 1em 0.5em 1em;
	border-top:1px solid  #fff;
}

ul.suckerfish.vertical, ul.suckerfish.vertical ul {
	line-height:1.4em;
}

ul.suckerfish.vertical li:hover ul, ul.suckerfish.vertical li.sfhover ul { 
	margin: -2.4em 0 0 10.9em;
}

ul.suckerfish.vertical li:hover ul li a, ul.suckerfish.vertical li.sfhover ul li a {
	border: 0px solid #FFF;
}

ul.suckerfish.vertical li:hover a, ul.suckerfish.vertical li.sfhover a{
	padding-right:1.1em;
}

ul.suckerfish.vertical li:hover ul li, ul.suckerfish.vertical li.sfhover ul li {
	border-bottom:1px solid  #fff;
}

/***** END LAYOUT AND APPEARANCE: VERTICAL *****/
/*}}}*/
The addition of an agent to the simulation is done using the {{className{[[SystemInfluenceAddAgentToLevel|../api/fr/lgi2a/similar/microkernel/influences/system/SystemInfluenceAddAgentToLevel.html]]}}} system influence.
!Specifications
Such an influence is created using the following constructor:
{{{
public SystemInfluenceAddAgentToLevel( 
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound, 
	ILocalStateOfAgent publicLocalState , 
	ILocalStateOfAgent privateLocalState 
);
}}}
This constructor defines the following arguments:
*{{argumentName{timeLowerBound}}} models the lower bound of the transitory period during which this influence was created;
*{{argumentName{timeUpperBound}}} models the upper bound of the transitory period during which this influence was created;
*{{argumentName{publicLocalState}}} models the public local state to add to the agent (and to the dynamic state of the level);
*{{argumentName{privateLocalState}}} models the private local state to add to the agent.
!Important notes
*The addition of the public and the private local state of the agent will be effective after the next reaction of the level for which the public local state is declared.
The addition of an agent to the simulation is done using the {{className{[[SystemInfluenceAddAgent|../api/fr/lgi2a/similar/microkernel/influences/system/SystemInfluenceAddAgent.html]]}}} system influence.
!Specifications
Such an influence is created using the following constructor:
{{{
public SystemInfluenceAddAgent( 
	LevelIdentifier targetLevel,
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound, 
	IAgent4Engine agent 
);
}}}
This constructor defines the following arguments:
*{{argumentName{targetLevel}}} models the level which reaction will add the new agent to the simulation;
*{{argumentName{timeLowerBound}}} models the lower bound of the transitory period during which this influence was created;
*{{argumentName{timeUpperBound}}} models the upper bound of the transitory period during which this influence was created;
*{{argumentName{agent}}} models the agent to add to the simulation. The agent has to be fully initialized before being added using this influence. This initialization has to include calls to the {{methodName{[[includeNewLevel(...)|../api/fr/lgi2a/similar/microkernel/agents/IAgent4Engine.html#includeNewLevel(fr.univ_artois.lgi2a.similar.microkernel.LevelIdentifier, fr.univ_artois.lgi2a.similar.microkernel.agents.ILocalStateOfAgent, fr.univ_artois.lgi2a.similar.microkernel.agents.ILocalStateOfAgent)]]}}} method of the {{className{IAgent4Engine}}} interface.
!Important notes
*The {{argumentName{targetLevel}}} of the influence defines when the public local states of the agent will begin to appear in the dynamic state of their respective levels: during the reaction of their respective levels occurring at the same time or after the reaction of {{argumentName{targetLevel}}};
*The reaction of this influence consists in creating a //"public local state addition"// influence for each public local state of the agent. These influences are processed either immediately if the level of the public local state is currently computing a reaction or during the next reaction of that level;
*If this influence is used on an agent already lying in the simulation, this influence will the public local states of the agent to their corresponding level, if they are not already present in the dynamic state of the level.
The removal of an agent from a level is done using the {{className{[[SystemInfluenceRemoveAgentFromLevel|../api/fr/lgi2a/similar/microkernel/influences/system/SystemInfluenceRemoveAgentFromLevel.html]]}}} system influence.
!Specifications
Such an influence can be created using two different constructors.
!!Removing another agent
This first constructor is used by the agents causing the removal of other agents from a level. It has the following signature:
{{{
public SystemInfluenceRemoveAgentFromLevel( 
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound, 
	ILocalStateOfAgent publicLocalStateOfAgent 
);
}}}
This constructor defines the following arguments:
*{{argumentName{timeLowerBound}}} models the lower bound of the transitory period during which this influence was created;
*{{argumentName{timeUpperBound}}} models the upper bound of the transitory period during which this influence was created;
*{{argumentName{publicLocalStateOfAgent}}} models the public local state that will dissapear as a side effect of this influence.
!!Removing iself
This second constructor is usually called by the agents decising to get out of a level by themselves:
{{{
public SystemInfluenceRemoveAgentFromLevel(
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound, 
	IAgent4Engine agent,
	LevelIdentifier levelId
);
}}}
This constructor defines the following arguments:
*{{argumentName{timeLowerBound}}} models the lower bound of the transitory period during which this influence was created;
*{{argumentName{timeUpperBound}}} models the upper bound of the transitory period during which this influence was created;
*{{argumentName{agent}}} models the agent that will be removed from a specific level;
*{{argumentName{levelId}}} models the identifier of the level from which the agent is removed.
The removal of an agent from the simulation is done using the {{className{[[SystemInfluenceRemoveAgent|../api/fr/lgi2a/similar/microkernel/influences/system/SystemInfluenceRemoveAgent.html]]}}} system influence.
!Specifications
Such an influence is created using the following constructor:
{{{
public SystemInfluenceRemoveAgent( 
	LevelIdentifier targetLevel, 
	SimulationTimeStamp timeLowerBound,
	SimulationTimeStamp timeUpperBound, 
	ILocalStateOfAgent publicLocalStateOfAgent 
);
}}}
This constructor defines the following arguments:
*{{argumentName{targetLevel}}} models the level which reaction will remove the specified agent from the simulation;
*{{argumentName{timeLowerBound}}} models the lower bound of the transitory period during which this influence was created;
*{{argumentName{timeUpperBound}}} models the upper bound of the transitory period during which this influence was created;
*{{argumentName{publicLocalStateOfAgent }}} models a public local state of the agent being removed from the simulation.
!Important notes
*The {{argumentName{targetLevel}}} of the influence defines when the public local states of the agent will begin to disappear from the dynamic state of their respective levels: during the reaction of their respective levels occurring at the same time or after the reaction of {{argumentName{targetLevel}}};
*The reaction of this influence consists in creating a //"public local state removal"// influence for each public local state of the agent. These influences are processed either immediately if the level of the public local state is currently computing a reaction or during the next reaction of that level.
The influences added to the influences set can either be the influences defined during the [[influence creation step|SMD - Influences skeleton]], or the following system influences:
*An influence ''adding'' an agent ''to the simulation''; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection {
<<tiddler [[System influence - Adding an agent to the simulation]]>>
}}} ===

*An influence ''removing'' an agent ''from the simulation''; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection {
<<tiddler [[System influence - Removing an agent from the simulation]]>>
}}} ===

*An influence ''adding'' an agent ''to a level''; +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection {
<<tiddler [[System influence - Adding an agent to a level]]>>
}}} ===

*An influence ''removing'' an agent ''from a level''. +++?[<span class="docsmallbtn">Documentation</span>]
{{docsection {
<<tiddler [[System influence - Removing an agent from a level]]>>
}}} ===
The influences resulting from this phase can be:
*''Regular influences'' modeling domain and case-dependent influences;
*''System influences'' modeling generic influences that can be found in any simulation. They currently include:
**The addition of a +++^34em^*@[fully initialized]Including the specification of the initial global state and the public local state in each level where they initially lie (see this step of the methodology).=== agent to the simulation
**The removal of an agent from the simulation (and from all the levels where it lies);
**The addition of an agent to a level;
**The removal of an agent from a level.
/*{{{*/
.leaf, .subtree {display:block; margin-left : 0.5em}
.subtree {margin-bottom:0.5em}
#mainMenu {text-align:left}
.branch .button {border:1px solid #DDD; color:#AAA;font-size:9px;padding:0 2px;margin-right:0.3em;vertical-align:middle;text-align:center;}
/*}}}*/
/***
|''Name:''|TiddlersBarPlugin|
|''Description:''|A bar to switch between tiddlers through tabs (like browser tabs bar).|
|''Version:''|1.2.5|
|''Date:''|Jan 18,2008|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.1.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0, others|
!Demos
On [[homepage|http://visualtw.ouvaton.org/VisualTW.html]], open several tiddlers to use the tabs bar.
!Installation
#import this tiddler from [[homepage|http://visualtw.ouvaton.org/VisualTW.html]] (tagged as systemConfig)
#save and reload
#''if you're using a custom [[PageTemplate]]'', add {{{<div id='tiddlersBar' refresh='none' ondblclick='config.macros.tiddlersBar.onTiddlersBarAction(event)'></div>}}} before {{{<div id='tiddlerDisplay'></div>}}}
#optionally, adjust StyleSheetTiddlersBar
!Tips
*Doubleclick on the tiddlers bar (where there is no tab) create a new tiddler.
*Tabs include a button to close {{{x}}} or save {{{!}}} their tiddler.
*By default, click on the current tab close all others tiddlers.
!Configuration options 
<<option chkDisableTabsBar>> Disable the tabs bar (to print, by example).
<<option chkHideTabsBarWhenSingleTab >> Automatically hide the tabs bar when only one tiddler is displayed. 
<<option txtSelectedTiddlerTabButton>> ''selected'' tab command button.
<<option txtPreviousTabKey>> previous tab access key.
<<option txtNextTabKey>> next tab access key.
!Code
***/
//{{{
config.options.chkDisableTabsBar = config.options.chkDisableTabsBar ? config.options.chkDisableTabsBar : false;
config.options.chkHideTabsBarWhenSingleTab  = config.options.chkHideTabsBarWhenSingleTab  ? config.options.chkHideTabsBarWhenSingleTab  : false;
config.options.txtSelectedTiddlerTabButton = config.options.txtSelectedTiddlerTabButton ? config.options.txtSelectedTiddlerTabButton : "closeOthers";
config.options.txtPreviousTabKey = config.options.txtPreviousTabKey ? config.options.txtPreviousTabKey : "";
config.options.txtNextTabKey = config.options.txtNextTabKey ? config.options.txtNextTabKey : "";
config.macros.tiddlersBar = {
	tooltip : "see ",
	tooltipClose : "click here to close this tab",
	tooltipSave : "click here to save this tab",
	promptRename : "Enter tiddler new name",
	currentTiddler : "",
	previousState : false,
	previousKey : config.options.txtPreviousTabKey,
	nextKey : config.options.txtNextTabKey,	
	tabsAnimationSource : null, //use document.getElementById("tiddlerDisplay") if you need animation on tab switching.
	handler: function(place,macroName,params) {
		var previous = null;
		if (config.macros.tiddlersBar.isShown())
			story.forEachTiddler(function(title,e){
				if (title==config.macros.tiddlersBar.currentTiddler){
					var d = createTiddlyElement(null,"span",null,"tab tabSelected");
					config.macros.tiddlersBar.createActiveTabButton(d,title);
					if (previous && config.macros.tiddlersBar.previousKey) previous.setAttribute("accessKey",config.macros.tiddlersBar.nextKey);
					previous = "active";
				}
				else {
					var d = createTiddlyElement(place,"span",null,"tab tabUnselected");
					var btn = createTiddlyButton(d,title,config.macros.tiddlersBar.tooltip + title,config.macros.tiddlersBar.onSelectTab);
					btn.setAttribute("tiddler", title);
					if (previous=="active" && config.macros.tiddlersBar.nextKey) btn.setAttribute("accessKey",config.macros.tiddlersBar.previousKey);
					previous=btn;
				}
				var isDirty =story.isDirty(title);
				var c = createTiddlyButton(d,isDirty ?"!":"x",isDirty?config.macros.tiddlersBar.tooltipSave:config.macros.tiddlersBar.tooltipClose, isDirty ? config.macros.tiddlersBar.onTabSave : config.macros.tiddlersBar.onTabClose,"tabButton");
				c.setAttribute("tiddler", title);
				if (place.childNodes) {
					place.insertBefore(document.createTextNode(" "),place.firstChild); // to allow break line here when many tiddlers are open
					place.insertBefore(d,place.firstChild); 
				}
				else place.appendChild(d);
			})
	}, 
	refresh: function(place,params){
		removeChildren(place);
		config.macros.tiddlersBar.handler(place,"tiddlersBar",params);
		if (config.macros.tiddlersBar.previousState!=config.macros.tiddlersBar.isShown()) {
			story.refreshAllTiddlers();
			if (config.macros.tiddlersBar.previousState) story.forEachTiddler(function(t,e){e.style.display="";});
			config.macros.tiddlersBar.previousState = !config.macros.tiddlersBar.previousState;
		}
	},
	isShown : function(){
		if (config.options.chkDisableTabsBar) return false;
		if (!config.options.chkHideTabsBarWhenSingleTab) return true;
		var cpt=0;
		story.forEachTiddler(function(){cpt++});
		return (cpt>1);
	},
	selectNextTab : function(){  //used when the current tab is closed (to select another tab)
		var previous="";
		story.forEachTiddler(function(title){
			if (!config.macros.tiddlersBar.currentTiddler) {
				story.displayTiddler(null,title);
				return;
			}
			if (title==config.macros.tiddlersBar.currentTiddler) {
				if (previous) {
					story.displayTiddler(null,previous);
					return;
				}
				else config.macros.tiddlersBar.currentTiddler=""; 	// so next tab will be selected
			}
			else previous=title;
			});		
	},
	onSelectTab : function(e){
		var t = this.getAttribute("tiddler");
		if (t) story.displayTiddler(null,t);
		return false;
	},
	onTabClose : function(e){
		var t = this.getAttribute("tiddler");
		if (t) {
			if(story.hasChanges(t) && !readOnly) {
				if(!confirm(config.commands.cancelTiddler.warning.format([t])))
				return false;
			}
			story.closeTiddler(t);
		}
		return false;
	},
	onTabSave : function(e) {
		var t = this.getAttribute("tiddler");
		if (!e) e=window.event;
		if (t) config.commands.saveTiddler.handler(e,null,t);
		return false;
	},
	onSelectedTabButtonClick : function(event,src,title) {
		var t = this.getAttribute("tiddler");
		if (!event) event=window.event;
		if (t && config.options.txtSelectedTiddlerTabButton && config.commands[config.options.txtSelectedTiddlerTabButton])
			config.commands[config.options.txtSelectedTiddlerTabButton].handler(event, src, t);
		return false;
	},
	onTiddlersBarAction: function(event) {
		var source = event.target ? event.target.id : event.srcElement.id; // FF uses target and IE uses srcElement;
		if (source=="tiddlersBar") story.displayTiddler(null,'New Tiddler',DEFAULT_EDIT_TEMPLATE,false,null,null);
	},
	createActiveTabButton : function(place,title) {
		if (config.options.txtSelectedTiddlerTabButton && config.commands[config.options.txtSelectedTiddlerTabButton]) {
			var btn = createTiddlyButton(place, title, config.commands[config.options.txtSelectedTiddlerTabButton].tooltip ,config.macros.tiddlersBar.onSelectedTabButtonClick);
			btn.setAttribute("tiddler", title);
		}
		else
			createTiddlyText(place,title);
	}
}

story.coreCloseTiddler = story.coreCloseTiddler? story.coreCloseTiddler : story.closeTiddler;
story.coreDisplayTiddler = story.coreDisplayTiddler ? story.coreDisplayTiddler : story.displayTiddler;

story.closeTiddler = function(title,animate,unused) {
	if (title==config.macros.tiddlersBar.currentTiddler)
		config.macros.tiddlersBar.selectNextTab();
	story.coreCloseTiddler(title,false,unused); //disable animation to get it closed before calling tiddlersBar.refresh
	var e=document.getElementById("tiddlersBar");
	if (e) config.macros.tiddlersBar.refresh(e,null);
}

story.displayTiddler = function(srcElement,tiddler,template,animate,unused,customFields,toggle){
	story.coreDisplayTiddler(config.macros.tiddlersBar.tabsAnimationSource,tiddler,template,animate,unused,customFields,toggle);
	var title = (tiddler instanceof Tiddler)? tiddler.title : tiddler;  
	if (config.macros.tiddlersBar.isShown()) {
		story.forEachTiddler(function(t,e){
			if (t!=title) e.style.display="none";
			else e.style.display="";
		})
		config.macros.tiddlersBar.currentTiddler=title;
	}
	var e=document.getElementById("tiddlersBar");
	if (e) config.macros.tiddlersBar.refresh(e,null);
}

var coreRefreshPageTemplate = coreRefreshPageTemplate ? coreRefreshPageTemplate : refreshPageTemplate;
refreshPageTemplate = function(title) {
	coreRefreshPageTemplate(title);
	if (config.macros.tiddlersBar) config.macros.tiddlersBar.refresh(document.getElementById("tiddlersBar"));
}

ensureVisible=function (e) {return 0} //disable bottom scrolling (not useful now)

config.shadowTiddlers.StyleSheetTiddlersBar = "/*{{{*/\n";
config.shadowTiddlers.StyleSheetTiddlersBar += "#tiddlersBar .button {border:0}\n";
config.shadowTiddlers.StyleSheetTiddlersBar += "#tiddlersBar .tab {white-space:nowrap}\n";
config.shadowTiddlers.StyleSheetTiddlersBar += "#tiddlersBar {padding : 1em 0.5em 2px 0.5em}\n";
config.shadowTiddlers.StyleSheetTiddlersBar += ".tabUnselected .tabButton, .tabSelected .tabButton {padding : 0 2px 0 2px; margin: 0 0 0 4px;}\n";
config.shadowTiddlers.StyleSheetTiddlersBar += ".tiddler, .tabContents {border:1px [[ColorPalette::TertiaryPale]] solid;}\n";
config.shadowTiddlers.StyleSheetTiddlersBar +="/*}}}*/";
store.addNotification("StyleSheetTiddlersBar", refreshStyles);

config.refreshers.none = function(){return true;}
config.shadowTiddlers.PageTemplate=config.shadowTiddlers.PageTemplate.replace(/<div id='tiddlerDisplay'><\/div>/m,"<div id='tiddlersBar' refresh='none' ondblclick='config.macros.tiddlersBar.onTiddlersBarAction(event)'></div>\n<div id='tiddlerDisplay'></div>");

//}}}
|~ViewToolbar|closeTiddler closeOthers editTiddler > fields syncing permalink references jump|
|~EditToolbar|+saveTiddler -cancelTiddler deleteTiddler|
<!--{{{-->
<div class='toolbar' role='navigation' macro='toolbar [[ToolbarCommands::ViewToolbar]]'></div>
<div class='title' macro='view title'></div>
<!-- <div class='subtitle'><span macro='view modifier link'></span>, <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
<div class='tagging' macro='tagging'></div>
<div class='tagged' macro='tags'></div> -->
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
Copyright © 2018 [[Laboratoire de Genie Informatique et d'Automatique de l'Artois|http://www.lgi2a.univ-artois.fr]]. All Rights Reserved.