Skip to content

FAQ: How to use map() and mapaccum() to speed up calculations?

András Retzler edited this page Feb 29, 2024 · 4 revisions

When do you use map() and mapaccum() in practice?

A main application of them are to speed up solving optimal control problems.

You can use mapaccum to simulate a system sample-by-sample, i.e. in a single shooting formulation.

You can use map to evaluate the multiple-shooting constraints, since these require $N$ evaluations of the discretized dynamics function with different arguments (xk, uk). This will also instruct the parallelization of the AD Jacobian of the function you are instructing to map. When using map() on the multiple-shooting constraints (whose output is a vector of $n_x$ elements), the map function will return an $n_x$ by $N$ matrix. Every column corresponds to a different shooting point $k$.

A quick introduction on what is single and multiple shooting in a nonlinear system identification setting.

To get started, you should watch the Yacoda Training lecture about map and mapaccum for sure.

Talk slides introducing these functions (but the API might have changed since then).

This document also tells how to use them.

There is a version of map that has the parameters reduce_in and reduce_out:

map(self, int n, [bool] reduce_in, [bool] reduce_out, dict opts)

reduce_out will sum the results.
reduce_in is to avoid having to copy parameters that shall appear repeatedly on the input (however, internally CasADi might still copy). See also the discussion here: issue 2963

Examples

Corner cases

  • if you mapaccum() for one sample only: check if it returns an SXFunction, then there is no performance overhead.
  • .map(100001, 'thread', 4) shall calculate the first 100000 elements in parallel and take the last 1 separately (small overhead).
  • FAQTODO will map() and mapaccum() be also code generated? In what cases?
  • mapaccum: beware if you use it for simulation of a state space model, that simulation might “blow up”, see again this video.
Clone this wiki locally