data_loaders.py 10.9 KB
Newer Older
Philip ABBET's avatar
Philip ABBET committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

###############################################################################
#                                                                             #
# Copyright (c) 2017 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.backend.python 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/.           #
#                                                                             #
###############################################################################


import time
import logging
logger = logging.getLogger(__name__)

from functools import reduce

import six
import zmq

from .data import mixDataIndices


#----------------------------------------------------------


class DataView(object):
    """Provides access to a subset of data from a group of inputs synchronized
    together

    Data views are created from a data loader
    (see :py:class:`beat.backend.python.data_loaders.DataLoader`), which are
    provided to the algorithms of types 'sequential' and 'autonomous'
    (see :py:class:`beat.backend.python.data_loaders.DataLoaderList`).

    Example:

      .. code-block:: python

         view = data_loader.view('input1', 0)

         for i in range(view.count())
             (data, start_index, end_index) = view[i]


    Parameters:

      data_loader (:py:class:`beat.backend.python.data_loaders.DataLoader`):
                Name of the data channel of the group of inputs

      data_indices (list of tuples): Data indices to consider


    Attributes:

      data_index_start (int): Lower data index across all inputs
        (see the section *Inputs synchronization* of the User's Guide)

      data_index_end (int): Bigger data index across all inputs
        (see the section *Inputs synchronization* of the User's Guide)

    """

    def __init__(self, data_loader, data_indices):
        self.infos             = {}
        self.data_indices      = data_indices
        self.nb_data_units     = len(data_indices)
        self.data_index_start  = data_indices[0][0]
        self.data_index_end    = data_indices[-1][1]

        for input_name, infos in data_loader.infos.items():
            input_data_indices = []
            current_start = self.data_index_start

            for i in range(self.data_index_start, self.data_index_end + 1):
                for indices in infos['data_indices']:
                    if indices[1] == i:
                        input_data_indices.append( (current_start, i) )
                        current_start = i + 1
                        break

            if (len(input_data_indices) == 0) or (input_data_indices[-1][1] != self.data_index_end):
                input_data_indices.append( (current_start, self.data_index_end) )

            self.infos[input_name] = dict(
                cached_file = infos['cached_file'],
                data_indices = input_data_indices,
                data = None,
                start_index = -1,
                end_index = -1,
            )


    def count(self, input_name=None):
        if input_name is not None:
            try:
                return len(self.infos[input_name]['data_indices'])
            except:
                return None
        else:
            return self.nb_data_units


    def __getitem__(self, index):
        if index < 0:
            return (None, None, None)

        try:
            indices = self.data_indices[index]
        except:
            return (None, None, None)

        result = {}

        for input_name, infos in self.infos.items():
            if (indices[0] < infos['start_index']) or (infos['end_index'] < indices[0]):
                (infos['data'], infos['start_index'], infos['end_index']) = \
                        infos['cached_file'].getAtDataIndex(indices[0])

            result[input_name] = infos['data']

        return (result, indices[0], indices[1])


#----------------------------------------------------------


