inputs.py 17.4 KB
Newer Older
André Anjos's avatar
André Anjos 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
#!/usr/bin/env python
# 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.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


class Input:
  """Represents the input of a processing block

  A list of those inputs must be provided to the algorithms (see
  :py:class:`beat.backend.python.inputs.InputList`)


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
  Parameters:

    name (str): Name of the input

    data_format (str): Data format accepted by the input

    data_source (beat.core.platform.data.DataSource): Source of data to be used
      by the input


  Attributes:

    group (beat.core.inputs.InputGroup): Group containing this input

    name (str): Name of the input (algorithm-specific)

    data (beat.core.baseformat.baseformat): The last block of data received on
      the input

    data_index (int): Index of the last block of data received on the input
      (see the section *Inputs synchronization* of the User's Guide)

    data_index_end (int): End index of the last block of data received on the
      input (see the section *Inputs synchronization* of the User's Guide)

    data_format (str): Data format accepted by the input

    data_source (beat.core.data.DataSource): Source of data used by the output

    nb_data_blocks_read (int): Number of data blocks read so far

  """

  def __init__(self, name, data_format, data_source):

    self.group               = None
82
    self.name                = str(name)
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
    self.data                = None
    self.data_index          = -1
    self.data_index_end      = -1
    self.data_same_as_previous = False
    self.data_format         = data_format
    self.data_source         = data_source
    self.nb_data_blocks_read = 0


  def isDataUnitDone(self):
    """Indicates if the current data unit will change at the next iteration"""

    return (self.data_index_end == self.group.data_index_end)


  def hasMoreData(self):
    """Indicates if there is more data to process on the input"""

    return self.data_source.hasMoreData()


  def next(self):
    """Retrieves the next block of data"""

    (self.data, self.data_index, self.data_index_end) = self.data_source.next()
    self.data_same_as_previous = False
    self.nb_data_blocks_read += 1


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


class InputGroup:
  """Represents a group of inputs synchronized together

  A group implementing this interface is provided to the algorithms (see
  :py:class:`beat.backend.python.inputs.InputList`).

  See :py:class:`beat.core.inputs.Input`

  Example:

    .. code-block:: python

       inputs = InputList()

       print inputs['labels'].data_format

       for index in range(0, len(inputs)):
           print inputs[index].data_format

       for input in inputs:
           print input.data_format

       for input in inputs[0:2]:
           print input.data_format


  Parameters:

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

    synchronization_listener (beat.core.outputs.SynchronizationListener):
      Synchronization listener to use

    restricted_access (bool): Indicates if the algorithm can freely use the
      inputs


  Atttributes:

    data_index (int): Index of the last block of data received on the inputs
      (see the section *Inputs synchronization* of the User's Guide)

    data_index_end (int): End index of the last block of data received on the
      inputs (see the section *Inputs synchronization* of the User's Guide)

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

    synchronization_listener (beat.core.outputs.SynchronizationListener):
      Synchronization listener used

  """

  def __init__(self, channel, synchronization_listener=None,
          restricted_access=True):

    self._inputs                  = []
    self.data_index               = -1
    self.data_index_end           = -1
