Advanced Trajectory Usage

Iñaki Ucar, Bart Smeets



Interaction with the environment

Many activities accept functions as arguments to be evaluated dynamically during the simulation. Those functions may interact with the environment to extract parameters of interest such as the current simulation time (see ?now), status of resources (see ?get_capacity), status of generators (see ?get_n_generated), or directly to gather the history of monitored values (see ?get_mon). The only requirement is that the simulation environment must be in the scope of the trajectory.

Therefore, this will not work:

t <- trajectory() %>%
  log_(function() as.character(now(env)))

env <- simmer() %>%
  add_generator("dummy", t, function() 1) %>%
#> 1: dummy0: 2.50175860496223
#> 2: dummy1: 2.50175860496223
#> 3: dummy2: 2.50175860496223

because the global env is not available at runtime: the simulation runs and then the resulting object is assigned to env. For env to be in the scope of t during this simulation, it is enough to detach the run() method from the definition pipe:

t <- trajectory() %>%
  log_(function() as.character(now(env)))

env <- simmer() %>%
  add_generator("dummy", t, function() 1)

env %>% run(4) %>% invisible
#> 1: dummy0: 1
#> 2: dummy1: 2
#> 3: dummy2: 3

And we get the expected output. However, as a general rule of good practice, it is recommended to instantiate the environment always in the first place to avoid possible mistakes, and because the code becomes more readable:

# First, instantiate the environment
env <- simmer()

# Here I'm using it
t <- trajectory() %>%
  log_(function() as.character(now(env)))

# And finally, run it
env %>%
  add_generator("dummy", t, function() 1) %>%
  run(4) %>% invisible
#> 1: dummy0: 1
#> 2: dummy1: 2
#> 3: dummy2: 3

Available set of activities

When a generator creates an arrival, it couples the arrival to a given trajectory. A trajectory is defined as an interlinkage of activities which together form the arrivals’ lifetime in the system. Once an arrival is coupled to the trajectory, it will (in general) start processing the activities in the trajectory in the specified order and, eventually, leave the system. Consider the following:

patient_traj <- trajectory(name = "patient_trajectory") %>%
  seize(resource = "doctor", amount = 1) %>%
  timeout(task = 3) %>%
  release(resource = "doctor", amount = 1)

Here we create a trajectory where a patient seizes a doctor for 3 minutes and then releases him again. This is a very straightforward example, however, most of the trajectory-related functions allow for more advanced usage. The different functions are introduced below.

Additionally, you may want to try the simmer.bricks package, a plugin for simmer which provides helper methods for trajectories. Each brick wraps a common activity pattern that can be used to build trajectories more conveniently (see the Introduction to simmer.bricks).


The log_(., message, level) method just prints a given message preceded by the simulation time and the name of the arrival, for debugging purposes. The logging level is defined in the simulation environment:

set_attribute(), set_global()

The set_attribute(., keys, values) method sets the values of an arrival’s attributes keys. Both keys and values can be vectors (and their lengths must match) or functions returning vectors. But either way, the values stored can only be numeric.

Above, a trajectory which only sets attribute my_key to value 123 is launched once by an arrival generated at time 0 (check ?at). The mon=2 of add_generator() makes the simulation environment monitor the attributes’ evolution (disabled by default). Using get_mon_attributes(), we can look at the evolution of the value of my_key.

If you want to set an attribute that depends on another attribute, or on the current value of the attribute to be set, this is also possible. Attributes can be retrieved inside user-supplied functions using get_attribute(., keys). Below, you can see an example of this in practice.

Attributes are per arrival, meaning that each arrival has its own set of attributes, not visible by anyone else:

Thus, the reader in the example above returns NA, missing. However, attributes can also be global with set_global(., keys, values):

As shown above, global attributes are reported in get_mon_attributes() as unnamed key/value pairs.

timeout(), timeout_from_attribute()

At its simplest, the timeout(., task) method delays the arrival’s advance through the trajectory for a specified amount of time. Consider the following minimal example where we simply supply a static value to the timeout’s task parameter.

Often, however, you want a timeout to be dependent on a distribution or, for example, an earlier set attribute. This is achieved by passing a function to the task parameter, as we explained before, and using get_attribute(.). In the following example, this functionality is demonstrated:

