def create_bin_method(op_name, klass):
    """
    Creates a new binary special method with only a left version, such as
    A.__eq__(B) <=> A==B, for target class. The method is called __op_name__.
    """

    # This function will become the method.

    def new_method(self, other):
        if not check_special_methods():
            raise NotImplementedError(
                'Special method %s called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.'
                % (op_name, str(self)))
        # This code creates a Deterministic object.

        def eval_fun(self, other, op):
            return getattr(self, op)(other)

        return pm.Deterministic(
            eval_fun,
            'A Deterministic returning the value of %s(%s,%s)' %
            (op_name, self.__name__, str(other)),
            '(' + '_'.join([self.__name__, op_name,
                            str(other)]) + ')', {
                                'self': self,
                                'other': other,
                                'op': '__' + op_name + '__'
                            },
            trace=False,
            plot=False)

    # Convert the function into a method for klass.
    new_method.__name__ = '__' + op_name + '__'
    setattr(klass, new_method.__name__,
            UnboundMethodType(new_method, None, klass))
Example #2
0
def create_uni_method(op_name, klass, jacobians = None):
    """
    Creates a new univariate special method, such as A.__neg__() <=> -A,
    for target class. The method is called __op_name__.
    """
    # This function will become the actual method.
    op_modules = [operator, __builtin__]
    op_names = [ op_name, op_name + '_']

    op_function_base = find_element( op_names,op_modules, error_on_fail = True)
    #many such functions do not take keyword arguments, so we need to wrap them 
    def op_function(self):
        return op_function_base(self)
    
    def new_method(self):
        # This code creates a Deterministic object.
        if not check_special_methods():
            raise NotImplementedError, 'Special method %s called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.'%(op_name, str(self))
            
        jacobian_formats = {'self' : 'transformation_operation'}
        return pm.Deterministic(op_function,
                                'A Deterministic returning the value of %s(%s)'%(op_name, self.__name__),
                                '('+op_name+'_'+self.__name__+')',
                                parents = {'self':self},
                                trace=False,
                                plot=False, 
                                jacobians=jacobians,
                                jacobian_formats = jacobian_formats)
    # Make the function into a method for klass. 
    
    new_method.__name__ = '__'+op_name+'__'
    setattr(klass, new_method.__name__, UnboundMethodType(new_method, None, klass))
Example #3
0
def create_rl_lin_comb_method(op_name, klass, x_roles, y_roles):
    """
    Creates a new binary special method with left and right versions, such as
        A.__mul__(B) <=> A*B,
        A.__rmul__(B) <=> [B*A if B.__mul__(A) fails]
    for target class. The method is called __op_name__.
    """
    # This function will became the methods.
    def new_method(self, other, x_roles=x_roles, y_roles=y_roles):
        if not check_special_methods():
            raise NotImplementedError, 'Special method %s called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.'%(op_name, str(self))
        x = []
        y = []
        for xr in x_roles:
            if xr=='self':
                x.append(self)
            elif xr=='other':
                x.append(other)
            else:
                x.append(xr)
        for yr in y_roles:
            if yr=='self':
                y.append(self)
            elif yr=='other':
                y.append(other)
            else:
                y.append(yr)
        # This code will create one of two Deterministic objects.
        return LinearCombination('('+'_'.join([self.__name__,op_name,str(other)])+')', x, y, trace=False, plot=False)

    # Convert the functions into methods for klass.
    new_method.__name__ = '__'+op_name+'__'
    setattr(klass, new_method.__name__, UnboundMethodType(new_method, None, klass))
Example #4
0
    def _addSetting(cls, setting):
        """Add a new instance method for the specified setting.

        Instance methods are cached, so that if a setting goes away and
        comes back later, the method will still point back to the
        same setting object.
        """
        if setting.name in cls._cache:
            method = cls._cache[setting.name]
        else:
            def wrapped(self, *args, **kw):
                key = extractKey(kw, 'key', None)
                tag = extractKey(kw, 'tag', None) or setting.accepts
                if len(args) == 0:
                    args = None
                elif len(args) == 1:
                    args = args[0]
                flat = T.flatten(args, tag)
                rec = PacketRecord(ID=setting.ID, data=args, tag=tag, flat=flat,
                                   key=key, name=setting.name)
                self._packet.append(rec)
                return self
            wrapped.name = setting.name
            if UnboundMethodType is not None:
                method = UnboundMethodType(wrapped, None, cls)
            else:
                # in python 3, unbound methods are just functions
                method = wrapped
        cls._cache[setting.name] = method
        cls.settings[setting.name, setting._py_name, setting.ID] = method
        setattr(cls, setting._py_name, method)
Example #5
0
def create_nonimplemented_method(op_name, klass):
    """
    Creates a new method that raises NotImplementedError.
    """
    def new_method(self, *args):
        raise NotImplementedError, 'Special method %s has not been implemented for PyMC variables.'%op_name
    new_method.__name__ = '__'+op_name+'__'
    setattr(klass, new_method.__name__, UnboundMethodType(new_method, None, klass))