173
    self.channel                  = str(channel)
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
    self.synchronization_listener = synchronization_listener
    self.restricted_access        = restricted_access


  def __getitem__(self, index):

    if isinstance(index, six.string_types):
      try:
        return [x for x in self._inputs if x.name == index][0]
      except:
        pass
    elif isinstance(index, int):
      if index < len(self._inputs):
        return self._inputs[index]
    return None


  def __iter__(self):
    for k in self._inputs: yield k


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


  def add(self, input):
    """Add an input to the group

    Parameters:

      input (beat.core.inputs.Input): The input to add

    """

    input.group = self
    self._inputs.append(input)


  def hasMoreData(self):
    """Indicates if there is more data to process in the group"""

    return bool([x for x in self._inputs if x.hasMoreData()])


  def next(self):
    """Retrieve the next block of data on all the inputs"""

    # Only for groups not managed by the platform
    if self.restricted_access: raise RuntimeError('Not authorized')

    # Only retrieve new data on the inputs where the current data expire first
    lower_end_index = reduce(lambda x, y: min(x, y.data_index_end),
            self._inputs[1:], self._inputs[0].data_index_end)
    inputs_to_update = [x for x in self._inputs \
            if x.data_index_end == lower_end_index]
    inputs_up_to_date = [x for x in self._inputs if x not in inputs_to_update]

    for input in inputs_to_update:
      input.next()
      input.data_same_as_previous = False

    for input in inputs_up_to_date:
      input.data_same_as_previous = True


    # Compute the group's start and end indices
    self.data_index = reduce(lambda x, y: max(x, y.data_index),
            self._inputs[1:], self._inputs[0].data_index)
    self.data_index_end = reduce(lambda x, y: min(x, y.data_index_end),
            self._inputs[1:], self._inputs[0].data_index_end)

    # Inform the synchronisation listener
    if self.synchronization_listener is not None:
      self.synchronization_listener.onIntervalChanged(self.data_index,
              self.data_index_end)


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


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
class RemoteException(Exception):

    def __init__(self, kind, message):
        super(RemoteException, self).__init__()

        if kind == 'sys':
            self.system_error = message
            self.user_error = ''
        else:
            self.system_error = ''
            self.user_error = message


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


def process_error(socket):
    kind = socket.recv()
    message = socket.recv()
    raise RemoteException(kind, message)


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


279
280
281
282
283
284
285
286
287
288
class RemoteInput:
  """Allows to access the input of a processing block, via a socket.

  The other end of the socket must be managed by a message handler (see
  :py:class:`beat.backend.python.message_handler.MessageHandler`)

  A list of those inputs must be provided to the algorithms (see
  :py:class:`beat.backend.python.inputs.InputList`)


André Anjos's avatar
André Anjos committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
  Parameters:

    name (str): Name of the input

    data_format (object): An object with the preloaded data format for this
      input (see :py:class:`beat.backend.python.dataformat.DataFormat`).

    socket (object): A 0MQ socket for writing the data to the server process


  Attributes:

    group (beat.backend.python.inputs.InputGroup): Group containing this input

    data (beat.core.baseformat.baseformat): The last block of data received on
      the input

  """

  def __init__(self, name, data_format, socket):

310
    self.name = str(name)
André Anjos's avatar
André Anjos committed
311
312
313
    self.data_format = data_format
    self.socket = socket
    self.data = None
314
315
    self.data_index = -1
    self.data_index_end = -1
André Anjos's avatar
André Anjos committed
316
317
    self.group = None
    self.comm_time = 0. #total time spent on communication
318
    self.nb_data_blocks_read = 0
André Anjos's avatar
André Anjos committed
319
320
321
322
323
324


  def isDataUnitDone(self):
    """Indicates if the current data unit will change at the next iteration"""

    logger.debug('send: (idd) is-dataunit-done %s', self.name)
325

André Anjos's avatar
André Anjos committed
326
    _start = time.time()
327

André Anjos's avatar
André Anjos committed
328
329
330
    self.socket.send('idd', zmq.SNDMORE)
    self.socket.send(self.group.channel, zmq.SNDMORE)
    self.socket.send(self.name)
331

André Anjos's avatar
André Anjos committed
332
    answer = self.socket.recv()
333

André Anjos's avatar
André Anjos committed
334
335
    self.comm_time += time.time() - _start
    logger.debug('recv: %s', answer)
336

André Anjos's avatar
André Anjos committed
337
338
339
340
341
342
343
    return answer == 'tru'


  def hasMoreData(self):
    """Indicates if there is more data to process on the input"""

    logger.debug('send: (hmd) has-more-data %s %s', self.group.channel, self.name)
344

André Anjos's avatar
André Anjos committed
345
    _start = time.time()
346

André Anjos's avatar
André Anjos committed
347
348
349
    self.socket.send('hmd', zmq.SNDMORE)
    self.socket.send(self.group.channel, zmq.SNDMORE)
    self.socket.send(self.name)
350

André Anjos's avatar
André Anjos committed
351
    answer = self.socket.recv()
