database.py 10.1 KB
Newer Older
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
#!/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/.           #
#                                                                             #
###############################################################################


"""Validation of databases"""

import os
import sys
# import collections

import six
import simplejson

from . import loader

# from . import dataformat
# from . import hash
# from . import utils
# from . import prototypes


class View(object):
  '''A special loader class for database views, with specialized methods

  Parameters:

    db_name (str): The full name of the database object for this view

    module (module): The preloaded module containing the database views as
      returned by :py:func:`beat.core.loader.load_module`.

    prefix (str, path): The prefix path for the current installation

    root_folder (str, path): The path pointing to the root folder of this
      database

    exc (class): The class to use as base exception when translating the
      exception from the user code. Read the documention of :py:func:`run`
      for more details.

    *args: Constructor parameters for the database view. Normally, none.

    **kwargs: Constructor parameters for the database view. Normally, none.

  '''


  def __init__(self, module, definition, prefix, root_folder, exc=None,
          *args, **kwargs):

    try:
      class_ = getattr(module, definition['view'])
    except Exception as e:
      if exc is not None:
        type, value, traceback = sys.exc_info()
        six.reraise(exc, exc(value), traceback)
      else:
        raise #just re-raise the user exception

    self.obj = loader.run(class_, '__new__', exc, *args, **kwargs)
    self.ready = False
    self.prefix = prefix
    self.root_folder = root_folder
    self.definition = definition
    self.exc = exc or RuntimeError
    self.outputs = None


  def prepare_outputs(self):
    '''Prepares the outputs of the dataset'''

    from .outputs import Output, OutputList
    from .data import MemoryDataSink
    from .dataformat import DataFormat

    # create the stock outputs for this dataset, so data is dumped
    # on a in-memory sink
    self.outputs = OutputList()
    for out_name, out_format in self.definition.get('outputs', {}).items():
      data_sink = MemoryDataSink()
      data_sink.dataformat = DataFormat(self.prefix, out_format)
      data_sink.setup([])
      self.outputs.add(Output(out_name, data_sink, dataset_output=True))


  def setup(self, *args, **kwargs):
    '''Sets up the view'''

    kwargs.setdefault('root_folder', self.root_folder)
    kwargs.setdefault('parameters', self.definition.get('parameters', {}))

    if 'outputs' not in kwargs:
      kwargs['outputs'] = self.outputs
    else:
      self.outputs = kwargs['outputs'] #record outputs nevertheless

    self.ready = loader.run(self.obj, 'setup', self.exc, *args, **kwargs)

    if not self.ready:
      raise self.exc("unknow setup failure")

    return self.ready


  def input_group(self, name='default', exclude_outputs=[]):
    '''A memory-source input group matching the outputs from the view'''

    if not self.ready:
      raise self.exc("database view not yet setup")

    from .data import MemoryDataSource
    from .outputs import SynchronizationListener
    from .inputs import Input, InputGroup

    # Setup the inputs
    synchronization_listener = SynchronizationListener()
    input_group = InputGroup(name,
            synchronization_listener=synchronization_listener,
            restricted_access=False)

    for output in self.outputs:
      if output.name in exclude_outputs: continue
      data_source = MemoryDataSource(self.done, next_callback=self.next)
      output.data_sink.data_sources.append(data_source)
      input_group.add(Input(output.name,
          output.data_sink.dataformat, data_source))

    return input_group


  def done(self, *args, **kwargs):
    '''Checks if the view is done'''

    if not self.ready:
      raise self.exc("database view not yet setup")

    return loader.run(self.obj, 'done', self.exc, *args, **kwargs)


  def next(self, *args, **kwargs):
    '''Runs through the next data chunk'''

    if not self.ready:
      raise self.exc("database view not yet setup")
    return loader.run(self.obj, 'next', self.exc, *args, **kwargs)


  def __getattr__(self, key):
    '''Returns an attribute of the view - only called at last resort'''
    return getattr(self.obj, key)



class Database(object):
  """Databases define the start point of the dataflow in an experiment.


  Parameters:

    prefix (str): Establishes the prefix of your installation.

    name (str): The fully qualified database name (e.g. ``db/1``)

    dataformat_cache (dict, optional): A dictionary mapping dataformat names
      to loaded dataformats. This parameter is optional and, if passed, may
      greatly speed-up database loading times as dataformats that are already
      loaded may be re-used. If you use this parameter, you must guarantee
      that the cache is refreshed as appropriate in case the underlying
      dataformats change.


  Attributes:

    name (str): The full, valid name of this database

    data (dict): The original data for this database, as loaded by our JSON
      decoder.

  """

  def __init__(self, prefix, name, dataformat_cache=None):

    self._name = None
    self.prefix = prefix
    self.dataformats = {} # preloaded dataformats

    self.data = None

    # if the user has not provided a cache, still use one for performance
    dataformat_cache = dataformat_cache if dataformat_cache is not None else {}

    self._load(name, dataformat_cache)


  def _load(self, data, dataformat_cache):
    """Loads the database"""

    self._name = data
    json_path = os.path.join(prefix, 'databases', name + '.json')
    with open(json_path, 'rb') as f: self.data = simplejson.load(f)


  @property
  def name(self):
    """Returns the name of this object
    """
    return self._name or '__unnamed_database__'


  @property
  def schema_version(self):
    """Returns the schema version"""
    return self.data.get('schema_version', 1)


  @property
  def protocols(self):
    """The declaration of all the protocols of the database"""

    data = self.data['protocols']
    return dict(zip([k['name'] for k in data], data))


  def protocol(self, name):
    """The declaration of a specific protocol in the database"""

    return self.protocols[name]


  @property
  def protocol_names(self):
    """Names of protocols declared for this database"""

    data = self.data['protocols']
    return [k['name'] for k in data]


  def sets(self, protocol):
    """The declaration of a specific set in the database protocol"""

    data = self.protocol(protocol)['sets']
    return dict(zip([k['name'] for k in data], data))


  def set(self, protocol, name):
    """The declaration of all the protocols of the database"""

    return self.sets(protocol)[name]


  def set_names(self, protocol):
    """The names of sets in a given protocol for this database"""

    data = self.protocol(protocol)['sets']
    return [k['name'] for k in data]


  def view(self, protocol, name, exc=None):
    """Returns the database view, given the protocol and the set name

    Parameters:

      protocol (str): The name of the protocol where to retrieve the view from

      name (str): The name of the set in the protocol where to retrieve the
        view from

      exc (class): If passed, must be a valid exception class that will be
        used to report errors in the read-out of this database's view.

    Returns:

      The database view, which will be constructed, but not setup. You
      **must** set it up before using methods ``done`` or ``next``.

    """

    if not self._name:
      exc = exc or RuntimeError
      raise exc("database has no name")

    if not self.valid:
      message = "cannot load view for set `%s' of protocol `%s' " \
              "from invalid database (%s)" % (protocol, name, self.name)
      if exc: raise exc(message)
      raise RuntimeError(message)

    # loads the module only once through the lifetime of the database object
    try:
      if not hasattr(self, '_module'):
        self._module = loader.load_module(self.name.replace(os.sep, '_'),
                  self.storage.code.path, {})
    except Exception as e:
      if exc is not None:
        type, value, traceback = sys.exc_info()
        six.reraise(exc, exc(value), traceback)
      else:
        raise #just re-raise the user exception

    return View(self._module, self.set(protocol, name), self.prefix,
            self.data['root_folder'], exc)