Example #6
0
def create_rl_bin_method(op_name, klass, jacobians={}):
    """
    Creates a new binary special method with left and right versions, such as
        A.__mul__(B) <=> A*B,
        A.__rmul__(B) <=> [B*A if B.__mul__(A) fails]
    for target class. The method is called __op_name__.
    """
    # Make left and right versions.
    for prefix in ['r', '']:
        # This function will became the methods.
        op_modules = [operator, builtins]
        op_names = [op_name, op_name + '_']

        op_function_base = find_element(
            op_names,
            op_modules,
            error_on_fail=True)
        # many such functions do not take keyword arguments, so we need to wrap
        # them

        def op_function(a, b):
            return op_function_base(a, b)

        def new_method(self, other, prefix=prefix):
            if not check_special_methods():
                raise NotImplementedError(
                    'Special method %s called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.' %
                    (op_name, str(self)))
            # This code will create one of two Deterministic objects.
            if prefix == 'r':
                parents = {'a': other, 'b': self}

            else:
                parents = {'a': self, 'b': other}
            jacobian_formats = {'a': 'broadcast_operation',
                                'b': 'broadcast_operation'}
            return pm.Deterministic(op_function,
                                    'A Deterministic returning the value of %s(%s,%s)' % (
                                        prefix + op_name, self.__name__, str(
                                            other)),
                                    '(' + '_'.join(
                                        [self.__name__,
                                         prefix + op_name,
                                         str(other)]) + ')',
                                    parents,
                                    trace=False,
                                    plot=False,
                                    jacobians=jacobians,
                                    jacobian_formats=jacobian_formats)
        # Convert the functions into methods for klass.
        new_method.__name__ = '__' + prefix + op_name + '__'
        setattr(
            klass,
            new_method.__name__,
            UnboundMethodType(
                new_method,
                None,
                klass))
Example #7
0
 def _attach_to(self, parser):
     if six.PY3:
         m = self
     else:
         m = UnboundMethodType(self, None, parser)
     setattr(parser, self.name, m)
     if not self.action and hasattr(parser, "on_{}".format(self.name)):
         self.action = "on_{}".format(self.name)
     return m
Example #8
0
    def __init__(cls, name, bases, dict):
        type.__init__(cls, name, bases, dict)

        def change_method(self, *args, **kwargs):
            raise NotImplementedError(name + ' instances cannot be changed.')

        if cls.register:
            ContainerRegistry.append((cls, cls.containing_classes))

            for meth in cls.change_methods:
                setattr(cls, meth, UnboundMethodType(change_method, None, cls))
        cls.register = False
Example #9
0
 def visit_rule(self, node):
     locals_ = dict()
     exec(node._py_code, None, locals_)
     new_method = locals_[node.name]
     if six.PY3:
         new_method.__name__ = node.name
         meth = FunctionType(new_method.__code__, globals(), node.name)
     else:
         new_method._code = node._py_code  # noqa
         new_method.func_name = node.name  # noqa
         meth = UnboundMethodType(new_method, None, self.parser)  # noqa
     setattr(self.parser, node.name, meth)
     return node
Example #10
0
def create_casting_method(op, klass):
    """
    Creates a new univariate special method, such as A.__float__() <=> float(A.value),
    for target class. The method is called __op_name__.
    """
    # This function will become the actual method.
    def new_method(self, op=op):
        if not check_special_methods():
            raise NotImplementedError, 'Special method %s called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.'%(op_name, str(self))
        return op(self.value)
    # Make the function into a method for klass.
    new_method.__name__ = '__'+op.__name__+'__'
    setattr(klass, new_method.__name__, UnboundMethodType(new_method, None, klass))
Example #11
0
def create_rl_bin_method(op_name, klass):
    """
    Creates a new binary special method with left and right versions, such as
        A.__mul__(B) <=> A*B,
        A.__rmul__(B) <=> [B*A if B.__mul__(A) fails]
    for target class. The method is called __op_name__.
    """
    # Make left and right versions.
    for prefix in ['r','']:
        # This function will became the methods.
        def new_method(self, other, prefix=prefix):
            if not check_special_methods():
                raise NotImplementedError, 'Special method %s called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.'%(op_name, str(self))
            # This code will create one of two Deterministic objects.
            if prefix == 'r':
                # Right version: raises error on failure.
                parents = {'self':self, 'other':other, 'op':'__r' + op_name + '__'}
                def eval_fun(self,other,op):
                    out = getattr(self, op)(other)
                    if out is NotImplemented:
                        # the rt version has failed, meainng the lft version has failed as well.
                        raise TypeError, "unsupported operand type(s) for %s: '%s' and '%s'"%(op.replace('_',''), self.__class__.__name__, other.__class__.__name__)
                    return out
            else:
                # Left version: tries right version on failure.
                parents = {'self':self, 'other':other, 'op':'__' + op_name + '__', 'rt_op': '__r'+op_name+'__'}
                def eval_fun(self, other, op, rt_op):
                    out = getattr(self, op)(other)
                    if out is NotImplemented:
                        # if try the rt version.
                        out = getattr(other, rt_op)(self)
                    return out
            return pm.Deterministic(eval_fun,
                                    'A Deterministic returning the value of %s(%s,%s)'%(prefix+op_name,self.__name__, str(other)),
                                    '('+'_'.join([self.__name__,prefix+op_name,str(other)])+')',
                                    parents,
                                    trace=False,
                                    plot=False)
        # Convert the functions into methods for klass.
        new_method.__name__ = '__'+prefix+op_name+'__'
        setattr(klass, new_method.__name__, UnboundMethodType(new_method, None, klass))