Be aware that if you want the timeout()’s task parameter to be evaluated dynamically, you should supply a callable function. For example in timeout(function() rexp(1, 10)), rexp(1, 10) will be evaluated every time the timeout activity is executed. However, if you supply it in the form of timeout(rexp(1, 10)), it will only be evaluated at the initalization and will remain static after that.

Of course, this task, supplied as a function, may be as complex as you need and, for instance, it may check a resource’s status, interact with other entities in your simulation model… The same applies to all the activities when they accept a function as a parameter.

If you simply need a delay previously set as an attribute, you may use timeout_from_attribute(., key) (or timeout_from_global(., key) for a global attribute). Thus, the following timeouts are equivalent, but the second one is much simpler and faster:

seize(), release()

The seize(., resource, amount) method seizes a specified amount of the resource named resource. Conversely, the release(., resource, amount) method releases a specified amount of the resource named resource. Be aware that, in order to use these functions in relation to a specific resource, you have to create it in your definition of the simulation environment (check ?add_resource).

Consider the following example:

Here the mon=1 argument (=default) of add_resource() makes the simulation environment monitor the resource usage. Using the get_mon_resources(env) method you can get access to the log of the usage evolution of resources.

There are situations where you want to let the amount of resources seized/released be dependent on a specific function or on a previously set attribute. To achieve this, you can pass a function to the amount parameter instead of a numeric value and use get_attribute(.):

By default, an unsuccessful seize() results in the rejection of the arrival. In the following example, the second patient tries to seize the only doctor while the first patient is being attended. There is no waiting room available, therefore it is rejected:

Sometimes, you don’t want to reject an unsuccessful seize(), but to follow another path. Let’s modify the example above to enable the second patient to visit a nurse instead:

The flag continue indicates whether the reject sub-trajectory should be connected to the main trajectory or not. In this case, with continue=FALSE, the rejected arrival seizes the nurse and its lifetime ends after releasing him/her. Otherwise, it would keep executing activities in the main trajectory.

Note that the second patient may also keep trying if he/she must see the doctor:

There is another optional sub-trajectory called post.seize and, as its name suggests, it is executed after a successful seize(). Thus, you can do the following:

set_capacity(), set_queue_size()

The set_capacity(., resource, value) method modifies the capacity of the specified resource by name, and the set_queue_size(., resource, value) method modifies its queue size. Be aware that, in order to use these functions in relation to a specific resource, you have to create it in your definition of the simulation environment (check ?add_resource). You can supply the value parameter either as a numeric value or as a function which must return a numeric value.

These activities are interesting to introduce dynamical changes in the resources. For instance, consider the following example in which two trajectories fight for the capacity of their resource:


seize(), release(), set_capacity() and set_queue_size() work well when you know the resources implied beforehand. But sometimes the resource to choose may depend on a certain policy. For these situations, the select(., resources, policy, id) method offers the possibility of selecting a resource at any point, and this choice will be observed by seize_selected(), release_selected(), set_capacity_selected() and set_queue_size_selected():

If you provide select() with resources as a vector of names, you can use one of the predefined policies (see ?select). If you need some custom policy, you can define it and supply it as a function. For instance, let’s pick a resource based on a previously set attribute:

patient_traj <- trajectory(name = "patient_trajectory") %>%
  set_attribute("resource", function() sample(1:3, 1)) %>%
  select(resources = function() paste0("doctor", get_attribute(env, "resource"))) %>%
  seize_selected(amount = 1) %>%
  timeout(5) %>%
  release_selected(amount = 1)

env <- simmer() %>%
  add_resource("doctor1", capacity = 1) %>%
  add_resource("doctor2", capacity = 1) %>%
  add_resource("doctor3", capacity = 1) %>%
  add_generator("patient", patient_traj, at(0, 1, 2), mon = 2)
env %>% run()
#> simmer environment: anonymous | now: 10 | next: 
#> { Monitor: in memory }
#> { Resource: doctor1 | monitored: TRUE | server status: 0(1) | queue status: 0(Inf) }
#> { Resource: doctor2 | monitored: TRUE | server status: 0(1) | queue status: 0(Inf) }
#> { Resource: doctor3 | monitored: TRUE | server status: 0(1) | queue status: 0(Inf) }
#> { Source: patient | monitored: 2 | n_generated: 3 }

