<commit_before># The Vision Egg: ParameterTypes
#
# Copyright (C) 2001-2003 <NAME>.
# Author: <NAME> <<EMAIL>>
# URL: <http://www.visionegg.org/>
#
# Distributed under the terms of the GNU Lesser General Public License
# (LGPL). See LICENSE.TXT that came with this file.
#
# $Id$

"""
Type checking for the Vision Egg.

"""

import VisionEgg
__version__ = VisionEgg.release_name
__cvs__ = '$Revision$'.split()[1]
__date__ = ' '.join('$Date$'.split()[1:3])
__author__ = '<NAME> <<EMAIL>>'

import types, warnings

# Use Python's bool constants if available, make aliases if not
try:
    True
except NameError:
    True = 1==1
    False = 1==0

class ParameterTypeDef(object):
    """Base class for all parameter type definitions"""
    def verify(value):
        # override this method with type-checking code
        raise RuntimeError('must override base class method verify')
    verify = staticmethod(verify)
    
def get_all_classes_list(klass):
    #assert(type(klass) == types.ClassType)
    result = [klass]
    for base_klass in klass.__bases__:
        result.extend(get_all_classes_list(base_klass))
    return result
            
def is_parameter_type_def(item_type):
    if type(item_type) == types.ClassType:
        if Sequence in get_all_classes_list(item_type):
            raise TypeError("Sequence definition must be an instance (with a contained type).")
        else:
            return ParameterTypeDef in get_all_classes_list(item_type)
    elif isinstance(item_type,ParameterTypeDef):
        return True
    elif issubclass(item_type,ParameterTypeDef): # for new style classes
        return True
    elif item_type == types.NoneType:
        warnings.warn("types.NoneType will stop being a supported type "+\
                      "argument.  Please call "+\
                      "VisionEgg.ParameterTypes.get_type(None) to get the "+\
                      "supported value",DeprecationWarning,stacklevel=2)
        return True
    else:
        return False

class AnyOf(ParameterTypeDef):
    def __init__(self,*item_types):
        for item_type in item_types:
            if not is_parameter_type_def(item_type):
                raise TypeError("%s is not a valid type definition")
        self.item_types = item_types
    def __str__(self):
        return 'AnyOf(%s)'%(' or '.join(map(str,self.item_types)))
    def verify(self,is_any_of):
        for item_type in self.item_types:
            if item_type.verify(is_any_of):
                return True
        return False
    def get_item_types(self):
        return self.item_types

class NoneMC(type):
    def __str__(self):
        return 'None'
    
class NoneType(ParameterTypeDef):
    __metaclass__ = NoneMC
    def verify(is_none):
        return is_none is None
    verify = staticmethod(verify)

class BooleanMC(type):
    def __str__(self):
        return 'Boolean'
    
class Boolean(ParameterTypeDef):
    __metaclass__ = BooleanMC
    def verify(is_boolean):
        if type(is_boolean) in (type(1==1), int):
            return True
        else:
            return False
    verify = staticmethod(verify)

class CallableMC(type):
    def __str__(self):
        return 'Callable'
    
class Callable(ParameterTypeDef):
    __metaclass__ = CallableMC
    def verify(is_callable):
        return callable(is_callable)
    verify = staticmethod(verify)

class AnyClassMC(type):
    def __str__(self):
        return 'AnyClass'
    
class AnyClass(ParameterTypeDef):
    __metaclass__ = AnyClassMC
    def verify(is_class):
        return type(is_class) == types.ClassType
    verify = staticmethod(verify)
    
class SubClass(ParameterTypeDef):
    def __init__(self,base_class):
        if type(base_class) != types.ClassType:
            raise TypeError("base_class must be ClassType")
        self.base_class = base_class
    def verify(self,is_class):
        if type(self.base_class) != types.ClassType:
            return False
        return self.base_class in get_all_classes_list(is_class)
    def __str__(self):
        return 'SubClass of %s'%str(self.base_class)

class Instance(ParameterTypeDef):
    def __init__(self,class_type):
        if type(class_type) not in (types.ClassType, types.TypeType):
            raise TypeError("expected a class type")
        self.class_type = class_type
    def __str__(self):
        contained_string = str(self.class_type)
        return 'Instance of %s'%contained_string
    def verify(self,is_instance):
        return isinstance(is_instance,self.class_type)

class IntegerMC(type):
    def __str__(self):
        return 'Integer'
    
class Integer(ParameterTypeDef):
    __metaclass__ = IntegerMC
    def verify(is_integer):
        return type(is_integer) == int
    verify = staticmethod(verify)

class UnsignedIntegerMC(IntegerMC):
    def __str__(self):
        return 'UnsignedInteger'
    
class UnsignedInteger(Integer):
    __metaclass__ = UnsignedIntegerMC
    def verify(is_unsigned_integer):
        if not Integer.verify(is_unsigned_integer):
            return False
        return is_unsigned_integer >= 0
    verify = staticmethod(verify)

class RealMC(type):
    def __str__(self):
        return 'Real'
    
class Real(ParameterTypeDef):
    __metaclass__ = RealMC
    def verify(is_real):
        if type(is_real) in (int, float):
            return True
        else:
            return False
    verify = staticmethod(verify)
    
class Sequence(ParameterTypeDef):
    """A tuple, list or Numeric array"""
    def __init__(self,item_type):
        if not is_parameter_type_def(item_type):
            raise TypeError("%s is not a valid type definition"%item_type)
        self.item_type = item_type
    def __str__(self):
        contained_string = str(self.item_type)
        return 'Sequence of %s'%contained_string
    def verify(self,is_sequence):
        try:
            len(is_sequence)
        except TypeError:
            return False
        for i in xrange(len(is_sequence)):
            if not self.item_type.verify(is_sequence[i]):
                return False
        return True
        
class Sequence2(Sequence):
    def __str__(self):
        contained_string = str(self.item_type)<commit_msg>Bugfix: type checking: Numeric scalar is OK as a ve_types.Real<commit_after># The Vision Egg: ParameterTypes
#
# Copyright (C) 2001-2003 <NAME>.
# Author: <NAME> <<EMAIL>>
# URL: <http://www.visionegg.org/>
#
# Distributed under the terms of the GNU Lesser General Public License
# (LGPL). See LICENSE.TXT that came with this file.
#
# $Id$

"""
Type checking for the Vision Egg.

"""

import VisionEgg
__version__ = VisionEgg.release_name
__cvs__ = '$Revision$'.split()[1]
__date__ = ' '.join('$Date$'.split()[1:3])
__author__ = '<NAME> <<EMAIL>>'

import types, warnings

# Allow use of numarray without requiring numarray
import Numeric
array_types = [Numeric.ArrayType]
try:
    import numarray
    array_types.append( numarray.numarraycore.NumArray )
except ImportError:
    pass

# Use Python's bool constants if available, make aliases if not
try:
    True
except NameError:
    True = 1==1
    False = 1==0

class ParameterTypeDef(object):
    """Base class for all parameter type definitions"""
    def verify(value):
        # override this method with type-checking code
        raise RuntimeError('must override base class method verify')
    verify = staticmethod(verify)
    
def get_all_classes_list(klass):
    #assert(type(klass) == types.ClassType)
    result = [klass]
    for base_klass in klass.__bases__:
        result.extend(get_all_classes_list(base_klass))
    return result
            
def is_parameter_type_def(item_type):
    if type(item_type) == types.ClassType:
        if Sequence in get_all_classes_list(item_type):
            raise TypeError("Sequence definition must be an instance (with a contained type).")
        else:
            return ParameterTypeDef in get_all_classes_list(item_type)
    elif isinstance(item_type,ParameterTypeDef):
        return True
    elif issubclass(item_type,ParameterTypeDef): # for new style classes
        return True
    elif item_type == types.NoneType:
        warnings.warn("types.NoneType will stop being a supported type "+\
                      "argument.  Please call "+\
                      "VisionEgg.ParameterTypes.get_type(None) to get the "+\
                      "supported value",DeprecationWarning,stacklevel=2)
        return True
    else:
        return False

