Beispiel #1
0
def global_rif_operators_disable(quiet=False):
    "disable rif operators via numpy.set_numeric_opts"
    global _ORIG_NUMPY_OPS
    assert _ORIG_NUMPY_OPS
    np.set_numeric_ops(**_ORIG_NUMPY_OPS)
    _ORIG_NUMPY_OPS = None
    unwrap_broken_functions()
Beispiel #2
0
def use_vml(use_vml = True):
    """change numpy so that it uses by default some of the vectorized functions""" 
    if use_vml:
        if __old_numeric_ops is None:
            old_numeric_ops = numpy.set_numeric_ops(
                multiply = Mul,
                divide = Div,
                power = Pow,
                sqrt = Sqrt,
                square = Sqr)
    else:
        if __old_numeric_ops is not None:
            numpy.set_numeric_ops(**old_numeric_ops)
Beispiel #3
0
def divide_pie(groups):
    np.set_numeric_ops(suppress=True)
    number = 0
    rest = [1,1]
    for i in groups:
        number += abs(i)
    for i in groups:
        if i > 0:
            rest = calculate(rest,[i,number])
        else:
            rest = calculate(rest,[-i*rest[0],number*rest[1]])
    temp = math.gcd(rest[0],rest[1])
    return (int(rest[0]/temp),int(rest[1]/temp))
Beispiel #4
0
def main():
    # Scalar case works.
    a = Custom('a')
    print(a == a)
    # Not what we want.
    av = np.array([a, a])
    print(np.equal(av, av))
    # Try custom ufunc:
    generic_equal = np.frompyfunc(lambda a, b: a == b, 2, 1)
    print(generic_equal(av, av))
    # Try replacing.
    np.set_numeric_ops(equal=generic_equal)
    print(av == av)
    print(np.equal(av, av))
    # Now replace original ufunc.
    np.equal = generic_equal
    print(np.equal(av, av))
Beispiel #5
0
def set_numpy_operators():
    import atexit

    global _previous_operators

    _previous_operators = numpy.set_numeric_ops(
        multiply=numpy_multiply_operator, divide=numpy_div_operator, true_divide=numpy_true_div_operator
    )
    atexit.register(unset_numpy_operators)
Beispiel #6
0
def set_numpy_operators():
    import atexit

    global _previous_operators

    _previous_operators = numpy.set_numeric_ops(
        multiply=numpy_multiply_operator,
        divide=numpy_div_operator,
        true_divide=numpy_true_div_operator)
    atexit.register(unset_numpy_operators)
Beispiel #7
0
def global_rif_operators_enable(quiet=False):
    "enable rif operators via numpy.set_numeric_opts"
    global _ORIG_NUMPY_OPS
    if rif_operators_are_enabled():
        print('warning: global_rif_ops is already enabled')
    else:
        d1 = {ufunc: _override1(ufunc) for ufunc in _opmap1.values()}
        d2 = {ufunc: _override2(ufunc) for ufunc in _opmap2.values()}
        d1.update(d2)
        _ORIG_NUMPY_OPS = np.set_numeric_ops(**d1)
        wrap_broken_functions()
Beispiel #8
0
def unset_numpy_operators():
    global _previous_operators
    numpy.set_numeric_ops(**_previous_operators)
Beispiel #9
0
            return self.grid.array(data ** a, shape)

    def sum(self, axis=None):
        if axis is None:
            data = self._data.reshape((self.grid.nx, self.grid.ny, -1)).sum(2)
            return self.grid.array(data, ())
        else:
            data = self._data.sum(axis + 2)
            return self.grid.array(data, data.shape[2:])


# ==============================================================================#
#                           replace numpy operations                           #
# ==============================================================================#

if np.set_numeric_ops()["add"] == np.add:

    def _add(x1, x2, out=None):
        if isinstance(x2, psarray_base):
            return x2.__add__(x1)
        else:
            return np.add(x1, x2, out)

    np.set_numeric_ops(add=_add)

if np.set_numeric_ops()["subtract"] == np.subtract:

    def _sub(x1, x2, out=None):
        if isinstance(x2, psarray_base):
            return (-x2).__add__(x1)
        else:
Beispiel #10
0
    __array_priority__ = 100

def override(name):
    if name == "equal":
        def ufunc(x, y):
            print y
            if isinstance(y, Bar1) or \
               isinstance(y, np.ndarray) and isinstance(y[0], Bar1):
                return NotImplemented
            return getattr(np, name)(x, y)
        return ufunc
    else:
        def ufunc(x, y):
            print y
            if isinstance(y, Bar1): 
                return NotImplemented
            return getattr(np, name)(x, y)
        return ufunc

np.set_numeric_ops(
    ** {
        ufunc : override(ufunc) for ufunc in (
            "less_equal", "equal", "greater_equal"
        )
    }
)

b = Bar1()
print a == b
print a <= b
print a + b
Beispiel #11
0
            y._data = data ** a
            y._shape = (np.ones(self.shape) ** a).shape
        return y

    def sum(self, axis=None):
        y = self.grid.array(None)
        y._data = self._data.sum(axis + 2)
        y._shape = y._data.shape[2:]
        return y


#==============================================================================#
#                           replace numpy operations                           #
#==============================================================================#

if np.set_numeric_ops()['add'] == np.add:
    def _add(x1, x2, out=None):
        if isinstance(x2, psarray_base):
            return x2.__add__(x1)
        else:
            return np.add(x1, x2, out)
    np.set_numeric_ops(add=_add)

if np.set_numeric_ops()['subtract'] == np.subtract:
    def _sub(x1, x2, out=None):
        if isinstance(x2, psarray_base):
            return (-x2).__add__(x1)
        else:
            return np.subtract(x1, x2, out)
    np.set_numeric_ops(subtract=_sub)
