Пример #1
0
def instance_from_dict(d):
    """Returns a new DLite instance created from dict `d`, which should
    be of the same form as returned by the Instance.asdict() method.
    """
    meta = dlite.get_instance(d['meta'])
    if meta.is_metameta:
        try:
            return dlite.get_instance(d['uri'])
        except RuntimeError:
            pass
        dimensions = [
            dlite.Dimension(d['name'], d.get('description'))
            for d in d['dimensions']
        ]
        props = []
        dimmap = {dim['name']: i for i, dim in enumerate(d['dimensions'])}
        for p in d['properties']:
            if 'dims' in p:
                dims = [dimmap[d] for d in p['dims']]
            else:
                dims = None
            props.append(
                dlite.Property(p['name'], p['type'], dims, p.get('unit'),
                               p.get('description')))
        inst = dlite.Instance(d['uri'], dimensions, props,
                              d.get('description'))
    else:
        dims = list(d['dimensions'].values())
        inst = dlite.Instance(meta.uri, dims, d.get('uuid', None))
        for p in meta['properties']:
            inst[p.name] = d['properties'][p.name]
    return inst
Пример #2
0
 def _set_schema(self, schema):
     if not schema:
         self._schema = dlite.get_instance(dlite.ENTITY_SCHEMA)
     elif isinstance(schema, dlite.Instance):
         self._schema = schema
     elif isinstance(schema, str):
         self._schema = dlite.get_instance(schema)
     else:
         TypeError('`schema` must be a string or a DLite metadata schema.')
Пример #3
0
    def load(self, uuid):
        """Loads `uuid` from current storage and return it as a new instance."""
        uuid = dlite.get_uuid(uuid)
        q = sql.SQL('SELECT meta FROM uuidtable WHERE uuid = %s')
        self.cur.execute(q, [uuid])
        metaid, = self.cur.fetchone()
        q = sql.SQL('SELECT * FROM {} WHERE uuid = %s').format(
            sql.Identifier(metaid))
        self.cur.execute(q, [uuid])
        tokens = self.cur.fetchone()
        uuid_, uri, metaid_, dims = tokens[:4]
        values = tokens[4:]
        assert uuid_ == uuid
        assert metaid_ == metaid

        # Make sure we have metadata object correcponding to metaid
        try:
            with dlite.err():
                meta = dlite.get_instance(metaid)
        except RuntimeError:
            dlite.errclr()
            meta = self.load(metaid)

        inst = dlite.Instance.create_from_metaid(metaid, dims, uri)

        for i, p in enumerate(inst.meta['properties']):
            inst.set_property(p.name, values[i])

        # The uuid will be wrong for data instances, so override it
        if not inst.is_metameta:
            d = inst.asdict()
            d['uuid'] = uuid
            inst = instance_from_dict(d)
        return inst
Пример #4
0
def reaction_energy(coll, reactants, products):
    """Returns the calculated reaction energy.

    Args:
        coll: Collection with Substance instances.
        reactants: Dict with reactants.  It should map molecule names to
          their corresponding stoichiometric coefficient in the reaction
          formula.
        products: Dict with products.  It should map molecule names to
          their corresponding stoichiometric coefficient in the reaction
          formula.
    """
    energy = 0
    for label, n in reactants.items():
        substance = coll.get(label, substance_id)
        energy -= n * substance.molecule_energy

    for label, n in products.items():
        substance = coll.get(label, substance_id)
        energy += n * substance.molecule_energy

    # Instantiate a new Reaction instance
    Reaction = dlite.get_instance(reaction_id)
    reaction = Reaction(dims=[len(reactants), len(products)])
    reaction.reactants = list(reactants.keys())
    reaction.products = list(products.keys())
    reaction.reactant_stoichiometric_coefficient = list(reactants.values())
    reaction.product_stoichiometric_coefficient = list(products.values())
    reaction.energy = energy

    return reaction
Пример #5
0
 def load(self, uuid):
     """Loads `uuid` from current storage and return it as a new instance."""
     with open(self.uri, 'rb') as f:
         content = f.read()
     meta = dlite.get_instance('http://onto-ns.com/meta/0.1/Blob')
     inst = meta(dims=[len(content)])
     inst.content = np.frombuffer(content, dtype='uint8')
     return inst
Пример #6
0
    def load(self, uuid=None):
        """Loads `uuid` from current storage and return it as a new
        instance."""
        reader = getattr(pd, 'read_' + self.format)
        pdopts = optstring2keywords(self.options.get('pandas_opts', ''))
        metaid = self.options.meta if 'meta' in self.options else None
        data = reader(self.uri, **pdopts)
        rows, columns = data.shape

        if 'infer' not in self.options or dlite.asbool(self.options.infer):
            Meta = infer_meta(data, metaid, self.uri)
        elif metaid:
            Meta = dlite.get_instance(metaid)
        else:
            raise ValueError(
                'csv option `meta` must be provided if `infer` if false')

        inst = Meta(dims=(rows, ), id=self.options.get('id'))
        for i, name in enumerate(inst.properties):
            inst[i] = data.iloc[:, i]

        return inst
Пример #7
0
dim = Dimension('N')

prop = Property("a", type='float')

prop2 = Property("b",
                 type='string10',
                 dims=['I', 'J', 'K'],
                 description='something enlightening...')
assert any(prop2.dims)

props = myentity['properties']
props[0]

assert inst.meta == myentity

e = dlite.get_instance('http://onto-ns.com/meta/0.1/MyEntity')
assert e == myentity
assert e != inst