#>   time     name      key value replication
#> 1    0 patient0 resource     3           1
#> 2    1 patient1 resource     3           1
#> 3    2 patient2 resource     2           1
#>       name start_time end_time activity_time finished replication
#> 1 patient0          0        5             5     TRUE           1
#> 2 patient2          2        7             5     TRUE           1
#> 3 patient1          1       10             5     TRUE           1
#>   resource time server queue capacity queue_size system limit replication
#> 1  doctor3    0      1     0        1        Inf      1   Inf           1
#> 2  doctor3    1      1     1        1        Inf      2   Inf           1
#> 3  doctor2    2      1     0        1        Inf      1   Inf           1
#> 4  doctor3    5      1     0        1        Inf      1   Inf           1
#> 5  doctor2    7      0     0        1        Inf      0   Inf           1
#> 6  doctor3   10      0     0        1        Inf      0   Inf           1

And, of course, everything learned for seize(), release(), set_capacity() and set_queue_size() applies to all their _selected versions.

activate(), deactivate()

The activate(., source) and deactivate(., source) methods are able to start or stop, respectively, a source by name. This name can be supplied as either a string or a function returning a string. In the following simple example, the use of these methods spreads the interarrival times which otherwise would be of 1 unit of time, as defined in the source:

set_trajectory(), set_source()

The set_trajectory(., source, trajectory) and set_source(., source, object) methods are able to install a new trajectory or source object (function or data frame, depending on the source type), respectively, in a source by name. This name can be supplied as either a string or a function returning a string.

In the following distribution, t2 changes the distribution and then switches to t1, so that only the first arrival takes t2:


The add_generator() method assigns a set of prioritization values to each generated arrival: by default, priority=0, preemptible=priority, restart=FALSE (see ?add_generator for more details). The set_prioritization(., values) method can change those values with more granularity at any point in the trajectory, and they can also be retrieved inside the trajectory using get_prioritization(.):

More details on prioritization in the Advanced Resource Usage vignette (pending).


The branch(., option, continue, ...) method offers the possibility of adding alternative paths in the trajectory. The following example shows how a trajectory can be built with a 50-50 chance for an arrival to pass through each path of a two-path branch.

When an arrival gets to the branch, the first argument is evaluated to select a specific path to follow, so it must be callable and must return a numeric value between 1 and n, where n is the number of paths defined. The second argument, continue, indicates whether the arrival must continue executing the activities after the selected path or not. In the example above, only the first path continues to the last release().

Sometimes you may need to count how many times a certain trajectory in a certain branch is entered, or how much time arrivals spend inside that trajectory. For these situations, it is handy to use resources with infinite capacity just for accounting purposes, like in the example below.


The rollback(., amount, times, check) method allows an arrival to rollback the trajectory an amount number of steps.

Consider the following where a string is printed in the timeout function. After the first run, the trajectory is rolled back 3 times (so that it prints “Hello!” four times).

The rollback() method also accepts an optional check parameter which overrides the default amount-based behaviour. This parameter must be a function that returns a logical value. Each time an arrival reaches the activity, this check is evaluated to determine whether the rollback() with amount steps must be performed or not. Consider the following example:


The leave(., prob) method allows an arrival to leave the trajectory with some probability:

And of course, this probability may be evaluated dynamically also:

clone(), synchronize()

The clone(., n, ...) method offers the possibility of replicating an arrival n-1 times to be processed through up to n sub-trajectories in parallel. Then, the synchronize(., wait, mon_all) method synchronizes and removes replicas. By default, synchronize() waits for all of the replicas to arrive and allows the last one to continue:

Note that the parameter n may also be a function. If there are more sub-trajectories than clones, the extra ones are ignored. If there are less sub-trajectories than clones, some clones will continue to the next activity directly:

The behaviour of synchronize() can be modified in order to let the first clone pass and remove the others by setting wait=FALSE:

By default, synchronize() does not record information about the clones removed (mon_all=FALSE). However, if it is required, you can get it by setting mon_all=TRUE:

batch(), separate()

The batch(., n, timeout, permanent, name, rule) method offers the possibility of collecting a number of arrivals before they can continue processing as a block. Then, the separate(.) method splits a previously established non-permanent batch. This allows us to implement a rollercoaster process, for instance.

Let us consider a rollercoaster, with up to 10 places and a queue of 20 people, that lasts 5 minutes. We can model this problem as follows:

We can see above that 3 batches have been created. The first 10 people arrive within 3.8 minutes and goes into the rollercoaster. When the ride ends, at 8.8, there are only 6 people waiting, but the batch() timer (timeout=5) has run out, and another ride starts with them. These batches are non-permanent (permanent=FALSE), so that separate() can split them and people can go their separate ways.

The optional argument rule accepts a function to perform a fine-grained selection of which arrivals should be batched. For each particular arrival, it is batched if the function returns TRUE, or it simply continues otherwise. For instance, in the example above, we can prevent batching by returning always FALSE:

By default, batches are unnamed (name=""), which makes them independent of one another. However, it may be interesting to feed a common batch from different trajectories. For instance, we can try this:

But we don’t get the expected output because the arrivals are feeding two different batches. The arrival following t1 join t0 after the timeout, but effectively this is a clone of t0, which means that the above definition is equivalent to the following:

Thus, arrivals following a different trajectory will end up in a different batch in general. Nonetheless, there is one way to share a common batch across batch() activities. This can be done by using a common name:

Or, equivalently,

send(), trap(), untrap(), wait()

These activities enable asynchronous programming. The send(., signals, delay) method broadcasts a signal or a list of signals to all the arrivals subscribed to them. Signals can be triggered immediately:

or after some delay:

Note that both arguments, signals and delay, can be functions, and therefore they can retrieve the arrival’s attributes.

This is not very useful if nobody is listening. Arrivals can subscribe to signals and (optionally) assign a handler with the trap(., signals, handler, interruptible). In the following example, an arrival subscribes to a signal and blocks until its reception using the wait(.) method.

Note that signals are ignored when an arrival is waiting in a resource’s queue. The same applies inside a batch: all the signals subscribed before entering the batch are ignored. Thus, the following batch will block indifinitely:

Upon a signal reception, the arrival stops the current activity and executes the handler if provided. Then, the execution returns to the activity following the point of the interruption:

Finally, the untrap(., signals) method can be used to unsubscribe from signals:

Signal handlers can be interrupted as well by default, meaning that a handler may keep restarting if there are frequent enough signals:

If an uninterruptible handler is needed, this can be achieved by setting the proper flag:

renege_in(), renege_if(), renege_abort()

The renege_in(., t, out) method offers the possibility of setting a timeout after which the arrival will abandon the trajectory. After reneging, the arrival can follow an optional sub-trajectory out. The renege_abort(.) method cancels the latter. Together, they allows us, for instance, to model arrivals with limited patience. In the example below, customer1 arrives at the bank, where there is only one busy clerk. He/she waits in the queue for 5 minutes and then leaves.

The same can be achieved with renege_if(., signal, out) if customer0 sends a signal to customer1 at t=5:

Note that, in contrast to trap(), reneging is triggered even if the arrival is in a queue or is part of a non-permanent batch.

Trajectory toolbox: joining and subsetting


The join(...) method is very useful to concatenate together any number of trajectories. It may be used as a standalone function as follows:

Or it may operate inline, like another activity:

[, [[

You can think about a trajectory object as a list of activities that has a length

and can be subset using the standard operator [. For instance, you can select the activities you want with a logical vector:

Or a set of indices that respect the order given:

Or a set of indices to remove from the selection:

Or by name, but note that this does not respect the order given though, because it performs a match:

If you provide no indices, the whole trajectory is returned:

In fact, you are cloning the trajectory with the latter command. It is equivalent to t0[1:length(t0)] or join(t0).

The generics head() and tail() use the [ operator under the hood, thus you can use them as well:

The [[ operator can also be used to extract only one element:

which is equivalent to t0[2]. If a string is provided, it ensures that only the first match is returned: