How to use the pydsdl.FloatType function in pydsdl

To help you get started, we’ve selected a few pydsdl examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github UAVCAN / pyuavcan / tests / dsdl_compiler.py View on Github external
def _make_random_object(data_type: pydsdl.SerializableType) -> typing.Any:
    if isinstance(data_type, pydsdl.BooleanType):
        return random.random() >= 0.5

    elif isinstance(data_type, pydsdl.IntegerType):  # noinspection PyTypeChecker
        return random.randint(int(data_type.inclusive_value_range.min),
                              int(data_type.inclusive_value_range.max))

    elif isinstance(data_type, pydsdl.FloatType):   # We want inf/nan as well, so we generate int and then reinterpret
        int_value = random.randrange(0, 2 ** data_type.bit_length)
        unpack_fmt, pack_fmt = {
            16: ('e', 'H'),
            32: ('f', 'I'),
            64: ('d', 'Q'),
        }[data_type.bit_length]
        fmt_prefix = '<'
        out, = struct.unpack(fmt_prefix + unpack_fmt, struct.pack(fmt_prefix + pack_fmt, int_value))
        return out

    elif isinstance(data_type, pydsdl.FixedLengthArrayType):
        return [_make_random_object(data_type.element_type) for _ in range(data_type.capacity)]

    elif isinstance(data_type, pydsdl.VariableLengthArrayType):
        length = random.randint(0, data_type.capacity)
        return [_make_random_object(data_type.element_type) for _ in range(length)]
github UAVCAN / pyuavcan / tests / dsdl / _util.py View on Github external
def make_random_object(model: pydsdl.SerializableType) -> typing.Any:
    """
    Returns an object of the specified DSDL type populated with random data.
    """
    def fifty_fifty() -> bool:
        return random.random() >= 0.5

    if isinstance(model, pydsdl.BooleanType):
        return fifty_fifty()

    elif isinstance(model, pydsdl.IntegerType):  # noinspection PyTypeChecker
        return random.randint(int(model.inclusive_value_range.min),
                              int(model.inclusive_value_range.max))

    elif isinstance(model, pydsdl.FloatType):   # We want inf/nan as well, so we generate int and then reinterpret
        int_value = random.randrange(0, 2 ** model.bit_length)
        unpack_fmt, pack_fmt = {
            16: ('e', 'H'),
            32: ('f', 'I'),
            64: ('d', 'Q'),
        }[model.bit_length]
        fmt_prefix = '<'
        out, = struct.unpack(fmt_prefix + unpack_fmt, struct.pack(fmt_prefix + pack_fmt, int_value))
        return out

    elif isinstance(model, pydsdl.FixedLengthArrayType):
        et = model.element_type
        if isinstance(et, pydsdl.UnsignedIntegerType) and et.bit_length == 8:   # Special case for faster testing
            out = numpy.random.randint(0, 256, size=model.capacity, dtype=numpy.uint8)
        else:
            out = [make_random_object(model.element_type) for _ in range(model.capacity)]
github UAVCAN / pyuavcan / tests / dsdl_compiler.py View on Github external
elif isinstance(data_type, pydsdl.CompositeType):
        if type(a) != type(b):  # pragma: no cover
            return False
        for f in pyuavcan.dsdl.get_type(a).fields_except_padding:  # pragma: no cover
            if not _are_close(f.data_type,
                              pyuavcan.dsdl.get_attribute(a, f.name),
                              pyuavcan.dsdl.get_attribute(b, f.name)):
                return False
        return True                 # Empty objects of same type compare equal

    elif isinstance(data_type, pydsdl.ArrayType):
        return all(starmap(partial(_are_close, data_type.element_type), zip(a, b))) \
            if len(a) == len(b) and a.dtype == b.dtype else False

    elif isinstance(data_type, pydsdl.FloatType):
        t = {
            16: numpy.float16,
            32: numpy.float32,
            64: numpy.float64,
        }[data_type.bit_length]
        return numpy.allclose(t(a), t(b), equal_nan=True)

    else:
        return numpy.allclose(a, b)
github UAVCAN / pyuavcan / pyuavcan / dsdl / _compiler.py View on Github external
def _numpy_scalar_type(t: pydsdl.Any) -> str:
    def pick_width(w: int) -> int:
        for o in [8, 16, 32, 64]:
            if w <= o:
                return o
        raise ValueError(f'Invalid bit width: {w}')  # pragma: no cover

    if isinstance(t, pydsdl.BooleanType):
        return f'_np_.bool'
    elif isinstance(t, pydsdl.SignedIntegerType):
        return f'_np_.int{pick_width(t.bit_length)}'
    elif isinstance(t, pydsdl.UnsignedIntegerType):
        return f'_np_.uint{pick_width(t.bit_length)}'
    elif isinstance(t, pydsdl.FloatType):
        return f'_np_.float{pick_width(t.bit_length)}'
    else:
        assert not isinstance(t, pydsdl.PrimitiveType), 'Forgot to handle some primitive types'
        return f'_np_.object_'
github UAVCAN / pyuavcan / pyuavcan / dsdl / _builtin_form.py View on Github external
elif isinstance(model, pydsdl.ArrayType):
        assert isinstance(obj, numpy.ndarray)
        if model.string_like:  # TODO: drop this special case when strings are natively supported in DSDL.
            try:
                return bytes(e for e in obj).decode()
            except UnicodeError:
                return list(map(int, obj))
        else:
            return [_to_builtin_impl(e, model.element_type) for e in obj]

    elif isinstance(model, pydsdl.PrimitiveType):
        # The explicit conversions are needed to get rid of NumPy scalar types.
        if isinstance(model, pydsdl.IntegerType):
            return int(obj)                         # type: ignore
        elif isinstance(model, pydsdl.FloatType):
            return float(obj)                       # type: ignore
        elif isinstance(model, pydsdl.BooleanType):
            return bool(obj)
        else:
            assert isinstance(obj, str)
            return obj

    else:
        assert False, 'Unexpected inputs'