.. _python-post-processing:

# CPython post-processing

RiskScape models support a post-processing script feature that can run
a python script after your model finishes running.  Your python
script must declare a Python
function in the following format, which will be the main entry-point for the Python script:

```
def function(metadata):
    pass
```

When called by RiskScape, it is given a single dictionary argument
that contains metadata about the generated outputs as well as the
parameters that were used to generate them.

A simple example might look like this:

```ini
[model impact-forecast]
framework = pipeline
location = impact-forecast-pipeline.txt
post-processing-script = ./functions/create-map-thumbnails.py
```

The CPython script will be called once your model completes successfully.  Your script might
look something like:

```python

def function(metadata):
  for name, path in metadata['outputs'].items():
    # Assign a name for the output
    thumbnail_output = model_output('%s-thumbnail.jpg' % name)

    # Call our fancy thumbnailing method with the input path and the path where
    # RiskScape can expect to find it
    generate_map_thumbnail(path, thumbnail_output)
```

## Metadata argument

The metadata argument is a JSON-like dictionary object containing:

- `outputs`: a dictionary of paths (or URIs if not stored locally) to the model's outputs, keyed by the name that was assigned to the output, e.g. `regional-impact`
- `parameters`: a dictionary of the parameters that were used to build the model.  Strings are given without quotes.

## Registering model outputs

The `model_output()` function is a special Python function provided by RiskScape.  It is
usually called like this:

```python
# example usage
with open(model_output('thumbnail.png'), 'w') as fout:
  pass # write something to fout
```

It tells RiskScape that our Python script is writing an output file (called `thumbnail.png` in our example above).
RiskScape will make sure that file gets saved in the same directory as all the other model outputs.


.. tip::

    We recommend that you use ``model_output()`` whenever you save a file in Python code.
    If you don't, the file will still get written but it might end up in a different directory,
    and the model won't be compatible with the RiskScape Platform.