352

André Anjos's avatar
André Anjos committed
353
354
    self.comm_time += time.time() - _start
    logger.debug('recv: %s', answer)
355
356
357
358

    if answer == 'err':
        process_error(self.socket)

André Anjos's avatar
André Anjos committed
359
360
361
362
363
364
365
    return answer == 'tru'


  def next(self):
    """Retrieves the next block of data"""

    logger.debug('send: (nxt) next %s %s', self.group.channel, self.name)
366

André Anjos's avatar
André Anjos committed
367
    _start = time.time()
368

André Anjos's avatar
André Anjos committed
369
370
371
    self.socket.send('nxt', zmq.SNDMORE)
    self.socket.send(self.group.channel, zmq.SNDMORE)
    self.socket.send(self.name)
372
373
374
375
376
377
378
379

    answer = self.socket.recv()

    if answer == 'err':
        self.comm_time += time.time() - _start
        process_error(self.socket)

    self.data_index = int(answer)
380
    self.data_index_end = int(self.socket.recv())
André Anjos's avatar
André Anjos committed
381
    self.unpack(self.socket.recv())
382

André Anjos's avatar
André Anjos committed
383
    self.comm_time += time.time() - _start
384
    self.nb_data_blocks_read += 1
André Anjos's avatar
André Anjos committed
385
386
387
388
389
390


  def unpack(self, packed):
    """Receives data through socket"""

    self.data = self.data_format.type()
391
392
    logger.debug('recv: <bin> (size=%d), indexes=(%d, %d)', len(packed),
                 self.data_index, self.data_index_end)
André Anjos's avatar
André Anjos committed
393
394
395
    self.data.unpack(packed)


396
397
398
399
400
401
402
403
#----------------------------------------------------------


class RemoteInputGroup:
  """Allows to access a group of inputs synchronized together, via a socket.

  The other end of the socket must be managed by a message handler (see
  :py:class:`beat.backend.python.message_handler.MessageHandler`)
André Anjos's avatar
André Anjos committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441

  A group implementing this interface is provided to the algorithms (see
  :py:class:`beat.core.inputs.InputList`).

  See :py:class:`beat.core.inputs.Input`

  Example:

    .. code-block:: python

       inputs = InputList()

       print inputs['labels'].data_format

       for index in range(0, len(inputs)):
           print inputs[index].data_format

       for input in inputs:
           print input.data_format

       for input in inputs[0:2]:
           print input.data_format


  Parameters:

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

    restricted_access (bool): Indicates if the algorithm can freely use the
      inputs

    socket (object): A 0MQ socket for writing the data to the server process

  """

  def __init__(self, channel, restricted_access, socket):

    self._inputs = []
442
    self.channel = str(channel)
André Anjos's avatar
André Anjos committed
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
    self.restricted_access = restricted_access
    self.socket = socket
    self.comm_time = 0.


  def __getitem__(self, index):

    if isinstance(index, six.string_types):
      try:
        return [x for x in self._inputs if x.name == index][0]
      except:
        pass
    elif isinstance(index, int):
      if index < len(self._inputs):
        return self._inputs[index]
    return None


  def __iter__(self):
    for k in self._inputs: yield k


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


  def add(self, input):
    """Add an input to the group

    Parameters:

      input (beat.backend.python.inputs.Input): The input to add

    """
    input.group = self
    self._inputs.append(input)


  def hasMoreData(self):
    """Indicates if there is more data to process in the group"""

    logger.debug('send: (hmd) has-more-data %s', self.channel)
485

André Anjos's avatar
André Anjos committed
486
    _start = time.time()
487

André Anjos's avatar
André Anjos committed
488
489
    self.socket.send('hmd', zmq.SNDMORE)
    self.socket.send(self.channel)
490

André Anjos's avatar
André Anjos committed
491
    answer = self.socket.recv()
492

André Anjos's avatar
André Anjos committed
493
494
    self.comm_time += time.time() - _start
    logger.debug('recv: %s', answer)
495
496
497
498

    if answer == 'err':
        process_error(self.socket)