class DataLoader(object):
    """Provides access to data from a group of inputs synchronized together

    Data loaders are provided to the algorithms of types 'sequential' and
    'autonomous' (see :py:class:`beat.backend.python.data_loaders.DataLoaderList`).

    Example:

      .. code-block:: python

         # Iterate through all the data
         for i in range(data_loader.count())
             (data, start_index, end_index) = data_loader[i]
             print data['input1'].data

         # Restrict to a subset of the data
         view = data_loader.view('input1', 0)
         for i in range(view.count())
             (data, start_index, end_index) = view[i]


    Parameters:

      channel (str): Name of the data channel of the group of inputs


    Attributes:

      data_index_start (int): Lower data index across all inputs
        (see the section *Inputs synchronization* of the User's Guide)

      data_index_end (int): Bigger data index across all inputs
        (see the section *Inputs synchronization* of the User's Guide)

      channel (str): Name of the data channel of the group

    """

    def __init__(self, channel):
        self.channel            = str(channel)
        self.infos              = {}
        self.mixed_data_indices = None
        self.nb_data_units      = 0
        self.data_index_start   = -1  # Lower index across all inputs
        self.data_index_end     = -1  # Bigger index across all inputs


    def add(self, input_name, cached_file):
        self.infos[input_name] = dict(
            cached_file = cached_file,
            data_indices = cached_file.data_indices(),
            data = None,
            start_index = -1,
            end_index = -1,
        )

        self.mixed_data_indices = mixDataIndices([ x['data_indices'] for x in self.infos.values() ])
        self.nb_data_units = len(self.mixed_data_indices)
        self.data_index_start = self.mixed_data_indices[0][0]
        self.data_index_end = self.mixed_data_indices[-1][1]


    def input_names(self):
        return self.infos.keys()


    def count(self, input_name=None):
        if input_name is not None:
            try:
                return len(self.infos[input_name]['data_indices'])
            except:
                return 0
        else:
            return self.nb_data_units


    def view(self, input_name, index):
        if index < 0:
            return None

        try:
            indices = self.infos[input_name]['data_indices'][index]
        except:
            return None

        limited_data_indices = [ x for x in self.mixed_data_indices
                                 if (indices[0] <= x[0]) and (x[1] <= indices[1]) ]

        return DataView(self, limited_data_indices)


    def __getitem__(self, index):
        if index < 0:
            return (None, None, None)

        try:
            indices = self.mixed_data_indices[index]
        except:
            return (None, None, None)

        result = {}

        for input_name, infos in self.infos.items():
            if (indices[0] < infos['start_index']) or (infos['end_index'] < indices[0]):
                (infos['data'], infos['start_index'], infos['end_index']) = \
                        infos['cached_file'].getAtDataIndex(indices[0])

            result[input_name] = infos['data']

        return (result, indices[0], indices[1])


#----------------------------------------------------------


class DataLoaderList(object):
    """Represents a list of data loaders

    Inputs are organized by groups. The inputs inside a group are all
    synchronized together (see the section *Inputs synchronization* of the User's
    Guide). A data loader provides access to data from a group of inputs.

    A list implementing this interface is provided to the algorithms of types
    'sequential' and 'autonomous'.

    One group of inputs is always considered as the **main** one, and is used to
    drive the algorithm. The usage of the other groups is left to the algorithm.

    See :py:class:`beat.backend.python.data_loaders.DataLoader`


    Example:

      .. code-block:: python

         data_loaders = DataLoaderList()
         ...

         # Retrieve a data loader by name
         data_loader = data_loaders['labels']

         # Retrieve a data loader by index
         for index in range(0, len(data_loaders)):
             data_loader = data_loaders[index]

         # Iteration over all data loaders
         for data_loader in data_loaders:
             ...

         # Retrieve the data loader an input belongs to, by input name
         data_loader = data_loaders.loaderOf('label')


    Attributes:

      main_loader (beat.backend.python.data_loaders.DataLoader): Main data loader

    """

    def __init__(self):
        self._loaders = []
        self.main_loader = None


    def add(self, data_loader):
        """Add a data loader to the list

        :param beat.backend.python.data_loaders.DataLoader data_loader: The data
            loader to add
        """
        if self.main_loader is None:
            self.main_loader = data_loader

        self._loaders.append(data_loader)


    def __getitem__(self, name_or_index):
        try:
            if isinstance(name_or_index, six.string_types):
                return [x for x in self._loaders if x.channel == name_or_index][0]

            elif isinstance(index, int):
                return self._loaders[index]
        except:
            pass

        return None


    def __iter__(self):
        for i in range(len(self._loaders)):
            yield self._loaders[i]


    def __len__(self):
        return len(self._loaders)


    def loaderOf(self, input_name):
        try:
            return [ k for k in self._loaders if input_name in k.input_names() ][0]
        except:
            return None