API
===

AOFlagger provides external C++ and Python Application Programming Interfaces (API)
to call the aoflagger from those languages.

To avoid confusion: These interfaces are not used to design a custom flagging strategy.
Custom flagging strategies make use of an internal Lua interface, which are described
in the :doc:`chapter on designing strategies <designing_strategies>`.
The external interfaces described here make
it possible to "push data" through AOFlagger from other software.

In particular, these interfaces allow integrating AOFlagger inside a pipeline, e.g. inside an observatory.
To use the interface, the C++ header file "``aoflagger.h``" is installed as part of the package, and can
be ``#include``\ d in a program's source code. Additionally, the program needs to be linked with libaoflagger.

C++ API
^^^^^^^

The documentation for the external C++ API is automatically extracted from the code
using Doxygen.
C++ API references can be found here:

 * http://www.andreoffringa.org/aoflagger/doxygen/

Python API
^^^^^^^^^^

The external Python API mirrors the external C++ API, and only differs in that it follows
the common Python naming conventions. The aoflagger module can be included in
Python using a standard ``import`` command:

.. code-block:: python

    import aoflagger
   
A few examples are given in the ``data`` directory. The following is an example to calculate
the false-positives ratio of the default strategy:

.. code-block:: python

    import aoflagger
    import numpy

    nch = 256
    ntimes = 1000
    count = 50       # number of trials in the false-positives test

    flagger = aoflagger.AOFlagger()
    path = flagger.find_strategy_file(aoflagger.TelescopeId.Generic)
    strategy = flagger.load_strategy_file(path)
    data = flagger.make_image_set(ntimes, nch, 8)

    ratiosum = 0.0
    ratiosumsq = 0.0
    for repeat in range(count):
        for imgindex in range(8):
            # Initialize data with random numbers
            values = numpy.random.normal(0, 1, [nch, ntimes])
            data.set_image_buffer(imgindex, values)
            
        flags = strategy.run(data)
        flagvalues = flags.get_buffer()
        ratio = float(sum(sum(flagvalues))) / (nch*ntimes)
        ratiosum += ratio
        ratiosumsq += ratio*ratio

    print("Percentage flags (false-positive rate) on Gaussian data: " +
        str(ratiosum * 100.0 / count) + "% +/- " +
        str(numpy.sqrt(
            (ratiosumsq/count - ratiosum*ratiosum / (count*count) )
            ) * 100.0) )

This takes about 10 seconds to run on my computer.
