Esempio n. 1
0
def test_construction():
    ''' Test the construction of quantity objects '''
    q = 500 * ms
    assert_quantity(q, 0.5, second)
    q = np.float64(500) * ms
    assert_quantity(q, 0.5, second)
    q = np.array(500) * ms
    assert_quantity(q, 0.5, second)
    q = np.array([500, 1000]) * ms
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity(500)
    assert_quantity(q, 500, 1)
    q = Quantity(500, dim=second.dim)
    assert_quantity(q, 500, second)
    q = Quantity([0.5, 1], dim=second.dim)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity(np.array([0.5, 1]), dim=second.dim)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity([500 * ms, 1 * second])
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = [0.5, 1] * second
    assert_quantity(q, np.array([0.5, 1]), second)

    # dimensionless quantities
    q = Quantity([1, 2, 3])
    assert_quantity(q, np.array([1, 2, 3]), Unit(1))
    q = Quantity(np.array([1, 2, 3]))
    assert_quantity(q, np.array([1, 2, 3]), Unit(1))
    q = Quantity([])
    assert_quantity(q, np.array([]), Unit(1))

    # copying/referencing a quantity
    q1 = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    q2 = Quantity(q1) # no copy
    assert_quantity(q2, np.asarray(q1), q1)
    q2[0] = 3 * second
    assert_equal(q1[0], 3*second)

    q1 = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    q2 = Quantity(q1, copy=True) # copy
    assert_quantity(q2, np.asarray(q1), q1)
    q2[0] = 3 * second
    assert_equal(q1[0], 0.5*second)

    # Illegal constructor calls
    assert_raises(TypeError, lambda: Quantity([500 * ms, 1]))
    assert_raises(TypeError, lambda: Quantity(['some', 'nonsense']))
    assert_raises(DimensionMismatchError, lambda: Quantity([500 * ms,
                                                            1 * volt]))
    assert_raises(DimensionMismatchError, lambda: Quantity([500 * ms],
                                                           dim=volt.dim))
    q = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    assert_raises(DimensionMismatchError, lambda: Quantity(q, dim=volt.dim))
Esempio n. 2
0
def test_construction():
    ''' Test the construction of quantity objects '''
    q = 500 * ms
    assert_quantity(q, 0.5, second)
    q = np.float64(500) * ms
    assert_quantity(q, 0.5, second)
    q = np.array(500) * ms
    assert_quantity(q, 0.5, second)
    q = np.array([500, 1000]) * ms
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity(500)
    assert_quantity(q, 500, 1)
    q = Quantity(500, dim=second.dim)
    assert_quantity(q, 500, second)
    q = Quantity([0.5, 1], dim=second.dim)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity(np.array([0.5, 1]), dim=second.dim)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity([500 * ms, 1 * second])
    assert_quantity(q, np.array([0.5, 1]), second)
    q = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    assert_quantity(q, np.array([0.5, 1]), second)
    q = [0.5, 1] * second
    assert_quantity(q, np.array([0.5, 1]), second)

    # dimensionless quantities
    q = Quantity([1, 2, 3])
    assert_quantity(q, np.array([1, 2, 3]), Unit(1))
    q = Quantity(np.array([1, 2, 3]))
    assert_quantity(q, np.array([1, 2, 3]), Unit(1))
    q = Quantity([])
    assert_quantity(q, np.array([]), Unit(1))

    # copying/referencing a quantity
    q1 = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    q2 = Quantity(q1)  # no copy
    assert_quantity(q2, np.asarray(q1), q1)
    q2[0] = 3 * second
    assert_equal(q1[0], 3 * second)

    q1 = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    q2 = Quantity(q1, copy=True)  # copy
    assert_quantity(q2, np.asarray(q1), q1)
    q2[0] = 3 * second
    assert_equal(q1[0], 0.5 * second)

    # Illegal constructor calls
    assert_raises(TypeError, lambda: Quantity([500 * ms, 1]))
    assert_raises(TypeError, lambda: Quantity(['some', 'nonsense']))
    assert_raises(DimensionMismatchError,
                  lambda: Quantity([500 * ms, 1 * volt]))
    assert_raises(DimensionMismatchError,
                  lambda: Quantity([500 * ms], dim=volt.dim))
    q = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
    assert_raises(DimensionMismatchError, lambda: Quantity(q, dim=volt.dim))