e2 = Instance.create_metadata(
    'http://onto-ns.com/meta/0.1/NewEntity',
    [Dimension('N', 'Number of something')], [
        Property('name', type='string', description='Name of something.'),
        Property('arr', type='int', dims=['N+2'], description='An array.'),
        Property('v', type='double', unit='m/s', description='Velocity')
    ], 'Something new...')

e3 = Instance.create_metadata('http://onto-ns.com/meta/0.1/NewEntity2', [], [
    Property('name', type='string', description='Name of something.'),
    Property('arr', type='int', description='An array.'),
    Property('v', type='double', unit='m/s', description='Velocity')
Пример #8
0
    for label, n in reaction.items():
        inst = make_instance(Substance, coll[label], mappings, mapsTo=mapsTo)
        energy += n * inst.molecule_energy
    return energy


# Import ontologies with mappings
molecules_onto = get_ontology(f'{thisdir}/mapping_mols.ttl').load()
reaction_onto = get_ontology(f'{thisdir}/mapping_substance.ttl').load()

# Convert to mappings to a single list of triples
mappings = list(molecules_onto.get_unabbreviated_triples())
mappings.extend(list(reaction_onto.get_unabbreviated_triples()))

# Obtain the Metadata to be mapped to each other
Molecule = dlite.get_instance('http://onto-ns.com/meta/0.1/Molecule')
Substance = dlite.get_instance('http://onto-ns.com/meta/0.1/Substance')

# Find mapping relation
# TODO: investigate what to do if the two cases
# use a different mappings relation. As of now it is a
# hard requirement that they use the same.
mapsTo = molecules_onto.mapsTo.iri

# Define where the molecule data is obtained from
# This is a dlite collection
coll = dlite.Collection.create_from_url(f'json://{atomdata}?mode=r#molecules')

# input from chemical engineer, e.g. what are reactants and products
# reactants (left side of equation) have negative stochiometric coefficient
# products (right side of equation) have positive stochiometric coefficient
Пример #9
0
dim = Dimension('N')

prop = Property("a", type='float')

# FIXME - property dimensions should be strings!
prop2 = Property("b",
                 type='string10',
                 dims=[2, 3, 4],
                 description='something enlightening...')

props = myentity['properties']
props[0]

assert inst.meta == myentity

e = dlite.get_instance('http://meta.sintef.no/0.1/MyEntity')
assert e == myentity
assert e != inst

e2 = Instance(
    'http://meta.sintef.no/0.1/NewEntity',
    [Dimension('N', 'Number of something')], [
        Property('name', type='string', description='Name of something.'),
        Property('arr', type='int', dims=[0], description='An array.'),
        Property('v', type='double', unit='m/s', description='Velocity')
    ], 'Something new...')

e3 = Instance('http://meta.sintef.no/0.1/NewEntity2', [], [
    Property('name', type='string', description='Name of something.'),
    Property('arr', type='int', description='An array.'),
    Property('v', type='double', unit='m/s', description='Velocity')
Пример #10
0
def instance_from_dict(d):
    """Returns a new DLite instance created from dict `d`, which should
    be of the same form as returned by the Instance.asdict() method.
    """
    meta = dlite.get_instance(d.get('meta', dlite.ENTITY_SCHEMA))
    if meta.is_metameta:

        if 'uri' in d:
            uri = d['uri']
        else:
            uri = dlite.join_meta_uri(d['name'], d['version'], d['namespace'])

        try:
            with dlite.silent:
                inst = dlite.get_instance(uri)
                if inst:
                    return inst
        except dlite.DLiteError:
            pass

        if isinstance(d['dimensions'], Sequence):
            dimensions = [
                dlite.Dimension(d['name'], d.get('description'))
                for d in d['dimensions']
            ]
        elif isinstance(d['dimensions'], Mapping):
            dimensions = [
                dlite.Dimension(k, v) for k, v in d['dimensions'].items()
            ]
        else:
            raise TypeError(
                "`dimensions` must be either a sequence or a mapping")

        props = []
        if isinstance(d['properties'], Sequence):
            for p in d['properties']:
                props.append(
                    dlite.Property(
                        name=p['name'],
                        type=p['type'],
                        dims=p.get('dims'),
                        unit=p.get('unit'),
                        description=p.get('description'),
                    ))
        elif isinstance(d['properties'], Mapping):
            for k, v in d['properties'].items():
                props.append(
                    dlite.Property(
                        name=k,
                        type=v['type'],
                        dims=v.get('dims'),
                        unit=v.get('unit'),
                        description=v.get('description'),
                    ))
        else:
            raise TypeError(
                "`properties` must be either a sequence or a mapping")

        inst = dlite.Instance.create_metadata(uri, dimensions, props,
                                              d.get('description'))
    else:
        dims = list(d['dimensions'].values())
        if 'uri' in d.keys():
            arg = d.get('uri', d.get('uuid', None))
        else:
            arg = d.get('uuid', None)
        inst = dlite.Instance.create_from_metaid(meta.uri, dims, arg)
        for p in meta['properties']:
            value = d['properties'][p.name]
            if p.type.startswith('blob'):
                if isinstance(value, str):
                    # Assume that the binary data string is hexadecimal
                    value = bytearray(binascii.unhexlify(value))
                elif isinstance(value, list) and len(value) > 1 \
                        and isinstance(value[1], str):
                    # Assume value = [binary string, encoding]
                    value = bytearray(value[0], value[1])
            if isinstance(inst[p.name], (float, int)):
                # Ensure correct scalar conversion by explicit cast
                inst[p.name] = type(inst[p.name])(value)
            else:
                inst[p.name] = value
    return inst