base.py 11 KB
Newer Older
1 2 3 4 5 6
import ctypes as ct
from . import libcconfigspace

ccs_init = libcconfigspace.ccs_init
ccs_init.restype = ct.c_int

7
class ccs_version(ct.Structure):
8 9 10 11 12
  _fields_ = [("revision", ct.c_ushort),
              ("patch",    ct.c_ushort),
              ("minor",    ct.c_ushort),
              ("major",    ct.c_ushort)]

13 14 15
  def __str__(self):
    return "{}.{}.{}.{}".format(self.major, self.minor, self.patch, self.revision)

Brice Videau's avatar
Brice Videau committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
# Base types
ccs_float  = ct.c_double
ccs_int    = ct.c_longlong
ccs_bool   = ct.c_int
ccs_result = ct.c_int
ccs_hash   = ct.c_uint
ccs_object = ct.c_void_p

# Objects
ccs_rng                 = ccs_object
ccs_distribution        = ccs_object
ccs_hyperparameter      = ccs_object
ccs_expression          = ccs_object
ccs_context             = ccs_object
ccs_configuration_space = ccs_object
ccs_configuration       = ccs_object
ccs_objective_space     = ccs_object
ccs_evaluation          = ccs_object
ccs_tuner               = ccs_object

ccs_false = 0
ccs_true = 1

39 40 41 42 43 44
def _ccs_get_function(method, argtypes = [], restype = ccs_result):
  res = getattr(libcconfigspace, method)
  res.restype = restype
  res.argtypes = argtypes
  return res

Brice Videau's avatar
Brice Videau committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58
# https://www.python-course.eu/python3_metaclasses.php
class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Inactive(metaclass=Singleton):
    pass

ccs_inactive = Inactive()

# derived and adapted from http://code.activestate.com/recipes/576415/
59 60 61
class CEnumerationType(type(ct.c_int)):
  def __new__(metacls, name, bases, dict):
    if not "_members_" in dict:
Brice Videau's avatar
Brice Videau committed
62 63 64
      raise ValueError("CEnumeration must define a _members_ attribute")
    last = -1
    if isinstance(dict["_members_"], list):
65
      _members_ = {}
Brice Videau's avatar
Brice Videau committed
66 67 68 69 70 71 72 73
      for item in dict["_members_"]:
        if isinstance(item, tuple):
          (i, v) = item
          _members_[i] = v
          last = v
        else:
          last += 1
          _members_[item] = last
74
      dict["_members_"] = _members_
Brice Videau's avatar
Brice Videau committed
75 76 77 78 79 80
    _reverse_members_ = {}
    for key,value in dict["_members_"].items():
      dict[key] = value
      _reverse_members_[value] = key
    dict["_reverse_members_"] = _reverse_members_
    cls = type(ct.c_int).__new__(metacls, name, bases, dict)
81 82 83 84 85 86 87 88 89 90
    for key,value in cls._members_.items():
      globals()[key] = value
    return cls

  def __contains__(self, value):
    return value in self._members_.values()

  def __repr__(self):
    return "<Enumeration %s>" % self.__name__

Brice Videau's avatar
Brice Videau committed
91
class CEnumeration(ct.c_int, metaclass=CEnumerationType):
92 93
  _members_ = {}
  def __init__(self, value):
94 95 96 97 98 99
    ct.c_int.__init__(self, value)

  @property
  def name(self):
    if self.value in self._reverse_members_:
      return self._reverse_members_[self.value]
100 101 102 103 104 105 106 107 108 109 110 111 112 113
    else:
      raise ValueError("No enumeration member with value %r" % value)

  @classmethod
  def from_param(cls, param):
    if isinstance(param, CEnumeration):
      if param.__class__ != cls:
        raise ValueError("Cannot mix enumeration members")
      else:
        return param
    else:
      return cls(param)

  def __repr__(self):
114
    return "<member %s(%d) of %r>" % (self.name, self.value, self.__class__)
115 116 117 118

  def __str__(self):
    return "%s.%s" % (self.__class__.__name__, self.name)

Brice Videau's avatar
Brice Videau committed
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
class CEnumerationType64(type(ct.c_longlong)):
  def __new__(metacls, name, bases, dict):
    if not "_members_" in dict:
      raise ValueError("CEnumeration must define a _members_ attribute")
    last = -1
    if isinstance(dict["_members_"], list):
      _members_ = {}
      for item in dict["_members_"]:
        if isinstance(item, tuple):
          (i, v) = item
          _members_[i] = v
          last = v
        else:
          last += 1
          _members_[item] = last
      dict["_members_"] = _members_
    _reverse_members_ = {}
    for key,value in dict["_members_"].items():
      dict[key] = value
      _reverse_members_[value] = key
    dict["_reverse_members_"] = _reverse_members_
    cls = type(ct.c_longlong).__new__(metacls, name, bases, dict)
    for key,value in cls._members_.items():
      globals()[key] = value
    return cls

  def __contains__(self, value):
    return value in self._members_.values()

  def __repr__(self):
    return "<Enumeration %s>" % self.__name__