Example #12
0
def create_uni_method(op_name, klass):
    """
    Creates a new univariate special method, such as A.__neg__() <=> -A,
    for target class. The method is called __op_name__.
    """
    # This function will become the actual method.
    def new_method(self):
        # This code creates a Deterministic object.
        def eval_fun(self,op=op):
            if not check_special_methods():
                raise NotImplementedError, 'Special method %s called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.'%(op_name, str(self))
            return getattr(self, op)()
        return pm.Deterministic(eval_fun,
                                'A Deterministic returning the value of %s(%s)'%(op_name, self.__name__),
                                '('+op_name+'_'+self.__name__+')',
                                {'self':self, 'op': '__'+op_name+'__'},
                                trace=False,
                                plot=False)
    # Make the function into a method for klass.
    new_method.__name__ = '__'+op_name+'__'
    setattr(klass, new_method.__name__, UnboundMethodType(new_method, None, klass))
Example #13
0
            return ret

        def _translate_newlines(self, data):
            data = data.replace("\r\n", "\n")
            data = data.replace("\r", "\n")
            return data

        if not SocketAdapter__del__:

            def __del__(self, close=os.close):
                fileno = self._fileno
                if fileno is not None:
                    close(fileno)

    if SocketAdapter__del__:
        SocketAdapter.__del__ = UnboundMethodType(SocketAdapter__del__, None,
                                                  SocketAdapter)

    class FileObjectPosix(_fileobject):
        def __init__(self, fobj, mode='rb', bufsize=-1, close=True):
            if isinstance(fobj, integer_types):
                fileno = fobj
                fobj = None
            else:
                fileno = fobj.fileno()
            sock = SocketAdapter(fileno, mode, close=close)
            self._fobj = fobj
            self._closed = False
            _fileobject.__init__(self,
                                 sock,
                                 mode=mode,
                                 bufsize=bufsize,
    jacobians = {'self': getitem_jacobian}
    jacobian_formats = {'self': 'index_operation'}
    return pm.Deterministic(eval_fun,
                            'A Deterministic returning the value of %s[%s]' %
                            (self.__name__, str(index)),
                            name, {
                                'self': self,
                                'index': index
                            },
                            trace=False,
                            plot=False,
                            jacobians=jacobians,
                            jacobian_formats=jacobian_formats)


Variable.__getitem__ = UnboundMethodType(__getitem__, None, Variable)

# Create __call__ method for Variable.


def __call__(self, *args, **kwargs):
    if not check_special_methods():
        raise NotImplementedError(
            'Special method __call__ called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.'
            % str(self))

    def eval_fun(self, args=args, kwargs=kwargs):
        return self(*args, **kwargs)

    return pm.Deterministic(
        eval_fun,
Example #15
0
def insert_method(instance, function):
    setattr(instance, function.__name__,
            UnboundMethodType(function, instance, instance.__class__))
Example #16
0
            else:
                if not self._translate or not data:
                    return data
                if self._eat_newline:
                    self._eat_newline = False
                    if data.startswith(b'\n'):
                        data = data[1:]
                        if not data:
                            return self.recv(size)
                if data.endswith(b'\r'):
                    self._eat_newline = True
                return self._translate_newlines(data)
            self.hub.wait(self._read_event)

    def _translate_newlines(self, data):
        data = data.replace(b"\r\n", b"\n")
        data = data.replace(b"\r", b"\n")
        return data

    if not SocketAdapter__del__:

        def __del__(self, close=os.close):
            fileno = self._fileno
            if fileno is not None:
                close(fileno)


if SocketAdapter__del__:
    SocketAdapter.__del__ = UnboundMethodType(SocketAdapter__del__, None,
                                              SocketAdapter)
Example #17
0
            assert_equal(y[0].value, y.value[0])

    def test_getitem(self):
        assert_equal(x[5](3).value, x[5].value(3))


for dnim in do_not_implement_methods:

    def meth(self, dnim=dnim):
        for y in x:
            if hasattr(y, '__%s__' % dnim):
                raise AssertionError('Method %s implemented in class %s' %
                                     (dnim, y.__class__))

    setattr(test_special_methods, 'test_' + dnim,
            UnboundMethodType(meth, None, test_special_methods))

for dnim in uni_methods:

    def meth(self, dnim=dnim):
        # These methods only work on integer-valued variables.
        if dnim in ['index', 'invert']:
            testvars = [x[3]]
        # All the others work on all numeric ar ndarray variables.
        else:
            testvars = x[:5]
        for y in testvars:
            assert_equal(
                getattr(y, '__%s__' % dnim)().value,
                getattr(y.value, '__%s__' % dnim)())