Esempio n. 3
0
 def wrapper_function(*args):
     if not len(args) == len(self._function._arg_units):
         raise ValueError(('Function %s got %d arguments, '
                           'expected %d') % (self._function.pyfunc.__name__, len(args),
                                             len(self._function._arg_units)))
     new_args = [Quantity.with_dimensions(arg, get_dimensions(arg_unit))
                 for arg, arg_unit in zip(args, self._function._arg_units)]
     result = orig_func(*new_args)
     return_unit = self._function._return_unit
     if return_unit is 1 or return_unit.dim is DIMENSIONLESS:
         fail_for_dimension_mismatch(result,
                                     return_unit,
                                     'The function %s returned '
                                     '{value}, but it was expected '
                                     'to return a dimensionless '
                                     'quantity' % orig_func.__name__,
                                     value=result)
     else:
         fail_for_dimension_mismatch(result,
                                     return_unit,
                                     ('The function %s returned '
                                      '{value}, but it was expected '
                                      'to return a quantity with '
                                      'units %r') % (orig_func.__name__,
                                                     return_unit),
                                     value=result)
     return np.asarray(result)
Esempio n. 4
0
 def wrapper_function(*args):
     if not len(args) == len(self._function._arg_units):
         raise ValueError(('Function %s got %d arguments, '
                           'expected %d') % (self._function.name, len(args),
                                             len(self._function._arg_units)))
     new_args = [Quantity.with_dimensions(arg, get_dimensions(arg_unit))
                 for arg, arg_unit in zip(args, self._function._arg_units)]
     result = orig_func(*new_args)
     fail_for_dimension_mismatch(result, self._function._return_unit)
     return np.asarray(result)
Esempio n. 5
0
 def new_f(*args, **kwds):
     newargs = []
     newkwds = {}
     for arg in args:
         newargs.append(modify_arg(arg))
     for k, v in kwds.items():
         newkwds[k] = modify_arg(v)
     rv = f(*newargs, **newkwds)
     if rv.__class__==b1h.Sound:
         rv.__class__ = BridgeSound
     elif isinstance(rv, b1.Quantity):
         rv = Quantity.with_dimensions(float(rv), rv.dim._dims)
     return rv
Esempio n. 6
0
 def new_f(*args, **kwds):
     newargs = []
     newkwds = {}
     for arg in args:
         newargs.append(modify_arg(arg))
     for k, v in kwds.items():
         newkwds[k] = modify_arg(v)
     rv = f(*newargs, **newkwds)
     if rv.__class__==b1h.Sound:
         rv.__class__ = BridgeSound
     elif isinstance(rv, b1.Quantity):
         rv = Quantity.with_dimensions(float(rv), rv.dim._dims)
     return rv
Esempio n. 7
0
 def wrapper_function(*args):
     if not len(args) == len(self._function._arg_units):
         raise ValueError(
             ('Function %s got %d arguments, '
              'expected %d') % (self._function.name, len(args),
                                len(self._function._arg_units)))
     new_args = [
         Quantity.with_dimensions(arg, get_dimensions(arg_unit))
         for arg, arg_unit in zip(args, self._function._arg_units)
     ]
     result = orig_func(*new_args)
     fail_for_dimension_mismatch(result,
                                 self._function._return_unit)
     return np.asarray(result)