class CEnumeration64(ct.c_longlong, metaclass=CEnumerationType64):
  _members_ = {}
  def __init__(self, value):
    ct.c_longlong.__init__(self, value)

  def __repr__(self):
157
    return "<member %s(%d) of %r>" % (self.name, self.value, self.__class__)
Brice Videau's avatar
Brice Videau committed
158 159 160 161 162 163 164 165 166 167 168

  def __str__(self):
    return "%s.%s" % (self.__class__.__name__, self.name)

  @property
  def name(self):
    if self.value in self._reverse_members_:
      return self._reverse_members_[self.value]
    else:
      raise ValueError("No enumeration member with value %r" % value)

169
  @classmethod
Brice Videau's avatar
Brice Videau committed
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
  def from_param(cls, param):
    if isinstance(param, CEnumeration):
      if param.__class__ != cls:
        raise ValueError("Cannot mix enumeration members")
      else:
        return param
    else:
      return cls(param)

class ccs_object_type(CEnumeration):
  _members_ = [
    ('RNG', 0),
    'DISTRIBUTION',
    'HYPERPARAMETER',
    'EXPRESSION',
    'CONFIGURATION_SPACE',
    'CONFIGURATION',
    'OBJECTIVE_SPACE',
    'EVALUATION',
    'TUNER' ]

class ccs_error(CEnumeration):
  _members_ = [ 
    ('SUCCESS', 0),
    'INVALID_OBJECT',
    'INVALID_VALUE',
    'INVALID_TYPE',
    'INVALID_SCALE',
    'INVALID_DISTRIBUTION',
    'INVALID_EXPRESSION',
    'INVALID_HYPERPARAMETER',
    'INVALID_CONFIGURATION',
    'INVALID_NAME',
    'INVALID_CONDITION',
    'INVALID_TUNER',
    'INVALID_GRAPH',
    'TYPE_NOT_COMPARABLE',
    'INVALID_BOUNDS',
    'OUT_OF_BOUNDS',
    'SAMPLING_UNSUCCESSFUL',
    'INACTIVE_HYPERPARAMETER',
    'OUT_OF_MEMORY',
    'UNSUPPORTED_OPERATION' ]

class ccs_data_type(CEnumeration64):
  _members_ = [
    ('NONE', 0),
    'INTEGER',
    'FLOAT',
    'BOOLEAN',
    'STRING',
    'INACTIVE',
    'OBJECT' ]
 
class ccs_numeric_type(CEnumeration64):
  _members_ = [
    ('NUM_INTEGER', ccs_data_type.INTEGER),
    ('NUM_FLOAT', ccs_data_type.FLOAT) ]

229
class ccs_numeric(ct.Union):
Brice Videau's avatar
Brice Videau committed
230 231 232
  _fields_ = [('f', ccs_float),
              ('i', ccs_int)]

233 234 235 236
  def __init__(self, v = 0):
    super().__init__()
    self.set_value(v)

Brice Videau's avatar
Brice Videau committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  def get_value(self, t):
    if t == ccs_numeric_type.NUM_INTEGER:
      return self.f
    elif t == ccs_numeric_type.NUM_FLOAT:
      return self.v
    else:
      raise Error(ccs_error.INVALID_VALUE)

  def set_value(self, v):
    if isinstance(v, int):
      self.i = v
    elif isinstance(v, float):
      self.f = v
    else:
      raise Error(ccs_error.INVALID_VALUE)

253
class ccs_value(ct.Union):
Brice Videau's avatar
Brice Videau committed
254 255 256 257 258
  _fields_ = [('f', ccs_float),
              ('i', ccs_int),
              ('s', ct.c_char_p),
              ('o', ccs_object)]

259 260 261 262
class ccs_datum_fix(ct.Structure):
  _fields_ = [('value', ccs_int),
              ('type', ccs_data_type)]