import Sofa
import numpy as np


def unsafe_multiply(a, b):
    if isinstance(b, Sofa.Core.Data):
        return np.multiply(a, b.value, casting="unsafe")
    return np.multiply(a, b, casting="unsafe")


np.set_numeric_ops(multiply=unsafe_multiply)


class MyController(Sofa.BaseController):
    def __init__(self, *args, **kwargs):
        Sofa.BaseController.__init__(self, *args, *kwargs)

    def onEvent(self, value):
        print("EVEnt " + value)


class MyForceField(Sofa.ForceField):
    def __init__(self, *args, **kwargs):
        kwargs["ks"] = kwargs.get("ks", 1.0)
        kwargs["kd"] = kwargs.get("kd", 2.0)
        Sofa.ForceField.__init__(self, *args, **kwargs)

    def init(self):
        self.initpos = self.mstate.position.array().copy()

    def addForce(self, m, out_force, pos, vel):
Beispiel #13
0
"""
"""
import numpy as np
from lsqpy.exprs.affine import Affine
from lsqpy.exprs.variable import Variable

def override(name):
	def ufunc(x, y):
		if isinstance(y, Affine): return NotImplemented
		return getattr(np, name)(x, y)
	return ufunc

np.set_numeric_ops(
	** {
		ufunc : override(ufunc) for ufunc in ("equal")
	}
)
Beispiel #14
0
    if name == "equal":

        def ufunc(x, y):
            print(y)
            if isinstance(y, Bar1) or \
               isinstance(y, np.ndarray) and isinstance(y[0], Bar1):
                raise NotImplementedError()
            return getattr(np, name)(x, y)

        return ufunc
    else:

        def ufunc(x, y):
            print(y)
            if isinstance(y, Bar1):
                raise NotImplementedError()
            return getattr(np, name)(x, y)

        return ufunc


np.set_numeric_ops(**{
    ufunc: override(ufunc)
    for ufunc in ("less_equal", "equal", "greater_equal")
})

b = Bar1()
print(a == b)
print(a <= b)
print(a + b)
Beispiel #15
0
        return self.accumulate_priop(*args, **kwargs)

    def outer(self, *args, **kwargs):
        """Calls ``.outer`` with *args* and *kwargs*."""

        return self.outer_priop(*args, **kwargs)

#
# Define the ``ufunc`` instances to be used with numpy ...
#
# We can only define ufuncs for those operations supported by 
# ``numpy.set_numeric_ops()``.
#

original = numpy.set_numeric_ops()

absolute = ufunc(name='absolute')
absolute.add_ufunc(ufunc=original['absolute'], 
    classes=(None, None))

add = ufunc(name='add')
add.add_ufunc(ufunc=original['add'],
    classes=(None, None))

bitwise_and = ufunc(name='bitwise_and')
bitwise_and.add_ufunc(ufunc=original['bitwise_and'],
    classes=(None, None))

bitwise_or = ufunc(name='bitwise_or')
bitwise_or.add_ufunc(ufunc=original['bitwise_or'],
Beispiel #16
0
            y._data = data**a
            y.shape = (np.ones(self.shape)**a).shape
        return y

    def sum(self, axis=None):
        y = self.grid.array(None)
        y._data = self._data.sum(axis + 2)
        y.shape = y._data.shape[2:]
        return y


#==============================================================================#
#                           replace numpy operations                           #
#==============================================================================#

if np.set_numeric_ops()['add'] == np.add:

    def _add(x1, x2, out=None):
        if isinstance(x2, psarray_base):
            return x2.__add__(x1)
        else:
            return np.add(x1, x2, out)

    np.set_numeric_ops(add=_add)

if np.set_numeric_ops()['subtract'] == np.subtract:

    def _sub(x1, x2, out=None):
        if isinstance(x2, psarray_base):
            return (-x2).__add__(x1)
        else:
Beispiel #17
0
#
# When executing this, NUMPYARRAY.__mul__() is called, or, equivalently,
# numpy.multiply().  This function checkes whether the other operand is an
# numpy.ndarray, and if not, it treats it as scalar and applies the operation
# to all elements of the numpy.ndararray NUMPYARRAY.  This is not what was
# expected.  The call executes properly if upyarray.__rmul__() is being 
# called, which is done by the wrapper functions below.  The wrapper
# functions only handle this special case, all other cases are handed over to
# numpy functions.  The wrapper functions are registered in numpy via
# numpy.set_arithmetic_ops().

# Arithmetic operators ...

# We store the original numpy settings, then create the callable objects,
# which take their .ufunc attribute from this array.
original_numpy_ops = numpy.set_numeric_ops()

class ufuncWrap:
    """Wraps numpy ufuncs.  Behaves like the original, with the exception
    that __call__() will be overloaded."""

    def __init__(self, ufunc_name, overload):
        """UFUNC is the ufunc to be wrapped.  OVERLOAD is the name (string)
        of the undarray method to be used in overloading __call__()."""

        self.ufunc_name = ufunc_name
        self.ufunc = original_numpy_ops[ufunc_name]
        self.overload = overload

    def __call__(self, a, b, *args, **kwargs):
        """When B is an undarray, call B.overload(a), else .ufunc(a, b)."""
Beispiel #18
0
def unset_numpy_operators():
    global _previous_operators
    numpy.set_numeric_ops(**_previous_operators)
def override_set_numeric_ops():
    def_ops = np.set_numeric_ops()
    new_ops ={}
    for name, call in def_ops.items():
        new_ops[name] = make_overridable(call)
    np.set_numeric_ops(**new_ops)