# parallel_func: Run functions in parallel almost automatically 

More precisely: run any matrices-returning gretl or hansl function in parallel
with the industry-standard MPI technology.

The prime example is a computationally intensive bootstrap routine which
returns some matrix results for many iterations, where each iteration is
independent from the others - each does the same stuff, but typically for
different random draws. This package allows you to run, say, K iterations in
parallel on, say, N CPU cores to get K * N total iterations.

Your routine must be encapsulated in a single function, which will typically
be a non-native user-defined function written in gretl's scripting and matrix
language hansl. (Hence the _func_ in the package name.) Of course, your
top-level function may in turn call as many native or other user-defined
functions as you wish.

The MPI technology is something much more general than gretl and must be
properly installed and running on the machine and be set up in gretl's
settings. See the _gretl + MPI_ guide in gretl's help menu.
 
(If MPI is not found by gretl, then this package will still execute the
specified function, but in a standard way in a single thread, so in the
bootstrap example mentioned above you would get K * 1 = K iterations only.)

# How to use the parfunc function

The `parfunc` function is new in version 0.5 and is the recommended interface.

## Arguments:

1. string  `funcname`
2. bundle  `args`
3. bundle  `opts`  (optional, members and defaults see below)

The underlying function with the name given in `funcname` must exist and in
case of a user-written hansl function be defined/loaded in the current gretl
session. This underlying function must return an array of M matrices, or a
single matrix, so we deal with numerical results only. 

The return value is always an array of matrices:

- If the function given in `funcname` itself returns a matrices array, then the
 result here has exactly the same array structure that the underlying function
 would yield if you ran it in the standard way. 

- On the other hand, if `funcname` returns only a single matrix, the return
 value of `parfunc` will be an array with a single element. Then, in order to
 extract the included single matrix, simply append the [1] index in your code
 like this:

 ```matrix myresult = parfunc(...)[1]```

**The args input:** The necessary parameters for the underlying function
need to be wrapped in the `args` bundle input. To match the positional
arguments of `funcname`, the keys in that bundle must each start with "`arg`"
and then have an integer suffix starting at 1: 
"`arg1`", "`arg2`", etc.

Attention: This naming is essential and strictly required! As always, see the
included sample script for several practical illustrations. The sample script
also contains a more realistic example at the end using the stationary
bootstrap. (That example needs a few more seconds to run, so it is commented
out in the sample script and you need to uncomment it to run it.) 

The argument types for the underlying function can be almost anything.
When gretl series or list types are detected, the dataset context is passed to
the MPI world as well. However, this feature is experimental (new in v0.5) and
probably more fragile. Bundle arguments are supported, but they should not in
turn contain nested series or a list. The lists array datatype is not supported,
either. Not all of these restrictions are currently checked or intercepted, so
you will be testing the limits of this mechanism at your own risk. The fallback
recommendation is to convert this kind of data to matrices and work with that.

**Optional opts input:** This bundle collects various optional user settings as
follows, where the spelling of these members must be followed exactly:

- `aggregate_ops`: strings array, determines how to consolidate the interim
 matrix results of the parallel threads, one string for each separate element
 of the matrices array which is returned by `funcname`. Default: omitted or
 empty array, meaning "`vcat`" for all matrix results (vertical concatenation).
 Other possible choices are determined by gretl's MPI framework, i.e.: 
 "`vcat`", "`hcat`", "`sum`", "`prod`". 

- `Nparallel`: integer, chooses the number of MPI processes. Default: 0,
 meaning all hardware CPU cores available, provided MPI is installed and ready.
 If set to 1, MPI is not used even if it is present. If no MPI support is
 found, a single thread is used in any case.

- `dataset_context`: switch to force passing the dataset context to MPI even
 though no series or list arguments are passed. Default: 0/FALSE. This option
 is only needed if the underlying function(s) do not take any series or list
 arguments but internally create temporary series objects, e.g. for running
 gretl's estimation commands. Requires gretl functionality introduced with
 version 2024a and will cause an error on earlier gretl versions.

 - `mwritebin`: switch that tries to speed up the transfer of very large result
 matrices out of the MPI world to the caller level, by using binary-format
 temporary files instead of transferring the matrices inside of a g-zipped
 bundle. Default: 0/FALSE.  

- `verbose`: switch on more messages, partly for debugging. Default: 0/FALSE.

- `RNGseed`: if non-zero, invokes a "`set seed`" command inside the parallel
 processes in order to obtain replicable results. Default: 0/none.

## Notes

Note I: This is a package for running the _same_ stuff in parallel. If you
want to run different scenarios or use different input parameters in parallel,
check out the sister contributed package `parallel_specs`.

Note II: This package does not touch gretl's default way of handling (pseudo)
random number generators, see section 7 of the "gretl + MPI" guide. This means
that each parallel process uses its "own" RNG, such that no unwanted implicit
dependency between the processes arises. This should be true no matter whether
the argument RNGseed is activated (positive) or not.

# The older parallel_func interface

Before version 0.5 of this package, only the `parallel_func` function existed.
It is still kept for compatibility reasons and there are currently no plans to
retire it. The difference is that there is no consolidated `opts` options
bundle.

## Arguments:

1. string  `funcname`
2. bundle  `args`
3. strings `aggregate_ops`   (array, optional, default "`vcat`" for all)
4. int     `Nparallel`       (optional, default 0/use all)
5. bool    `verbose`         (optional, default 0/FALSE)
6. int     `RNGseed`         (optional, default 0/none)

The `funcname` and `args` inputs work just like with `parfunc`.
Returns the same output as `parfunc`, too.
Finally, the optional arguments **aggregate_ops**, **Nparallel**, **verbose**
and **RNGseed** correspond to the members of the `opts` bundle in `parfunc`.
All of these items and their meanings are described above.

## Changelog

March 2024, 0.55: 

- experimental/optional internal transfer of output matrices in bin format for speed
- impose a limit of 9 arguments to the underlying function to prevent a sorting bug
 from biting (might be lifted again in the future) 

February 2024, 0.5: 

- Switch to markdown for the help text.
- Send the dataset context to MPI if the underlying function arguments contain series
 or lists, and make it work also with subsampled datasets on current released gretl
 versions. Also add an experimental switch (requiring bleeding-edge gretl snapshots)
 to send the dataset context even without explicit series or list arguments.
- Fix trivial bug in the example with the stationary bootstrap (unfortunately
 went unnoticed because it is commented out in the sample script).

June 2023, 0.4: check for empty matrix or array input to pre-empt a 
    non-implementation issue in MPI on Windows and Mac.

April/June 2023, 0.31 (no public release):
    Catch errors within MPI a little bit better than before.

January 2023, 0.3:

- Modernize internal syntax. 
- Require gretl 2022a (because of errorif handling in MPI, for example).
- Enable running trivially in a non-MPI environment.
- Fix bug with lazy catch-all specifications of aggregation methods. 
- The labels for the positional args are changed from pure numbers to
        include the prefix "arg", like: "1" -> "arg1", etc.
        (the old form should hopefully still work)

August 2020, initial release 0.2: add option for setting the seed; try to add
    a catch and error message for failed execution (e.g. incorrect number of
    arguments) -- but not successful yet.

July 2020, internal version 0.1