263 264
class ccs_datum(ct.Structure):
  _fields_ = [('_value', ccs_value),
Brice Videau's avatar
Brice Videau committed
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
              ('type', ccs_data_type)]

  def __init__(self, v = None):
    super().__init__()
    self.value = v

  @property
  def value(self):
    if self.type.value == ccs_data_type.NONE:
      return None
    elif self.type.value == ccs_data_type.INTEGER:
      return self._value.i
    elif self.type.value == ccs_data_type.FLOAT:
      return self._value.f
    elif self.type.value == ccs_data_type.BOOLEAN:
      return False if self._value.i == ccs_false else True
    elif self.type.value == ccs_data_type.STRING:
      return self._value.s.decode()
    elif self.type.value == ccs_data_type.INACTIVE:
      return ccs_inactive
    elif self.type.value == ccs_data_type.OBJECT:
      return Object.from_handle(ct.c_void_p(self._value.o))
    else:
      raise Error(ccs_error.INVALID_VALUE)

  @value.setter
  def value(self, v):
    if v is None:
      self.type.value = ccs_data_type.NONE
      self._value.i = 0
    elif isinstance(v, bool):
      self.type.value = ccs_data_type.BOOLEAN
      self._value.i = 1 if v else 0
    elif isinstance(v, int):
      self.type.value = ccs_data_type.INTEGER
      self._value.i = v
    elif isinstance(v, float):
      self.type.value = ccs_data_type.FLOAT
      self._value.f = v
    elif isinstance(v, str):
      self.type.value = ccs_data_type.STRING
      self._string = str.encode(v)
      self._value.s = ct.c_char_p(self._string)
    elif v is ccs_inactive:
      self.type.value = ccs_data_type.INACTIVE
      self._value.i = 0
    elif isinstance(v, Object):
      self.type.value = ccs_data_type.OBJECT
313
      self._object = v
Brice Videau's avatar
Brice Videau committed
314 315 316 317 318
      self._value.o = v.handle
    else:
      raise Error(ccs_error.INVALID_VALUE)

class Error(Exception):
319 320 321 322 323 324
  def __init__(self, message):
    self.message = message

  @classmethod
  def check(cls, err):
    if err < 0:
Brice Videau's avatar
Brice Videau committed
325
      raise cls(ccs_error(-err))
326

327 328 329 330 331
ccs_get_version = _ccs_get_function("ccs_get_version", restype = ccs_version)
ccs_retain_object = _ccs_get_function("ccs_retain_object", [ccs_object])
ccs_release_object = _ccs_get_function("ccs_release_object", [ccs_object])
ccs_object_get_type = _ccs_get_function("ccs_object_get_type", [ccs_object, ct.POINTER(ccs_object_type)])
ccs_object_get_refcount = _ccs_get_function("ccs_object_get_refcount", [ccs_object, ct.POINTER(ct.c_int)])
332 333 334 335

class Object:
  def __init__(self, handle, retain = False, auto_release = True):
    if handle is None:
Brice Videau's avatar
Brice Videau committed
336
      raise Error(ccs_error.INVALID_OBJECT)
337
    self._handle = handle
338 339 340
    self.auto_release = auto_release
    if retain:
      res = ccs_retain_object(handle)
Brice Videau's avatar
Brice Videau committed
341
      Error.check(res)
342 343

  def __del__(self):
344
    res = ccs_release_object(self._handle)
Brice Videau's avatar
Brice Videau committed
345
    Error.check(res)
346

347 348 349 350 351
  @property
  def handle(self):
    return self._handle

  @property
352
  def object_type(self):
353 354
    if hasattr(self, "_object_type"):
      return self._object_type
Brice Videau's avatar
Brice Videau committed
355
    t = ccs_object_type(0)
356
    res = ccs_object_get_type(self.handle, ct.byref(t))
Brice Videau's avatar
Brice Videau committed
357
    Error.check(res)
358
    self._object_type = t
359 360
    return t

361
  @property
362 363 364
  def refcount(self):
    c = ct.c_int(0)
    res = ccs_object_get_refcount(self.handle, ct.byref(c))
Brice Videau's avatar
Brice Videau committed
365
    Error.check(res)
366
    return c.value
Brice Videau's avatar
Brice Videau committed
367 368 369 370 371 372

  @classmethod
  def from_handle(cls, h):
    t = ccs_object_type(0)
    res = ccs_object_get_type(h, ct.byref(t))
    Error.check(res)
373 374
    v = t.value
    if v == ccs_object_type.RNG:
Brice Videau's avatar
Brice Videau committed
375
      return Rng.from_handle(h)
376 377 378 379
    elif v == ccs_object_type.DISTRIBUTION:
      return Distribution.from_handle(h)
    elif v == ccs_object_type.HYPERPARAMETER:
      return Hyperparameter.from_handle(h)
380 381
    elif v == ccs_object_type.EXPRESSION:
      return Expression.from_handle(h)
382 383 384 385
    elif v == ccs_object_type.CONFIGURATION_SPACE:
      return ConfigurationSpace.from_handle(h)
    elif v == ccs_object_type.CONFIGURATION:
      return Configuration.from_handle(h)
Brice Videau's avatar
Brice Videau committed
386 387
    else:
      raise Error(ccs_error.INVALID_OBJECT)
388 389 390 391 392 393 394

_ccs_id = 0
def _ccs_get_id():
  global _ccs_id
  res = _ccs_id
  _ccs_id += 1
  return res
Brice Videau's avatar
Brice Videau committed
395
from .rng import Rng
396 397
from .distribution import Distribution
from .hyperparameter import Hyperparameter
398
from .expression import Expression
399 400
from .configuration_space import ConfigurationSpace
from .configuration import Configuration