Ejemplo n.º 1
0
def add_type_from_schema(path_to_schema, **kwargs):
    r"""Add a type from a schema in a file.

    Args:
        path_to_schema (string): Full path to the location of a schema file that
            can be loaded.
        target_globals (dict, optional): Globals dictionary for module where the
            fixed class should be added. If None, the new class is returned.
            Defaults to local globals.
        **kwargs: Additional keyword arguments are assumed to be attributes for
            the new class.

    """
    from yggdrasil.metaschema.datatypes.FixedMetaschemaType import (
        create_fixed_type_class)
    if 'target_globals' not in kwargs:
        kwargs['target_globals'] = globals()
    if not os.path.isfile(path_to_schema):
        raise ValueError("The 'path_to_schema' attribute is not a valid path: "
                         + "'%s'" % path_to_schema)
    with open(path_to_schema, 'r') as fd:
        out = decode_json(fd)
    jsonschema.validate(out, {'type': 'object',
                              'required': ['title', 'description', 'type']})
    name = out['title']
    if _type_registry.has_entry(name):
        assert(kwargs['target_globals'] is not None)
        return name
    description = out['description']
    base = get_type_class(out['type'])
    fixed_properties = out
    return create_fixed_type_class(name, description, base, fixed_properties,
                                   loaded_schema_file=path_to_schema, **kwargs)
Ejemplo n.º 2
0
        Returns:
            object: Python object of the specified type.

        """
        dtype = ScalarMetaschemaProperties.definition2dtype(typedef)
        if typedef['type'] == '1darray':
            out = np.zeros(typedef.get('length', 2), dtype)
        elif typedef['type'] == 'ndarray':
            out = np.zeros(typedef['shape'], dtype)
        else:
            out = np.zeros(1, dtype)[0]
        out = units.add_units(out, typedef.get('units', ''))
        return out


# Dynamically create explicity scalar classes for shorthand
for t in ScalarMetaschemaProperties._valid_types.keys():
    short_doc = 'A %s value with or without units.' % t
    long_doc = ('%s\n\n'
                '    Developer Notes:\n'
                '        Precision X is preserved.\n\n') % short_doc
    kwargs = {
        'target_globals': globals(),
        '__doc__': long_doc,
        '__module__': ScalarMetaschemaType.__module__,
        'python_types': ScalarMetaschemaProperties._python_scalars[t]
    }
    create_fixed_type_class(t, short_doc, ScalarMetaschemaType, {'subtype': t},
                            **kwargs)
Ejemplo n.º 3
0
        if units.is_null_unit(metadata.get('units', '')):
            out.remove('units')
        return out

    @classmethod
    def as_python_type(cls, obj, typedef):
        r"""Convert a possible numpy type into a native Python type if possible.

        Args:
            obj (object): Object to convert.
            typedef (dict): Type definition for the object.

        Returns:
            object: Native Python version of input object if conversion possible.

        """
        if ((isinstance(typedef, dict)
             and (typedef.get('type', '1darray') not in ['1darray', 'ndarray']))):
            stype = typedef.get('subtype', typedef.get('type', None))
            py_type = ScalarMetaschemaProperties._python_scalars[stype][0]
            if np.dtype(py_type) == type(obj):
                obj = py_type(obj)
        return obj


# Dynamically create explicity scalar classes for shorthand
for t in ScalarMetaschemaProperties._valid_types.keys():
    create_fixed_type_class(t, 'A %s value with or without units.' % t,
                            ScalarMetaschemaType, {'subtype': t}, globals(),
                            python_types=ScalarMetaschemaProperties._python_scalars[t])