class AnyOf(ParameterTypeDef):
    def __init__(self,*item_types):
        for item_type in item_types:
            if not is_parameter_type_def(item_type):
                raise TypeError("%s is not a valid type definition")
        self.item_types = item_types
    def __str__(self):
        return 'AnyOf(%s)'%(' or '.join(map(str,self.item_types)))
    def verify(self,is_any_of):
        for item_type in self.item_types:
            if item_type.verify(is_any_of):
                return True
        return False
    def get_item_types(self):
        return self.item_types

class NoneMC(type):
    def __str__(self):
        return 'None'
    
class NoneType(ParameterTypeDef):
    __metaclass__ = NoneMC
    def verify(is_none):
        return is_none is None
    verify = staticmethod(verify)

class BooleanMC(type):
    def __str__(self):
        return 'Boolean'
    
class Boolean(ParameterTypeDef):
    __metaclass__ = BooleanMC
    def verify(is_boolean):
        if type(is_boolean) in (type(1==1), int):
            return True
        else:
            return False
    verify = staticmethod(verify)

class CallableMC(type):
    def __str__(self):
        return 'Callable'
    
class Callable(ParameterTypeDef):
    __metaclass__ = CallableMC
    def verify(is_callable):
        return callable(is_callable)
    verify = staticmethod(verify)

class AnyClassMC(type):
    def __str__(self):
        return 'AnyClass'
    
class AnyClass(ParameterTypeDef):
    __metaclass__ = AnyClassMC
    def verify(is_class):
        return type(is_class) == types.ClassType
    verify = staticmethod(verify)
    
class SubClass(ParameterTypeDef):
    def __init__(self,base_class):
        if type(base_class) != types.ClassType:
            raise TypeError("base_class must be ClassType")
        self.base_class = base_class
    def verify(self,is_class):
        if type(self.base_class) != types.ClassType:
            return False
        return self.base_class in get_all_classes_list(is_class)
    def __str__(self):
        return 'SubClass of %s'%str(self.base_class)

class Instance(ParameterTypeDef):
    def __init__(self,class_type):
        if type(class_type) not in (types.ClassType, types.TypeType):
            raise TypeError("expected a class type")
        self.class_type = class_type
    def __str__(self):
        contained_string = str(self.class_type)
        return 'Instance of %s'%contained_string
    def verify(self,is_instance):
        return isinstance(is_instance,self.class_type)

class IntegerMC(type):
    def __str__(self):
        return 'Integer'
    
class Integer(ParameterTypeDef):
    __metaclass__ = IntegerMC
    def verify(is_integer):
        return type(is_integer) == int
    verify = staticmethod(verify)

class UnsignedIntegerMC(IntegerMC):
    def __str__(self):
        return 'UnsignedInteger'
    
class UnsignedInteger(Integer):
    __metaclass__ = UnsignedIntegerMC
    def verify(is_unsigned_integer):
        if not Integer.verify(is_unsigned_integer):
            return False
        return is_unsigned_integer >= 0
    verify = staticmethod(verify)

class RealMC(type):
    def __str__(self):
        return 'Real'
    
class Real(ParameterTypeDef):
    __metaclass__ = RealMC
    def verify(is_real):
        if type(is_real) in (int, float):
            return True
        elif type(is_real) in array_types:
            # scalars can be Numeric arrays
            if len(is_real.shape)==0:
                try:
                    float(is_real)
                    return True
                except:
                    return False
        return False
    verify = staticmethod(verify)
    
class Sequence(ParameterTypeDef):
    """A tuple, list or Numeric array"""
    def __init__(self,item_type):
        if not is_parameter_type_def(item_type):
            raise TypeError("%s is not a valid type definition"%item_type)
        self.item_type = item_type
    def __str__(self):
        contained_string = str(self.item_type)
        return 'Sequence of %s'%contained_string
    def verify(self,is_sequence):
        try:
            len(is_sequence)
        except TypeError:
            return False
        for i in xrange(len(is_sequence)):
            if not self.item_type.verify(is_sequence[i]):
                return False
        return True
        
class Sequence2(Sequence):
    def __str__(self):
        contained_string = str(self.item_type)
{'fraction_non_alphanumeric': 0.09004113948614453, 'fraction_numerical': 0.0031824885508033845, 'mean_word_length': 2.768353319684118, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2810632', 'n_tokens_mistral': 3804, 'n_tokens_neox': 3728, 'n_words': 982}