Esempio n. 8
0
            def wrapper_function(*args):
                arg_units = list(self._function._arg_units)

                if self._function.auto_vectorise:
                    arg_units += [DIMENSIONLESS]
                if not len(args) == len(arg_units):
                    raise ValueError(('Function %s got %d arguments, '
                                      'expected %d') % (self._function.pyfunc.__name__, len(args),
                                                        len(arg_units)))
                new_args = []
                for arg, arg_unit in zip(args, arg_units):
                    if arg_unit == bool or arg_unit is None or isinstance(arg_unit, str):
                        new_args.append(arg)
                    else:
                        new_args.append(Quantity.with_dimensions(arg,
                                                                 get_dimensions(arg_unit)))
                result = orig_func(*new_args)
                if isinstance(self._function._return_unit, Callable):
                    return_unit = self._function._return_unit(*[get_dimensions(a)
                                                                for a in args])
                else:
                    return_unit = self._function._return_unit
                if return_unit == bool:
                    if not (isinstance(result, bool) or
                            np.asarray(result).dtype == bool):
                        raise TypeError('The function %s returned '
                                        '%s, but it was expected '
                                        'to return a boolean '
                                        'value ' % (orig_func.__name__,
                                                    result))
                elif (isinstance(return_unit, int) and return_unit == 1) or return_unit.dim is DIMENSIONLESS:
                    fail_for_dimension_mismatch(result,
                                                return_unit,
                                                'The function %s returned '
                                                '{value}, but it was expected '
                                                'to return a dimensionless '
                                                'quantity' % orig_func.__name__,
                                                value=result)
                else:
                    fail_for_dimension_mismatch(result,
                                                return_unit,
                                                ('The function %s returned '
                                                 '{value}, but it was expected '
                                                 'to return a quantity with '
                                                 'units %r') % (orig_func.__name__,
                                                                return_unit),
                                                value=result)
                return np.asarray(result)
Esempio n. 9
0
            def wrapper_function(*args):
                arg_units = list(self._function._arg_units)

                if self._function.auto_vectorise:
                    arg_units += [DIMENSIONLESS]
                if not len(args) == len(arg_units):
                    func_name = self._function.pyfunc.__name__
                    raise ValueError(
                        f"Function {func_name} got {len(args)} arguments, "
                        f"expected {len(arg_units)}.")
                new_args = []
                for arg, arg_unit in zip(args, arg_units):
                    if arg_unit == bool or arg_unit is None or isinstance(
                            arg_unit, str):
                        new_args.append(arg)
                    else:
                        new_args.append(
                            Quantity.with_dimensions(arg,
                                                     get_dimensions(arg_unit)))
                result = orig_func(*new_args)
                if isinstance(self._function._return_unit, Callable):
                    return_unit = self._function._return_unit(
                        *[get_dimensions(a) for a in args])
                else:
                    return_unit = self._function._return_unit
                if return_unit == bool:
                    if not (isinstance(result, bool)
                            or np.asarray(result).dtype == bool):
                        raise TypeError(
                            f"The function {orig_func.__name__} returned "
                            f"'{result}', but it was expected to return a "
                            f"boolean value ")
                elif (isinstance(return_unit, int) and return_unit
                      == 1) or return_unit.dim is DIMENSIONLESS:
                    fail_for_dimension_mismatch(
                        result, return_unit,
                        f"The function '{orig_func.__name__}' "
                        f"returned {result}, but it was "
                        f"expected to return a dimensionless "
                        f"quantity.")
                else:
                    fail_for_dimension_mismatch(
                        result, return_unit,
                        f"The function '{orig_func.__name__}' "
                        f"returned {result}, but it was "
                        f"expected to return a quantity with "
                        f"units {return_unit!r}.")
                return np.asarray(result)
Esempio n. 10
0
def convert_unit_b1_to_b2(val):
    return Quantity.with_dimensions(float(val), arg.dim._dims)
Esempio n. 11
0
def convert_unit_b1_to_b2(val):
    return Quantity.with_dimensions(float(val), arg.dim._dims)
Esempio n. 12
0
def get_unit_fast(x):
    """ Return a `Quantity` with value 1 and the same dimensions. """
    return Quantity.with_dimensions(1, get_dimensions(x))
Esempio n. 13
0
def get_unit_fast(x):
    """ Return a `Quantity` with value 1 and the same dimensions. """
    return Quantity.with_dimensions(1, get_dimensions(x))