André Anjos's avatar
André Anjos committed
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
    return answer == 'tru'


  def next(self):
    """Retrieve the next block of data on all the inputs"""

    logger.debug('send: (nxt) next %s', self.channel)
    self.socket.send('nxt', zmq.SNDMORE)
    self.socket.send(self.channel)

    # read all incomming data
    _start = time.time()
    more = True
    parts = []
    while more:
      parts.append(self.socket.recv())
515
516
517
518
      if parts[-1] == 'err':
        self.comm_time += time.time() - _start
        process_error(self.socket)

André Anjos's avatar
André Anjos committed
519
520
521
522
523
524
525
526
527
528
529
530
531
      more = self.socket.getsockopt(zmq.RCVMORE)

    n = int(parts.pop(0))
    logger.debug('recv: %d (inputs)', n)
    for k in range(n):
      name = parts.pop(0)
      logger.debug('recv: %s (data follows)', name)
      inpt = self[name]
      if inpt is None:
        raise RuntimeError("Could not find input `%s' at input group for " \
            "channel `%s' while performing `next' operation on this group " \
            "(current reading position is %d/%d)" % \
            (name, self.channel, k, n))
532
533
      inpt.data_index = int(parts.pop(0))
      inpt.data_index_end = int(parts.pop(0))
André Anjos's avatar
André Anjos committed
534
      inpt.unpack(parts.pop(0))
535
      inpt.nb_data_blocks_read += 1
André Anjos's avatar
André Anjos committed
536
537
538
    self.comm_time += time.time() - _start


539
540
541
#----------------------------------------------------------


André Anjos's avatar
André Anjos committed
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
class InputList:
  """Represents the list of inputs of a processing block

  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 list implementing this interface is provided to the algorithms

  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.core.inputs.Input`
  See :py:class:`beat.core.inputs.InputGroup`


  Example:

    .. code-block:: python

       inputs = InputList()
       ...

       # Retrieve an input by name
       input = inputs['labels']

       # Retrieve an input by index
       for index in range(0, len(inputs)):
           input = inputs[index]

       # Iteration over all inputs
       for input in inputs:
           ...

       # Iteration over some inputs
       for input in inputs[0:2]:
           ...

       # Retrieve the group an input belongs to, by input name
       group = inputs.groupOf('label')

       # Retrieve the group an input belongs to
       input = inputs['labels']
       group = input.group


  Attributes:

    group (beat.core.inputs.InputGroup): Main group (for data-driven
      algorithms)

  """

  def __init__(self):
    self._groups = []
    self.main_group = None


  def add(self, group):
    """Add a group to the list

    :param beat.core.platform.inputs.InputGroup group: The group to add
    """
    if group.restricted_access and (self.main_group is None):
      self.main_group = group

    self._groups.append(group)

610

André Anjos's avatar
André Anjos committed
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
  def __getitem__(self, index):
    if isinstance(index, six.string_types):
      try:
        return [k for k in map(lambda x: x[index], self._groups) \
                if k is not None][0]
      except:
        pass

    elif isinstance(index, int):
      for group in self._groups:
        if index < len(group): return group[index]
        index -= len(group)

    return None

626

André Anjos's avatar
André Anjos committed
627
628
629
  def __iter__(self):
    for i in range(len(self)): yield self[i]

630

André Anjos's avatar
André Anjos committed
631
632
633
  def __len__(self):
    return reduce(lambda x, y: x + len(y), self._groups, 0)

634

André Anjos's avatar
André Anjos committed
635
636
637
  def nbGroups(self):
    return len(self._groups)

638

André Anjos's avatar
André Anjos committed
639
640
641
642
643
644
  def groupOf(self, input_name):
    try:
      return [k for k in self._groups if k[input_name] is not None][0]
    except:
      return None

645

André Anjos's avatar
André Anjos committed
646
647
648
649
650
651
652
653
654
655
  def hasMoreData(self):
    """Indicates if there is more data to process in any group"""
    return bool([x for x in self._groups if x.hasMoreData()])


  def group(self, name):
    try:
      return [x for x in self._groups if x.channel == name][0]
    except:
      return None