### Sim.js Simulation Setup and Execution Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/producers-consumers.md Initializes the Sim.js simulator, creates producer and consumer entities, starts the simulation, and reports buffer statistics. ```javascript // Create simulator var sim = new Sim.Sim(); // Create producer entities for (var i = 0; i < nProducers; i++) sim.addEntity(Producer); // Create consumer entities for (var i = 0; i < nConsumers; i++) sim.addEntity(Consumer); // Start simulation sim.simulate(SIMTIME); // statistics buffer.report(); ``` -------------------------------- ### Simulation Setup and Execution Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/buffet-restaurant.md Adds entities to the simulation, optionally sets a logger, starts the simulation, and returns key statistics. This is the final step to run the simulation. ```javascript sim.addEntity(Customer); sim.addEntity(Chef); sim.setLogger((msg) => { document.write(msg); }); sim.simulate(Simtime); return [stats.durationSeries.average(), stats.durationSeries.deviation(), stats.sizeSeries.average(), stats.sizeSeries.deviation()]; ``` -------------------------------- ### Define a Simple Entity Prototype Source: https://github.com/btelles/simjs-updated/blob/master/docs/entities.md This is a basic example of an Entity Prototype. It must include a start() function, which is called when the simulation begins. This function is essential for initializing entity state and scheduling future events. ```javascript class EntityPrototype extends Sim.Entity { start() { // This function is necessary! // This function is called by simulator when simulation starts. document.write("the simulation has started!"). } }; ``` -------------------------------- ### Customer Entity Start Function Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/buffet-restaurant.md Defines the start function for the Customer entity. It initiates an order and schedules the next customer arrival with an exponentially distributed delay. ```javascript class Customer extends Sim.Entity { start() { this.order(); var nextCustomerAt = random.exponential (1.0 / MeanArrival); this.setTimer(nextCustomerAt).done(this.start); }, ... ``` -------------------------------- ### Starting SIM.JS Simulation Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/traffic-lights.md Initiates the SIM.JS simulation for a predefined duration. `SIMTIME` should be a globally defined constant representing the simulation time. ```javascript // simulate for SIMTIME time sim.simulate(SIMTIME); ``` -------------------------------- ### Sim.Sim.simulate(duration) Source: https://github.com/btelles/simjs-updated/blob/master/docs/entities.md Starts the simulation process. The simulation will run until the specified duration is reached. ```APIDOC ## Sim.Sim.simulate(duration) ### Description Starts the simulation. `duration` is the time until which the simulation runs. ### Method POST (conceptual, as it's an SDK method) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **duration** (number) - Required - The time until which the simulation runs. ``` -------------------------------- ### Sim.Population Example Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md Demonstrates how to use Sim.Population to track population changes over time. Use enter() and leave() to record events, finalize() to mark the end of observations, and current(), sizeSeries.average(), and durationSeries.average() to retrieve statistics. ```javascript var motel0 = new Sim.Population("Motel 0"); motel0.enter(1600); // one person entered at 4:00 pm motel0:enter(1600); // second person entered at 4:00 pm motel0.leave(1600, 1601); // one person who entered at 4:00 pm, left at 4:01 pm motel0.enter(1630); // another person entered at 4:30 pm motel0.leave(1630, 1700); // person who entered at 4:30 pm left at 5:00 pm motel0.finalize(1700); // No more observations after this motel0.current(); // current population = 1 motel0.sizeSeries.average(); // average population in motel motel0.durationSeries.average(); // average stay duration in motel ``` -------------------------------- ### Sim.js Store Creation and Usage Example Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md Demonstrates how to create a Sim.js Store, put objects into it, and retrieve objects using both FIFO and filtered methods. Entities use the Entity Prototype API (putStore, getStore) to interact with stores. ```javascript // Create a store var store = new Sim.Store("Example Store", 10); class Entity extends Sim.Entity { start() { // Put an object this.putStore(store, {myfield: "myvalue"}); // Put another object this.putStore(store, {myfield: "othervalue"}); // arrays, numbers, strings etc can also be stored this.putStore(store, "stored string"); // Retrieve object from store. // Note 1: If filter function is not supplied, objects are returned in FIFO order // Note 2: The object can be accessed via this.callbackMessage this.getStore(store).done(() => { assert(this.callbackMessage.myfield === "myvalue"); }); // Retrieve object from store using filter function this.getStore(store, (obj) => obj === 'stored string') .done(() => assert(this.callbackMessage === "stored string")); } } ``` -------------------------------- ### Enable Simulation Logging Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/traffic-lights.md Add these lines before starting the simulation to enable logging and direct trace output to the web document. This helps in debugging and understanding simulation events. ```javascript // add these lines before starting simulation document.write("
");
sim.setLogger(function (str) {
document.write(str);
});
```
--------------------------------
### Ping-Pong Game Simulation with Sim.js
Source: https://github.com/btelles/simjs-updated/blob/master/docs/events.md
This example demonstrates how two entities, 'Jack' and 'Jill', simulate a ping-pong game by sending messages back and forth. It utilizes the `send()` function to transmit messages with a specified delay and includes the `onMessage` handler for receiving and responding to messages.
```javascript
class Player extends Sim.Entity{
start() {
if (this.firstServer) {
// Send the string to other player with delay = 0.
this.send("INITIAL", 0, this.opponent);
}
},
onMessage(sender, message) {
// Receive message, add own name and send back
var newMessage = message + this.name;
this.send(newMessage, HOLDTIME, sender);
}
};
var sim = new Sim.Sim();
var jack = sim.addEntity(Player);
var jill = sim.addEntity(Player);
jack.name = "Jack";
jill.name = "Jill";
jack.firstServer = true;
jack.opponent = jill;
sim.simulate(SIMTIME);
```
--------------------------------
### Sim.js Consumer Entity Model
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/producers-consumers.md
Models a consumer entity that retrieves tokens from a buffer and processes them. Consumers recursively call their start method after a consumption time to model continuous consumption.
```javascript
class Consumer extends Sim.Entity {
start() {
// Retrieve one token from buffer
this.getBuffer(buffer, 1).done(() => {
// After an item has been retrieved, wait for some time
// to model the consumption time.
// After the waiting period is over, we repeat by
// recursively calling this same function.
var timeToConsume = rand.exponential(1.0 / consumptionRate);
this.setTimer(timeToConsume).done(this.start);
});
}
}
```
--------------------------------
### Get Facility System Statistics
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Obtains population statistics for requests currently in the facility's system, which includes both waiting time in the queue and service time.
```javascript
const systemStats = myFacility.systemStats();
```
--------------------------------
### Load Complex Simulation Data
Source: https://github.com/btelles/simjs-updated/blob/master/ui/panel.html
Loads a more complex set of simulation elements, including multiple sources, splitters, and queues, from a JSON string. This allows for the setup of intricate simulation models.
```javascript
QueueApp.loadtext('[{"x":324,"y":158,"type":"splitter","name":"splitter_1","out":["queue_2","queue_1"],"model":{"prob":0.5}},{"x":315,"y":259,"type":"source","name":"source_5","out":"queue_1","model":{"lambda":0.5}},{"x":310,"y":68,"type":"source","name":"source_4","out":"queue_2","model":{"lambda":0.5}},{"x":162,"y":229,"type":"source","name":"source_3","out":"queue_4","model":{"lambda":0.5}},{"x":169,"y":125,"type":"source","name":"source_2","out":"queue_4","model":{"lambda":0.5}},{"x":5,"y":237,"type":"source","name":"source_1","out":"queue_3","model":{"lambda":0.5}},{"x":190,"y":165,"type":"queue","name":"queue_4","out":"splitter_1","model":{"nservers":1,"mu":1,"infinite":true,"maxqlen":0}},{"x":40,"y":165,"type":"queue","name":"queue_3","out":"queue_4","model":{"nservers":1,"mu":1,"infinite":true,"maxqlen":0}},{"x":362,"y":91,"type":"queue","name":"queue_2","model":{"nservers":1,"mu":1,"infinite":true,"maxqlen":0}},{"x":380,"y":212,"type":"queue","name":"queue_1","model":{"nservers":1,"mu":1,"infinite":true,"maxqlen":0}}]');
```
--------------------------------
### Sim.js Producer Entity Model
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/producers-consumers.md
Models a producer entity that generates tokens at a specified rate. Producers store items in a buffer and recursively call their start method to model continuous production.
```javascript
Random rand = new Random(SEED);
class Producer extends Sim.Entity {
start() {
var timeToProduce = rand.exponential(1.0 / productionRate);
// Set timer to self (models the time spend in production)
this.setTimer(timeToProduce).done(() => {
// Timer expires => item is ready to be stored in buffer.
// When the item is successfully stored in buffer, we repeat
// the process by recursively calling the same function.
this.putBuffer(buffer, 1).done(this.start);
});
}
}
```
--------------------------------
### Get Facility Queue Statistics
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Retrieves population statistics specifically for requests that are currently waiting in the facility's queue. This helps in analyzing queue length and waiting times.
```javascript
const queueStats = myFacility.queueStats();
```
--------------------------------
### Chained Request Modifications
Source: https://github.com/btelles/simjs-updated/blob/master/docs/request.md
Demonstrates chaining multiple modification functions on a Request object. Use this pattern for complex request setups involving completion callbacks, timeouts, event conditions, and custom data.
```javascript
this.putBuffer(buffer, 10)
.done(fnWhenSatisfied)
.done(fnAlsoWhenSatisfied)
.waitUntil(10, fnCouldNotAllocIn10Sec)
.unlessEvent(event1, fnEvent1Happened)
.unlessEvent(event2, fnEvent2Happened)
.setData('give me this data when ANY callback function is called');
```
--------------------------------
### Initialize and Run M/M/c Simulation
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Sets up and runs the M/M/c simulation, then reports statistics for the server facility.
```javascript
var sim = new Sim.Sim("M/M/c"); // create simulator
sim.addEntity(Customer); // add entity
sim.simulate(SIMTIME); // start simulation
server.report(); // statistics
```
--------------------------------
### Initialize and Load Sample Model
Source: https://github.com/btelles/simjs-updated/blob/master/queuing/queuing.html
Initializes the queuing application and loads a sample model when a link is clicked. It also handles displaying model-specific 'About' information.
```javascript
$(function () {
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
$('#accordion').accordion({autoHeight: false});
$('#about_this_model').accordion({collapsible: true, autoHeight: false}).hide();
$('#sample_models a').click(function (event) {
var id = $(this).attr('id');
var name = $(this).text();
var model = MODELS[id];
if (!model) return;
QueueApp.reset(true);
QueueApp.loadtext(model.model);
$('#about_this_model a').text('About this model [' + name + ']');
var a = $('#about_this_model');
a.show();
if (a.accordion('option', 'active') !== 0) {
a.accordion('option', 'active', 0);
}
$('.about_text').hide();
$('#about_' + id).show();
return false;
});
QueueApp.init();
});
```
--------------------------------
### Get Count of Observations
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Retrieve the total number of observations recorded.
```javascript
var count = queueSize.count();
```
--------------------------------
### Initialize and Load Sample Model
Source: https://github.com/btelles/simjs-updated/blob/master/queuing/index.html
Initializes the QueueApp, resets the simulation, and loads a selected sample model. It also handles displaying and updating the 'About this model' section.
```javascript
$(function () {
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
$('#accordion').accordion({autoHeight: false});
$('#about_this_model').accordion({collapsible: true, autoHeight: false}).hide();
$('#sample_models a').click(function (event) {
var id = $(this).attr('id');
var name = $(this).text();
var model = MODELS[id];
if (!model) return;
QueueApp.reset(true);
QueueApp.loadtext(model.model);
$('#about_this_model a').text('About this model [' + name + ']');
var a = $('#about_this_model');
a.show();
if (a.accordion('option', 'active') !== 0) {
a.accordion('option', 'active', 0);
}
$('.about_text').hide();
$('#about_' + id).show();
return false;
});
QueueApp.init();
});
```
--------------------------------
### Get Sum of Observation Values
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Retrieve the sum of all recorded observation values.
```javascript
var sumVal = queueSize.sum();
```
--------------------------------
### Initialize Simulator
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/traffic-lights.md
Create a new instance of the SIM.JS simulator.
```javascript
var sim = new Sim.Sim();
```
--------------------------------
### Get Variance of Observation Values
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Calculate and retrieve the variance of all recorded observation values.
```javascript
var varianceVal = queueSize.variance();
```
--------------------------------
### Get Maximum Observation Value
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Retrieve the maximum value recorded among all observations.
```javascript
var maxVal = queueSize.max();
```
--------------------------------
### Get Minimum Observation Value
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Retrieve the minimum value recorded among all observations.
```javascript
var minVal = queueSize.min();
```
--------------------------------
### Get Time-Averaged Observation Value
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Calculate and retrieve the time-averaged mean of all recorded observation values.
```javascript
var avgVal = queueSize.average();
```
--------------------------------
### Create Processor Sharing Facility
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Initializes a facility with the Processor Sharing (PS) discipline for modeling shared resources like a network cable.
```javascript
// create the facility
var network = new Sim.Facility("Network Cable", Sim.Facility.PS);
```
--------------------------------
### Create a Facility with Processor Sharing Discipline
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Instantiates a new facility using the Processor Sharing (PS) scheduling discipline. In this model, resources are shared among all active entities without a traditional queue.
```javascript
const myFacility = new Sim.Facility("SharedCPU", Sim.Facility.PS);
```
--------------------------------
### Get Standard Deviation of Observation Values
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Calculate and retrieve the standard deviation of all recorded observation values.
```javascript
var stdDev = queueSize.deviation();
```
--------------------------------
### Get Facility Usage Duration
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Retrieves the total duration for which the facility has been actively in use. This is useful for performance monitoring and analysis.
```javascript
const usageDuration = myFacility.usage();
```
--------------------------------
### Sim.Sim()
Source: https://github.com/btelles/simjs-updated/blob/master/docs/entities.md
Creates an instance of the discrete event simulator. This is the primary object for setting up and running a simulation.
```APIDOC
## Sim.Sim()
### Description
Creates an instance of discrete event simulator.
### Method
Constructor
### Endpoint
N/A
### Parameters
None
```
--------------------------------
### Initialize Population Statistics
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/traffic-lights.md
Create a SIM.JS Population object to record statistics about vehicles waiting at the intersection.
```javascript
var stats = new Sim.Population("Waiting at Intersection");
```
--------------------------------
### Get Histogram Data
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Retrieve the histogram data as a read-only array. The array includes counts for values below the lower bound, within each bucket, and above the upper bound.
```javascript
var histogramData = queueSize.getHistogram();
```
--------------------------------
### Get Histogram Data
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Retrieve the histogram data as a read-only array using getHistogram(). The array includes counts for values below the lower bound and above the upper bound.
```javascript
var histogramData = data.getHistogram();
```
--------------------------------
### Sim.Facility Constructor
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Creates a new facility resource with a given name and optional scheduling discipline and number of servers.
```APIDOC
## new Sim.Facility(name, discipline, numServers)
### Description
Creates a new facility resource. The `name` is used for statistics reporting. The `discipline` specifies the queuing policy, and `numServers` indicates the number of available servers (primarily used with FCFS).
### Parameters
#### Path Parameters
- **name** (string) - Required - Identifier for the facility used in reports.
- **discipline** (Sim.Facility.FCFS | Sim.Facility.LCFS | Sim.Facility.PS) - Optional - The scheduling discipline. Defaults to Sim.Facility.FCFS.
- **numServers** (number) - Optional - The number of servers available. Defaults to 1. Currently only used by Sim.Facility.FCFS.
```
--------------------------------
### Create a Facility with FCFS Discipline
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Instantiates a new facility using the default First Come First Served (FCFS) scheduling discipline. The facility is identified by its name and can have a specified number of servers.
```javascript
const myFacility = new Sim.Facility("BarberShop", Sim.Facility.FCFS, 3);
```
--------------------------------
### Model Simultaneous Resource Requests with Processor Sharing
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Demonstrates how entities make simultaneous requests to a Processor Sharing resource. Asserts the expected completion times based on the shared capacity.
```javascript
class Entity extends Sim.Entity {
start() {
// make request at time 0, to use network for 10 sec
this.useFacility(network, 10).done(() => {
assert(this.time(), 11);
});
// make request at time 5, to use the network for 1 sec
this.setTimer(5).done(() => {
this.useFacility(network, 1).done(() => {
assert(this.time(), 7);
});
});
}
};
var sim = new Sim.Sim();
sim.addEntity(Entity);
sim.simulate(100);
```
--------------------------------
### Create a Facility with LCFS Discipline
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Instantiates a new facility using the Last Come First Served (LCFS) scheduling discipline. This discipline allows the last arriving entity to preempt any currently using entity.
```javascript
const myFacility = new Sim.Facility("PrinterQueue", Sim.Facility.LCFS);
```
--------------------------------
### Create a Sim.js Buffer
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/producers-consumers.md
This snippet shows how to initialize a common buffer with a specified capacity in Sim.js. This buffer is used by both producers and consumers.
```javascript
var buffer = new Sim.Buffer("buffer", bufferSize);
```
--------------------------------
### Initialize and Load Simulation Data
Source: https://github.com/btelles/simjs-updated/blob/master/ui/panel.html
Initializes the QueueApp, resets its state, and loads simulation data from a JSON string. This is typically used to set up a new simulation environment.
```javascript
$(function () {
QueueApp.init();
QueueApp.reset();
QueueApp.loadtext('[{"x":384,"y":73,"type":"monitor","name":"monitor_1","model":null},{"x":156,"y":92,"type":"source","name":"source_1","out":"monitor_1","model":{"lambda":0.25}}]');
});
```
--------------------------------
### HTML Page for Buffet Restaurant Simulation
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/buffet-restaurant.md
This HTML snippet demonstrates how to include the simulation script files in a web page to run the buffet restaurant model.
```html
Tutorial: Customers at a Buffet Restaurant
```
--------------------------------
### Create DataSeries Objects
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Instantiate DataSeries objects to record and analyze observation sets. Provide a name for identification.
```javascript
var studentGrades = new Sim.DataSeries("Student Grades");
var riverLengths = new Sim.DataSeries("Length of Rivers in US");
```
--------------------------------
### SIM.JS Event Waiting and Callback Chaining
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/traffic-lights.md
Illustrates the pattern for requesting resources using `waitEvent`. It shows how to chain `setData`, `done`, `waitUntil`, and `unlessEvent` to handle event satisfaction and pass data to callbacks.
```javascript
this.waitEvent(event)
.setData('Data to all callback functions')
.done(fn1, this, 'data to fn1 only')
.done(fn2, this, 'data to fn2 only')
.waitUntil(fn3, this, 'data to fn3 only')
.unlessEvent(fn4, this, 'data to fn4 only');
fn1 = function(arg) {
assert(arg == 'data to fn1 only');
assert(this.callbackData == 'Data to all callback functions');
}
fn2 = function(arg) {
assert(arg == 'data to fn2 only');
assert(this.callbackData == 'Data to all callback functions');
}
```
--------------------------------
### SVN Checkout Latest Source Code
Source: https://github.com/btelles/simjs-updated/blob/master/docs/download.md
Use this command to anonymously check out the latest project source code from code.google.com.
```bash
svn checkout http://simjs-source.googlecode.com/svn/trunk/ simjs-source-read-only
```
--------------------------------
### Sim.DataSeries
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Initializes a new DataSeries object to record and analyze statistics. An optional name can be provided for identification in reports.
```APIDOC
## Sim.DataSeries()
### Description
Creates a new DataSeries object for recording and analyzing statistical data. An optional `name` parameter can be provided to identify the statistics in a report.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Constructor
`new Sim.DataSeries(name?: string)`
### Example
```javascript
var studentGrades = new Sim.DataSeries("Student Grades");
```
```
--------------------------------
### Customer Order Functionality
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/buffet-restaurant.md
Models the customer's actions: logging arrival, recording statistics, requesting from the buffer, using the cashier facility, and logging departure. Arrival time is stored for later use.
```javascript
order() {
// Logging
sim.log("Customer ENTER at " + this.time());
// statistics
stats.enter(this.time());
this.getBuffer(buffet, 1).done(() => {
// Logging
sim.log("Customer at CASHIER " + this.time()
+ " (entered at " + this.callbackData + ")");
var serviceTime = random.exponential(1.0 / CashierTime);
this.useFacility(cashier, serviceTime).done(() => {
// Logging
sim.log("Customer LEAVE at " + this.time()
+ " (entered at " + this.callbackData + ")");
// Statistics
stats.leave(this.callbackData, this.time());
}).setData(this.callbackData);
}).setData(this.time());
}
```
--------------------------------
### Initialize Random Number Generator
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/traffic-lights.md
Create a random number generator instance. SEED should be defined elsewhere.
```javascript
var random = new Random(SEED);
```
--------------------------------
### Initialize TimeSeries Objects
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Create new TimeSeries objects to record and analyze statistics for different observation sets. The 'name' parameter is optional and used for identification in reports.
```javascript
var queueSize = new Sim.TimeSeries("Queue Size");
var customers = new Sim.TimeSeries("Customers at Restaurant");
```
--------------------------------
### Adding SIM.JS Entities
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/traffic-lights.md
Demonstrates how to add entity prototypes to the SIM.JS simulator instance. Ensure entity prototypes are defined before calling this.
```javascript
sim.addEntity(LightController);
sim.addEntity(Traffic);
```
--------------------------------
### Simulate Wait and Queue Event Behavior
Source: https://github.com/btelles/simjs-updated/blob/master/docs/events.md
Demonstrates how entities use `waitEvent` and `queueEvent` with Sim.Event objects. Entities waiting on 'barrier' are all notified, while only one entity at a time is notified for 'funnel'. The master entity triggers both events after a delay.
```javascript
var barrier = new Sim.Event('Barrier');
var funnel = new Sim.Event('Funnel');
class Entity extends Sim.Entity {
start() {
this.waitEvent(barrier).done(() => {
document.write("This line is printed by all entities.");
});
this.queueEvent(funnel).done(() => {
document.write("This line is printed by one entity only");
});
if (this.master) {
this.setTimer(10)
.done(barrier.fire, barrier)
.done(funnel.fire, funnel);
}
}
}
var sim = new Sim.Sim();
var entities = [];
for (var i = 0; i < NUM_ENTITIES; i++) {
entities.push(sim.addEntity(Entity));
}
entities[0].master = true;
sim.simulate(SIMTIME);
```
--------------------------------
### Model Customer Arrival and Service
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Models customer arrivals with exponentially distributed intervals and service times. The customer uses the facility for a specified duration.
```javascript
var rand = new Sim.Random(SEED);
class Customer extends Sim.Entity {
start() {
// the next customer will arrive at:
var nextCustomerInterval = rand.exponential(lamda);
// wait for nextCustomerInterval
this.setTimer(nextCustomerInterval).done(() => {
// customer has arrived.
var useDuration = rand.exponential(mu); // time to use the server
this.useFacility(server, useDuration);
// repeat for the next customer
this.start();
});
}
}
```
--------------------------------
### Seeding and Multiple Random Streams
Source: https://github.com/btelles/simjs-updated/blob/master/docs/random.md
Demonstrates how to create multiple independent random number streams using Sim.Random with specific seeds. Each stream will produce a deterministic sequence of numbers.
```javascript
/* Demonstrate that random number streams can be seeded,
* and multiple streams can be created in a single script. */
var stream1 = new Sim.Random(1234);
var stream2 = new Sim.Random(6789);
stream1.random(); // returns 0.966453535715118 always
stream2.random(); // returns 0.13574991398490965 always
```
--------------------------------
### Sim.Random Class Constructor
Source: https://github.com/btelles/simjs-updated/blob/master/docs/random.md
Initializes a new random number stream using the Mersenne Twister algorithm. An optional seed can be provided to ensure reproducible random sequences.
```APIDOC
## Sim.Random()
### Description
Initializes a new random number stream. If no seed is provided, the current time is used.
### Arguments
* **seed** (integer) - An optional seed value. If this argument is not provided, then the seed value is set to `new Date().getTime()`.
```
--------------------------------
### Event-Based Simulation Design Pattern with Callback
Source: https://github.com/btelles/simjs-updated/blob/master/docs/basics.md
An event-based approach to discrete event simulation using callbacks. Actions are encapsulated in functions invoked upon event completion.
```python
entity::
do_some_local_computation
request_some_shared_resource_with_callback(entity_get_resource)
return
entity_get_resource (resource)::
do_more_local_computation
```
--------------------------------
### Run Traffic Light Simulation
Source: https://github.com/btelles/simjs-updated/blob/master/docs/_static/traffic_lights.html
Executes the traffic light simulation when the 'run_simulation' button is clicked. It reads input values for green time, mean arrival, seed, and simulation time, then displays the simulation results.
```javascript
$(function () {
$("#run_simulation").click(function () {
var green_time = parseFloat($('\\[name="GREEN_TIME"\\]').val());
var mean_arrival = parseFloat($('\\[name="MEAN_ARRIVAL"\\]').val());
var seed = parseFloat($('\\[name="SEED"\\]').val());
var simtime = parseFloat($('\\[name="SIMTIME"\\]').val());
var results = trafficLightSimulation(green_time, mean_arrival, seed, simtime);
var msg = "Simulation Results for [" +
"Green Time = " + green_time + ", Mean Arrival = " + mean_arrival + ", Seed = " + seed + ", Simulation time = " + simtime + "]
" +
"Average time waiting at intersection (min) = " + results[0].toFixed(4) + "
" +
"Average number of vehicles waiting at intersection = " + results[2].toFixed(4) + "
";
$(".results").append(msg);
});
});
```
--------------------------------
### useFacility(facility, duration)
Source: https://github.com/btelles/simjs-updated/blob/master/docs/entities.md
Requests to use a facility for a specified duration.
```APIDOC
## useFacility(facility, duration)
### Description
Request to use the `facility` for `duration` duration.
### Method
(Not specified, likely a function call)
### Parameters
* **facility** (Facility) - The facility to use.
* **duration** (number) - The duration for which to use the facility.
### Returns
A [Request](request.md#request-main) object.
```
--------------------------------
### Sim.TimeSeries Class
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Initializes a new TimeSeries object to record and analyze statistics. An optional name can be provided for identification in reports.
```APIDOC
## Sim.TimeSeries()
### Description
Creates a new instance of the TimeSeries class.
### Parameters
* **name** (string) - Optional - A name to identify the statistics in a report.
```
--------------------------------
### Create M/M/c Queue Facility
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Defines a facility for an M/M/c queue using FCFS discipline.
```javascript
var server = new Sim.Facility('Server', Sim.Facility.FCFS, nServers);
```
--------------------------------
### Set Up Histogram for Value Frequency
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Prepare a histogram to record the frequency of occurrence of values within a specified range and number of buckets. This should be called before recording values for the histogram to be effective.
```javascript
queueSize.setHistogram(0, 10, 10); // 10 buckets from 0 to 10
```
--------------------------------
### Prepare Histogram for Frequency Recording
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Use setHistogram() before recording values to create a histogram. This defines the range and number of buckets for frequency analysis. Existing histograms are replaced.
```javascript
var data = new Sim.DataSeries('Simple Data');
data.setHistogram(0, 100, 10);
```
--------------------------------
### Run Buffet Restaurant Simulation
Source: https://github.com/btelles/simjs-updated/blob/master/docs/_static/buffet_restaurant.html
Handles the click event for the 'Run Simulation' button. It collects simulation parameters from input fields, calls the simulation function, and appends the formatted results to the page.
```javascript
$(function () {
$("#run_simulation").click(function () {
var BuffetCapacity = parseFloat($('\\[name="BuffetCapacity"\\]').val());
var PreparationTime = parseFloat($('\\[name="PreparationTime"\\]').val());
var MeanArrival = parseFloat($('\\[name="MeanArrival"\\]').val());
var CashierTime = parseFloat($('\\[name="CashierTime"\\]').val());
var Seed = parseFloat($('\\[name="Seed"\\]').val());
var Simtime = parseFloat($('\\[name="Simtime"\\]').val());
var results = buffetRestaurantSimulation( BuffetCapacity, PreparationTime, MeanArrival, CashierTime, Seed, Simtime);
var msg = "Simulation Results for \\[" + "Buffet Capacity = " + BuffetCapacity + ", Preparation Time = " + PreparationTime + ", Mean Arrival = " + MeanArrival + ", Mean Cashier time = " + CashierTime + ", Seed = " + Seed + ", Sim time = " + Simtime + \\]
" +
"Average time spent at restaurant (min) = " + results\[0\].toFixed(4) + "
Average number of customers in restaurant = " + results\[2\].toFixed(4) + "
";
$(".results").append(msg);
});
$("#clear_result").click(function () {
$(".results").html('Clear
');
});
});
```
--------------------------------
### Sim.Facility.systemStats
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Retrieves population statistics for requests currently in the system (both waiting and being serviced).
```APIDOC
## Sim.Facility.systemStats()
### Description
Returns population statistics for all requests associated with this facility, including those waiting in the queue and those currently being serviced.
### Returns
- [Population](statistics.md#statistics-population) statistics object for requests in the system.
```
--------------------------------
### useFacility
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Requests to use a facility for a specified duration. This method is part of the Extended Entity Prototype API.
```APIDOC
## useFacility(facility, duration)
### Description
Requests to use the specified *facility* for a given *duration*.
### Method
`useFacility`
### Parameters
#### Path Parameters
- **facility** (Sim.Facility) - Required - The facility to use.
- **duration** (number) - Required - The time duration for which to use the facility.
### Returns
- [Request](request.md#request-main) object representing the request to use the facility.
```
--------------------------------
### Include Simulation Scripts in HTML
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/traffic-lights.md
Include these script tags in your HTML file to load the Sim.js library and the traffic light simulation code.
```html
Tutorial: Simulation of Traffic Lights at Intersection
```
--------------------------------
### Sim.Facility.usage
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Returns the total duration for which the facility has been in use.
```APIDOC
## Sim.Facility.usage()
### Description
Returns the cumulative duration that this facility has been actively used.
### Returns
- **duration** (number) - The total time the facility has been in use.
```
--------------------------------
### Record Observations with Optional Weights
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Use the record() function to add observations to a DataSeries. An optional weight parameter can adjust the observation's influence.
```javascript
studentGrades.record(3.0);
riverLengths.record(2320.0);
experimentData.record(1.5, 0.8);
```
--------------------------------
### getStore(store)
Source: https://github.com/btelles/simjs-updated/blob/master/docs/entities.md
Requests to retrieve an object from a store, optionally matching a filter.
```APIDOC
## getStore(store)
### Description
Request to retrieve object from the `store`.
### Method
(Not specified, likely a function call)
### Parameters
* **store** (Store) - The store to retrieve the object from.
* **filter** (function, optional) - A filter function to match the object. If supplied, the first object matching the filter is retrieved. Otherwise, the first object in FIFO order is retrieved.
### Returns
A [Request](request.md#request-main) object. The retrieved object can be accessed via the `this.callbackMessage` attribute in the callback function.
```
--------------------------------
### Create Traffic Light Events
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/traffic-lights.md
Instantiate two SIM.JS Events to represent the North-South and East-West traffic lights.
```javascript
var trafficLights = [new Sim.Event("North-South Light"),
new Sim.Event("East-West Light")];
```
--------------------------------
### Sim.Request.done(callback)
Source: https://github.com/btelles/simjs-updated/blob/master/docs/request.md
Registers a callback function to be executed when the request is satisfied. Multiple callbacks can be added and will be executed in order. The callback is invoked after the current function scope finishes.
```APIDOC
## Sim.Request.done(callback)
### Description
Registers a callback function to be executed when the request is satisfied. If multiple callbacks are registered, they are called in the order they were added. The callback is invoked after the function scope that initiated the request has completed.
### Method Signature
`done(callback, context, argument)`
### Parameters
#### callback
- **callback** (function) - Required - The function to call when the request is satisfied.
- **context** (object) - Optional - The object in whose context the callback will be called. Defaults to the calling entity if not provided.
- **argument** (any | array) - Optional - Arguments to pass to the callback. If an array, `apply` is used; otherwise, `call` is used.
### Notes
- This function can be called multiple times for the same request object.
- If not called, other callbacks like `waitUntil` or `unlessEvent` may still be invoked.
- Callbacks are executed after the current function scope finishes, even if the request is immediately satisfied.
```
--------------------------------
### putStore(store, object)
Source: https://github.com/btelles/simjs-updated/blob/master/docs/entities.md
Requests to store an object in a store.
```APIDOC
## putStore(store, object)
### Description
Request to store `object` in the `store`.
### Method
(Not specified, likely a function call)
### Parameters
* **store** (Store) - The store to put the object into.
* **object** (any) - The object to store. Can be any JavaScript value.
### Returns
A [Request](request.md#request-main) object.
```
--------------------------------
### Global Variables for SIM.JS Simulation
Source: https://github.com/btelles/simjs-updated/blob/master/docs/examples/buffet-restaurant.md
Declare and initialize global variables required for the simulation, including the simulation object, statistics tracker, resources (facility and buffer), and random number generator.
```javascript
var sim = new Sim.Sim();
var stats = new Sim.Population();
var cashier = new Sim.Facility('Cashier');
var buffet = new Sim.Buffer('Buffet', BuffetCapacity);
var random = new Random(Seed);
```
--------------------------------
### Sim.Sim.addEntity(entityPrototype)
Source: https://github.com/btelles/simjs-updated/blob/master/docs/entities.md
Adds an entity to the simulation environment. The entity object inherits from the provided entityPrototype. The simulator also augments the prototype with additional API functions.
```APIDOC
## Sim.Sim.addEntity(entityPrototype)
### Description
Adds an entity in the simulation environment. The entity object inherits from the `entityPrototype` object. The simulator also adds several other API function in the prototype. See [Sim.Entity](#entity-entity) for further details.
### Method
POST (conceptual, as it's an SDK method)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **entityPrototype** (object) - Required - The prototype object for the entity to be added.
```
--------------------------------
### Calculate Statistics for a Data Series
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
After recording observations, use methods like count(), min(), max(), sum(), average(), deviation(), and variance() to analyze the data. The range() method is also available.
```javascript
var data = new Sim.DataSeries('Simple Data');
for (var i = 1; i <= 100; i++) {
data.record(i);
}
data.count(); // = 100
data.min(); // = 1.0
data.max(); // = 100.0
data.range(); // = 99.0
data.sum(); // = 5050.0
data.average(); // 50.5
data.deviation(); // = 28.86607004772212
data.variance(); // = 833.25
```
--------------------------------
### Instantiate Entity Objects
Source: https://github.com/btelles/simjs-updated/blob/master/docs/entities.md
Use the Sim.Sim.addEntity() function to create runtime entity objects from an Entity Prototype. Multiple entity objects can be instantiated from the same prototype.
```javascript
// Create entity object from the entity prototype object
var entityObject = sim.addEntity(EntityPrototype);
// More than one entity objects can be created by same entity prototype object
var anotherEntityObject = sim.addEntity(EntityPrototype);
```
--------------------------------
### Create a Sim.Event Object
Source: https://github.com/btelles/simjs-updated/blob/master/docs/events.md
Creates a new Sim.Event object. The optional name parameter is used for statistics and tracing.
```javascript
var event = new Sim.Event(name)
```
--------------------------------
### Sim.Population.enter(timestamp)
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Records the entry of a new entity into the system at a specified timestamp. This increments the population count.
```APIDOC
## Sim.Population.enter(timestamp)
### Description
An entity has entered the system at `timestamp`.
### Method
POST
### Endpoint
N/A (Method call on an object)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **timestamp** (number) - Required - The time at which the entity entered the system.
### Request Example
```json
{
"timestamp": 1600
}
```
### Response
#### Success Response (200)
- **message** (string) - Indicates successful recording of the entry.
```
--------------------------------
### Sim.Population.current()
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Retrieves the current population count of the system. This method returns the number of entities currently present in the system.
```APIDOC
## Sim.Population.current()
### Description
The current population of the system.
### Method
GET
### Endpoint
N/A (Method call on an object)
### Response
#### Success Response (200)
- **population** (integer) - The current number of entities in the system.
```
--------------------------------
### Sim.Facility.queueStats
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
Retrieves population statistics for requests currently waiting in the facility's queue.
```APIDOC
## Sim.Facility.queueStats()
### Description
Returns population statistics for requests that are currently waiting in the queue for this facility.
### Returns
- [Population](statistics.md#statistics-population) statistics object for requests in the queue.
```
--------------------------------
### Request Facility Usage
Source: https://github.com/btelles/simjs-updated/blob/master/docs/resources.md
An entity requests to use a specified facility for a given duration. This method returns a Request object, allowing for tracking and potential cancellation while the entity is waiting.
```javascript
const request = entity.useFacility(myFacility, 10.0);
```
--------------------------------
### Process-Based Simulation Design Pattern
Source: https://github.com/btelles/simjs-updated/blob/master/docs/basics.md
A common design pattern for process-based discrete event simulations. Entities may block when requesting shared resources.
```python
1. entity::
2. do_some_local_computation
3. resource = request_some_shared_resource
4. do_more_local_computation
```
--------------------------------
### Sim.Population.leave(enteredAt, leaveAt)
Source: https://github.com/btelles/simjs-updated/blob/master/docs/statistics.md
Records the departure of an entity from the system. It requires the timestamp when the entity entered and when it left.
```APIDOC
## Sim.Population.leave(enteredAt, leaveAt)
### Description
An entity that entered the system at `enteredAt` will leave at `leaveAt`.
### Method
POST
### Endpoint
N/A (Method call on an object)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **enteredAt** (number) - Required - The timestamp when the entity entered the system.
- **leaveAt** (number) - Required - The timestamp when the entity left the system.
### Request Example
```json
{
"enteredAt": 1600,
"leaveAt": 1601
}
```
### Response
#### Success Response (200)
- **message** (string) - Indicates successful recording of the departure.
```
--------------------------------
### Handling Request Completion with done()
Source: https://github.com/btelles/simjs-updated/blob/master/docs/request.md
Use `done()` to specify a callback function that executes when a request is satisfied. The callback can be called with a specific context and arguments. Multiple callbacks can be added and will be executed in order.
```javascript
this.putBuffer(buffer, 10)
.unlessEvent(event, handleEvent)
.waitUntil(event, handleTimeout);
```
```javascript
this.putBuffer(buffer, 0).done(function () {
document.write("I will be printed as second line.");
});
document.write("I will be printed as first line.");
```
--------------------------------
### putBuffer(buffer, amount)
Source: https://github.com/btelles/simjs-updated/blob/master/docs/entities.md
Requests to put a specified amount of tokens into a buffer.
```APIDOC
## putBuffer(buffer, amount)
### Description
Request to put `amount` quantity of tokens in the `buffer`.
### Method
(Not specified, likely a function call)
### Parameters
* **buffer** (Buffer) - The buffer to put tokens into.
* **amount** (number) - The quantity of tokens to put.
### Returns
A [Request](request.md#request-main) object.
```
--------------------------------
### Extending Layout Template
Source: https://github.com/btelles/simjs-updated/blob/master/docs/_templates/layout.html
This Jinja template code shows how to extend the base layout and override the 'extrahead' and 'footer' blocks to add custom content.
```html
{% extends "!layout.html" %}
{%- block extrahead %} {{ super() }} var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-24240723-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
{% endblock %}
{% block footer %} {{ super() }}
{% endblock %}
```
--------------------------------
### Sim.Sim.log(message)
Source: https://github.com/btelles/simjs-updated/blob/master/docs/entities.md
Logs a message using the currently assigned logger function. If no logger is set, the message may not be displayed.
```APIDOC
## Sim.Sim.log(message)
### Description
Logs a message using a logger function defined in `setLogger()`.
### Method
POST (conceptual, as it's an SDK method)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **message** (string) - Required - The message to be logged.
```