.. vim: set fileencoding=utf-8 : .. Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/ .. .. Contact: beat.support@idiap.ch .. .. .. .. This file is part of the beat.core module of the BEAT platform. .. .. .. .. Commercial License Usage .. .. Licensees holding valid commercial BEAT licenses may use this file in .. .. accordance with the terms contained in a written agreement between you .. .. and Idiap. For further information contact tto@idiap.ch .. .. .. .. Alternatively, this file may be used under the terms of the GNU Affero .. .. Public License version 3 as published by the Free Software and appearing .. .. in the file LICENSE.AGPL included in the packaging of this file. .. .. The BEAT platform is distributed in the hope that it will be useful, but .. .. WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY .. .. or FITNESS FOR A PARTICULAR PURPOSE. .. .. .. .. You should have received a copy of the GNU Affero Public License along .. .. with the BEAT platform. If not, see http://www.gnu.org/licenses/. .. .. _beat-core-algorithms: =========== Algorithms =========== Algorithms are user-defined piece of software that run within the blocks of a toolchain. An algorithm can read data on the input(s) of the block and write processed data on its output(s). They are, hence, key components for scientific experiments, since they formally describe how to transform raw data into higher level concept such as classes. An algorithm lies at the core of each processing block and may be subject to parametrization. Inputs and outputs of an algorithm have well-defined data formats. The format of the data on each input and output of the block is defined at a higher-level in the platform. It is expected that the implementation of the algorithm respects whatever was declared on the platform. By default, the algorithm is **data-driven**; algorithm is typically provided one data sample at a time and must immediately produce some output data. Furthermore, the way the algorithm handle the data is highly configurable and covers a huge range of possible scenarios. :numref:`beat-core-overview-block` displays the relationship between a processing block and its algorithm. .. _beat-core-overview-block: .. figure:: ./img/block.* Relationship between a processing block and its algorithm This section contains information on the definition of algorithm and its programmatic use on Python-based language bindings. .. _beat-core-algorithms-definition: Definition ---------- An algorithm is defined by two distinct components: * a `JSON`_ object with several fields, specifying the inputs, the outputs, the parameters and additional information such as the language in which it is implemented. * source code (and/or [later] binary code) describing how to transform the input data. .. _beat-core-algorithms-definition-json: JSON Declaration ................ A `JSON`_ declaration of an algorithm consists of several fields. For example, the following declaration is the one of an algorithm implementing probabilistic component analysis (PCA): .. code-block:: javascript { "language": "python", "splittable": false, "groups": [ { "inputs": { "image": { "type": "system/array_2d_uint8/1" } }, "outputs": { "subspace": { "type": "tutorial/linear_machine/1" } } } ], "parameters": { "number-of-components": { "default": 5, "type": "uint32" } }, "description": "Principal Component Analysis (PCA)" } The field `language` specifies the language in which the algorithm is implemented. The field `splittable` indicates, whether the algorithm can be parallelized into chunks or not. The field `parameters` lists the parameters of the algorithm, describing both default values and their types. The field `groups` gives information about the inputs and outputs of the algorithm. They are provided into a list of dictionary, each element in this list being associated to a database `channel`. The group, which contains outputs, is the **synchronization channel**. By default, a loop is automatically performs by the platform on the synchronization channel, and user-code must not loop on this group. In contrast, it is the responsability of the user to load data from the other groups. This is described in more details in the following subsections. Finally, the field `description` is optional and gives a short description of the algorithm. The web client of the BEAT platform provides a graphical editor for algorithm, which simplifies its `JSON`_ declaration definition. .. _beat-core-algorithms-definition-analyzer: Analyzer ........ At the end of the processing workflow of an experiment, there is a special kind of algorithm, which does not yield any output, but in contrast so called `results`. These algorithms are called **analyzers**. `Results` of an experiment are reported back to the user. Since the platform is concerned about data privacy, only a limited number of data formats can be employed as results in an analyzer, such as boolean, integers, floating point values, strings (of limited size), as well as plots (such as scatter or bar plots). For example, the following declaration is the one of a simple analyzer, which generates an ROC curve as well as few other metrics. .. code-block:: javascript { "language": "python", "groups": [ { "inputs": { "scores": { "type": "tutorial/probe_scores/1" } } } ], "results": { "far": { "type": "float32", "display": true }, "roc": { "type": "plot/scatter/1", "display": false }, "number_of_positives": { "type": "int32", "display": false }, "frr": { "type": "float32", "display": true }, "eer": { "type": "float32", "display": true }, "threshold": { "type": "float32", "display": false }, "number_of_negatives": { "type": "int32", "display": false } } } .. _beat-core-algorithms-definition-code: Source Code ........... The BEAT platform has been designed to support algorithms written in different programming languages. However, for each language, a corresponding back-end needs to be implemented, which is in charge of connecting the inputs and outputs to the algorithm and running its code as expected. In this section, we describe the implementation of algorithms in the Python programming language. To implement a new algorithm, one must write a class following a few conventions. In the following, examples of such classes are provided. .. _beat-core-algorithms-examples: Examples -------- .. _beat-core-algorithms-examples-simple: Simple algorithm (no parametrization) ..................................... At the very minimum, an algorithm class must look like this: .. code-block:: python class Algorithm: def process(self, inputs, outputs): # Read data from inputs, compute something, and write the result # of the computation on outputs ... return True The class must be called ``Algorithm`` and must have a method called ``process()``, that takes as parameters a list of inputs (see section :ref:`beat-core-algorithms-input-inputlist`) and a list of outputs (see section :ref:`beat-core-algorithms-output-outputlist`). This method must return ``True`` if everything went correctly, and ``False`` if an error occurred. The platform will call this method once per block of data available on the `synchronized` inputs of the block. .. _beat-core-algorithms-examples-parametrizable: Parametrizable algorithm ........................ To implement a parametrizable algorithm, two things must be added to the class: (1) a field in the JSON declaration of the algorithm containing their default values as well as the type of the parameters, and (2) a method called ``setup()``, that takes one argument, a map containing the parameters of the algorithm. .. code-block:: javascript { ... "parameters": { "threshold": { "default": 0.5, "type": "float32" } }, ... } .. code-block:: python class Algorithm: def setup(self, parameters): # Retrieve the value of the parameters self.threshold = parameters['threshold'] return True def process(self, inputs, outputs): # Read data from inputs, compute something, and write the result # of the computation on outputs ... return True When retrieving the value of the parameters, one must not assume that a value was provided for each parameter. This is why we may use a *try: ... except: ...* construct in the ``setup()`` method. .. _beat-core-algorithms-input: Handling input data ------------------- .. _beat-core-algorithms-input-inputlist: Input list .......... An algorithm is given access to the **list of the inputs** of the processing block. This list can be used to access each input individually, either by their name (see section :ref:`beat-core-algorithms-input-name`), their index or by iterating over the list: .. code-block:: python # 'inputs' is the list of inputs of the processing block print(inputs['labels'].data_format) for index in range(0, inputs.length): print(inputs[index].data_format) for input in inputs: print(input.data_format) for input in inputs[0:2]: print(input.data_format) Additionally, the following method is useable on a **list of inputs**: .. py:method:: hasMoreData() Indicates if there is (at least) another block of data to process on some of the inputs .. _beat-core-algorithms-input-input: Input ..... Each input provides the following informations: .. py:attribute:: name *(string)* Name of the input .. py:attribute:: data_format *(string)* Data format accepted by the input .. py:attribute:: data_index *(integer)* Index of the last block of data received on the input (See section :ref:`beat-core-algorithms-input-synchronization`) .. py:attribute:: data *(object)* The last block of data received on the input The structure of the ``data`` object is dependent of the data format assigned to the input. Note that ``data`` can be *None*. .. _beat-core-algorithms-input-name: Input naming ............ Each algorithm assign a name of its choice to each input (and output, see section :ref:`beat-core-algorithms-output-name`). This mechanism ensures that algorithms are easily shareable between users. For instance, in :numref:`beat-core-algorithms-input-naming`, two different users (Joe and Bill) are using two different toolchains. Both toolchains have one block with two entries and one output, with a similar set of data formats (*image/rgb* and *label* on the inputs, *array/float* on the output), although not in the same order. The two blocks use different algorithms, which both refers to their inputs and outputs using names of their choice Nevertheless, Joe can choose to use Bill's algorithm instead of his own one. When the algorithm to use is changed on the web interface, the platform will attempt to match each input with the names (and types) declared by the algorithm. In case of ambiguity, the user will be asked to manually resolve it. In other words: the way the block is connected in the toolchain doesn't force a naming scheme or a specific order of inputs to the algorithms used in that block. As long as the set of data types (on the inputs and outputs) is compatible for both the block and the algorithm, the algorithm can be used in the block. .. _beat-core-algorithms-input-naming: .. figure:: ./img/inputs-naming.* Different toolchains, but interchangeable algorithms The name of the inputs are assigned in the JSON declaration of the algorithm, such as: .. code-block:: javascript { ... "groups": [ { "inputs": { "name1": { "type": "data_format_1" }, "name2": { "type": "data_format_2" } } } ], ... } .. _beat-core-algorithms-input-synchronization: Inputs synchronization ...................... The data available on the different inputs from the synchronized channels are (of course) synchronized. Let's consider the example toolchain on :numref:`beat-core-algorithms-input-synchronization-example`, where: * The image database provides two kind of data: some *images* and their associated *labels* * The *block A* receives both data via its inputs * The *block B* only receives the *labels* * Both algorithms are *data-driven* The system will ask the *block A* to process 6 images, one by one. On the second input, the algorithm will find the correct label for the current image. The ``block B`` will only be asked to process 2 labels. The algorithm can retrieve the index of the current block of data of each of its input by looking at their ``data_index`` attribute. For simplicity, the list of inputs has two attributes (``current_data_index`` and ``current_end_data_index``) that indicates the data indexes currently used by the synchronization mechanism of the platform. .. _beat-core-algorithms-input-synchronization-example: .. figure:: ./img/inputs-synchronization.* :width: 80% Synchronization example .. _beat-core-algorithms-input-unsynchronized: Additional input methods for unsynchronized channels .................................................... Unsynchronized input channels of algorithms can be accessed at will, and algorithms can use it any way they want. To be able to perform their job, they have access to additional methods. The following method is useable on a **list of inputs**: .. py:method:: next() Retrieve the next block of data on all the inputs **in a synchronized manner** Let's come back at the example toolchain on :numref:`beat-core-algorithms-input-synchronization-example`, and assume that *block A* uses an autonomous algorithm. To iterate over all the data on its inputs, the algorithm would do: .. code-block:: python class Algorithm: def process(self, inputs, outputs): # Iterate over all the unsynchronized data while inputs.hasMoreData(): inputs.next() # Do something with inputs['images'].data and inputs['labels'].data ... # At this point, there is no more data available on inputs['images'] and # inputs['labels'] return True The following methods are useable on an ``input``, in cases where the algorithm doesn't care about the synchronization of some of its inputs: .. py:method:: hasMoreData() Indicates if there is (at least) another block of data available on the input .. py:method:: next() Retrieve the next block of data .. warning:: Once this method has been called by an algorithm, the input is no more automatically synchronized with the other inputs of the block. In the following example, the algorithm desynchronizes one of its inputs but keeps the others synchronized and iterate over all their data: .. code-block:: javascript { ... "groups": [ { "inputs": { "images": { "type": "image/rgb" }, "labels": { "type": "label" }, "desynchronized": { "type": "number" } } } ], ... } .. code-block:: python class Algorithm: def process(self, inputs, outputs): # Desynchronize the third input. From now on, inputs['desynchronized'].data # and inputs['desynchronized'].data_index won't change inputs['desynchronized'].next() # Iterate over all the data on the inputs still synchronized while inputs.hasMoreData(): inputs.next() # Do something with inputs['images'].data and inputs['labels'].data ... # At this point, there is no more data available on inputs['images'] and # inputs['labels'], but there might be more on inputs['desynchronized'] return True .. _beat-core-algorithms-input-feedbackloop: Feedback inputs ............... The :numref:`beat-core-algorithms-input-feedbackloop-example` shows a toolchain containing a feedback loop. A special kind of input is needed in this scenario: a *feedback input*, that isn't synchronized with the other inputs, and can be freely used by the algorithm. Those feedback inputs aren't yet implemented in the prototype of the platform. This will be addressed in a later version. .. _beat-core-algorithms-input-feedbackloop-example: .. figure:: ./img/feedback-loop.* Feedback loop .. _beat-core-algorithms-output: Handling output data -------------------- .. _beat-core-algorithms-output-outputlist: Output list ........... An algorithm is given access to the **list of the outputs** of the processing block. This list can be used to access each output individually, either by their name (see section :ref:`beat-core-algorithms-output-name`), their index or by iterating over the list: .. code-block:: python # 'outputs' is the list of outputs of the processing block print outputs['features'].data_format for index in range(0, outputs.length): outputs[index].write(...) for output in outputs: output.write(...) for output in outputs[0:2]: output.write(...) .. _beat-core-algorithms-output-output: Output ...... Each output provides the following informations: .. py:attribute:: name *(string)* Name of the output .. py:attribute:: data_format *(string)* Format of the data written on the output And the following methods: .. py:method:: createData() Retrieve an initialized block of data corresponding to the data format of the output .. py:method:: write(data, end_data_index=None) Write a block of data on the output We'll look at the usage of those methods through some examples in the following sections. .. _beat-core-algorithms-output-name: Output naming ............. Like for its inputs, each algorithm assign a name of its choice to each output (see section :ref:`beat-core-algorithms-input-name` for more details) by including them in the JSON declaration of the algorithm. .. code-block:: javascript { ... "groups": [ { "inputs": { ... }, "outputs": { "name1": { "type": "data_format1" }, "name2": { "type": "data_format2" } } } ], ... } .. _beat-core-algorithms-output-example1: Example 1: Write one block of data for each received block of data .................................................................. .. _beat-core-algorithms-output-example1-figure: .. figure:: ./img/outputs-example1.* Example 1: 6 images as input, 6 blocks of data produced Consider the example toolchain on :numref:`beat-core-algorithms-output-example1-figure`. We will implement a *data-driven* algorithm that will write one block of data on the output of the block for each image received on its inputs. This is the simplest case. .. code-block:: javascript { ... "groups": [ { "inputs": { "images": { "type": "image/rgb" }, "labels": { "type": "label" } }, "outputs": { "features": { "type": "array/float" } } } ], ... } .. code-block:: python class Algorithm: def process(self, inputs, outputs): # Ask the output to create a data object according to its data format data = outputs['features'].createData() # Compute something from inputs['images'].data and inputs['labels'].data # and store the result in 'data' ... # Write our data block on the output outputs['features'].write(data) return True The structure of the ``data`` object is dependent of the data format assigned to the output. .. _beat-core-algorithms-output-example2: Example 2: Skip some blocks of data ................................... .. _beat-core-algorithms-output-example2-figure: .. figure:: ./img/outputs-example2.* Example 2: 6 images as input, 4 blocks of data produced, 2 blocks of data skipped Consider the example toolchain on :numref:`beat-core-algorithms-output-example2-figure`. This time, our algorithm will use a criterion to decide if it can perform its computation on an image or not, and tell the platform that, for a particular data index, no data is available. .. code-block:: javascript { ... "groups": [ { "inputs": { "images": { "type": "image/rgb" }, "labels": { "type": "label" } }, "outputs": { "features": { "type": "array/float" } } } ], ... } .. code-block:: python class Algorithm: def process(self, inputs, outputs): # Use a criterion on the image to determine if we can perform our # computation on it or not if can_compute(inputs['images'].data): # Ask the output to create a data object according to its data format data = outputs['features'].createData() # Compute something from inputs['images'].data and inputs['labels'].data # and store the result in 'data' ... # Write our data block on the output outputs['features'].write(data) else: # Tell the platform that no data is available for this image outputs['features'].write(None) return True def can_compute(self, image): # Implementation of our criterion ... return True # or False .. _beat-core-algorithms-output-example3: Example 3: Write one block of data related to several received blocks of data ............................................................................. .. _beat-core-algorithms-output-example3-figure: .. figure:: ./img/outputs-example3.* Example 3: 6 images as input, 2 blocks of data produced Consider the example toolchain on :numref:`beat-core-algorithms-output-example3-figure`. This time, our algorithm will compute something using all the images with the same label (all the dogs, all the cats) and write only one block of data related to all those images. The key here is the correct usage of the **current end data index** of the input list to specify the indexes of the blocks of data we write on the output. This ensure that the data will be synchronized everywhere in the toolchain: the platform can now tell, for each of our data block, which image and label it relates to (See section :ref:`beat-core-algorithms-input-synchronization`). Additionally, since we can't know in advance if the image currently processed is the last one with the current label, we need to memorize the current data index of the input list to correctly assign it later when we effectively write the data block on the output. .. code-block:: javascript { ... "groups": [ { "inputs": { "images": { "type": "image/rgb" }, "labels": { "type": "label" } }, "outputs": { "features": { "type": "array/float" } } } ], ... } .. code-block:: python class Algorithm: def __init__(self): self.data = None # Block of data updated each time we # receive a new image self.current_label = None # Label of the images currently processed self.previous_data_index = None # Data index of the input list during the # processing of the previous image def process(self, inputs, outputs): # Determine if we already processed some image(s) if self.data is not None: # Determine if the label has changed since the last image we processed if inputs['labels'].data.name != self.current_label: # Write the block of data on the output outputs['features'].write(data, self.previous_data_index) self.data = None # Memorize the current data index of the input list self.previous_data_index = inputs.current_end_data_index # Create a new block of data if necessary if self.data is None: # Ask the output to create a data object according to its data format self.data = outputs['features'].createData() # Remember the label we are currently processing self.current_label = inputs['labels'].data.name # Compute something from inputs['images'].data and inputs['labels'].data # and update the content of 'self.data' ... # Determine if this was the last block of data or not if not(inputs.hasMoreData()): # Write the block of data on the output outputs['features'].write(self.data, inputs.current_end_data_index) return True .. include:: links.rst