Skip to content

Commit

Permalink
Further satisfy pylint
Browse files Browse the repository at this point in the history
  • Loading branch information
CasperWA committed Oct 14, 2021
1 parent fd7f451 commit af952a7
Show file tree
Hide file tree
Showing 20 changed files with 274 additions and 220 deletions.
7 changes: 4 additions & 3 deletions demo/horizontal/emmo2meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,12 +174,13 @@ def get_properties(self, cls): # pylint: disable=too-many-locals
def get_dim(restriction, name, descr=None):
"""Returns dimension index corresponding to dimension name `name`
for property `restriction.value`."""
# pylint: disable=protected-access
result = []
restriction_type = (
owlready2.class_construct._restriction_type_2_label[
restriction.type
]
) # pylint: disable=protected-access
)
if restriction_type in ("some", "only", "min") or (
restriction_type in ("max", "exactly")
and restriction.cardinality > 1
Expand Down Expand Up @@ -272,9 +273,9 @@ def get_dim(restriction, name, descr=None):

def add_restriction(self, restriction):
"""Adds owl restriction to collection and returns a reference to it."""
restriction_type = owlready2.class_construct._restriction_type_2_label[
restriction_type = owlready2.class_construct._restriction_type_2_label[ # pylint: disable=protected-access
restriction.type
] # pylint: disable=protected-access
]
cardinality = restriction.cardinality if restriction.cardinality else 0
entity = self.add_restriction_entity()
inst = entity()
Expand Down
6 changes: 3 additions & 3 deletions demo/horizontal/step1_generate_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
"""
import os

from ontopy import get_ontology
from emmo2meta import EMMO2Meta
from ontopy import get_ontology


# Load our ontology from the vertical case
Expand Down Expand Up @@ -51,5 +51,5 @@
e.save("json", "usercase_metadata.json", "mode=w")

print("Generated metadata for the usercase ontology:")
print(" %d instances" % e.coll.count())
print(" %d relations" % len(list(e.coll.relations())))
print(f" {e.coll.count()} instances")
print(f" {len(list(e.coll.relations()))} relations")
11 changes: 6 additions & 5 deletions demo/horizontal/step2_define_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
adds some methods for handling some special attributes.
"""
# pylint: disable=import-error
import ase
from ase.spacegroup import Spacegroup

Expand All @@ -23,14 +24,14 @@
BaseAtoms = dlite.classfactory(ase.Atoms, url="json://atoms.json?mode=r#")


class DLiteAtoms(BaseAtoms):
class DLiteAtoms(BaseAtoms): # pylint: disable=too-few-public-methods
"""ASE Atoms class extended as a dlite entity."""

def _dlite_get_info(self):
d = self.info.copy()
sg = Spacegroup(d.get("spacegroup", "P 1"))
d["spacegroup"] = sg.symbol
return [(k, str(v)) for k, v in d.items()]
info = self.info.copy()
space_group = Spacegroup(info.get("spacegroup", "P 1"))
info["spacegroup"] = space_group.symbol
return [(key, str(value)) for key, value in info.items()]

def _dlite_set_info(self, value):
self.info.update(value)
Expand Down
37 changes: 19 additions & 18 deletions demo/horizontal/step4_map_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,20 @@
a atomistic Al-Fe4Al13 interface structure from a cif file and
represents it using the same metadata framework as used in step 1.
"""
# pylint: disable=import-error,invalid-name
import dlite


def map_app2common(inst, metacoll, out_id=None):
"""Maps atom structure `inst` from our application representation
def map_app2common(instance, meta_collection, out_id=None):
"""Maps atom structure `instance` from our application representation
(based on a not explicitly stated ontology) to the common
EMMO-based representation in `metacoll`.
EMMO-based representation in `meta_collection`.
Parameters
----------
inst : Instance of http://sintef.no/meta/soft/0.1/Atoms
instance : Instance of http://sintef.no/meta/soft/0.1/Atoms
Input atom structure.
metacoll : Collection
meta_collection : Collection
Collection of EMMO-based metadata generated from the ontology.
out_id : None | string
An optional id associated with the returned collection.
Expand All @@ -32,21 +33,21 @@ def map_app2common(inst, metacoll, out_id=None):
-------
atcoll : Collection
New collection with the atom structure represented as instances
of metadata in `metacoll`.
of metadata in `meta_collection`.
Notes
-----
We use lowercase and underscore notation for the individuals.
"""
infodict = dict(inst.info) # make dict out of the info field
infodict = dict(instance.info) # make dict out of the info field

# Create new collection representing `inst` in our case ontology
# Create new collection representing `instance` in our case ontology
atcoll = dlite.Collection(out_id)

# Get metadata from metacoll
Crystal = metacoll["Crystal"]
UnitCell = metacoll["CrystalUnitCell"]
EBondedAtom = metacoll["BondedAtom"]
# Get metadata from meta_collection
Crystal = meta_collection["Crystal"]
UnitCell = meta_collection["CrystalUnitCell"]
EBondedAtom = meta_collection["BondedAtom"]

# Instanciate the structure
crystal = Crystal([])
Expand All @@ -58,12 +59,12 @@ def map_app2common(inst, metacoll, out_id=None):
atcoll.add("unit_cell", unit_cell)
atcoll.add_relation("crystal", "hasSpatialDirectPart", "unit_cell")

for i in range(inst.natoms):
label = "atom%d" % i
a = EBondedAtom([3])
a.AtomicNumber = inst.numbers[i]
a.Position = inst.positions[i]
atcoll.add(label, a)
for index in range(instance.natoms):
label = f"atom{index}"
atom = EBondedAtom([3])
atom.AtomicNumber = instance.numbers[index]
atom.Position = instance.positions[index]
atcoll.add(label, atom)
atcoll.add_relation("unit_cell", "hasSpatialDirectPart", label)

return atcoll
Expand Down
9 changes: 7 additions & 2 deletions demo/vertical/define_ontology.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
[1] Khalid et al. Proc. Manufact. 15 (2018) 1407
"""
# pylint: disable=fixme,invalid-name,too-few-public-methods
from ontopy import World


Expand All @@ -56,8 +57,6 @@
class hasType(emmo.hasConvention):
"""Associates a type (string, number...) to a property."""

pass

class isTypeOf(emmo.hasConvention):
"""Associates a property to a type (string, number...)."""

Expand All @@ -69,10 +68,14 @@ class isTypeOf(emmo.hasConvention):

# TODO: remove
class SquareLengthDimension(emmo.PhysicalDimension):
"""Squared length dimension."""

is_a = [emmo.hasSymbolData.value("T0 L2 M0 I0 Θ0 N0 J0")]

# TODO: remove
class SquareMetre(emmo.SICoherentDerivedUnit):
"""A square metre unit."""

emmo.altLabel = ["m²"]
is_a = [emmo.hasPhysicalDimension.only(SquareLengthDimension)]

Expand Down Expand Up @@ -177,6 +180,8 @@ class CrystalUnitCell(emmo.Material):
]

class InterfaceModel(CrystalUnitCell):
"""A crystal interface."""

is_a = [emmo.hasProperty.some(Area)]

class Crystal(emmo.Solid):
Expand Down
5 changes: 3 additions & 2 deletions emmopy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
"""# `emmopy`"""
import sys
from ontopy import __version__ as __ontopy_version__

Expand All @@ -9,11 +10,11 @@
raise RuntimeError("emmopy requires Python 3.6 or later")

# Ensure emmopy is imported before owlready2...
if "owlready2" in sys.modules.keys() and "ontopy" not in sys.modules.keys():
if "owlready2" in sys.modules and "ontopy" not in sys.modules:
raise RuntimeError("emmopy must be imported before owlready2")

# Import functions from emmopy
from .emmopy import get_emmo
from .emmopy import get_emmo # pylint: disable=wrong-import-position


__all__ = ("get_emmo",)
6 changes: 3 additions & 3 deletions emmopy/emmocheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
- name_of_test_to_skip
"""
import os
import sys
import re
import unittest
Expand Down Expand Up @@ -85,8 +84,9 @@ def test_number_of_labels(self):
)

if (
"prefLabel" in self.onto.world._props
): # pylint: disable=protected-access
"prefLabel"
in self.onto.world._props # pylint: disable=protected-access
):
for entity in self.onto.get_entities():
if repr(entity) not in exceptions:
with self.subTest(
Expand Down
8 changes: 7 additions & 1 deletion emmopy/emmopy.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from ontopy import get_ontology
"""# `emmopy.emmopy`
Automagically retrieve the EMMO utilizing
[`ontopy.get_ontology`][ontopy.get_ontology].
"""
from typing import Optional, TYPE_CHECKING

from ontopy import get_ontology

if TYPE_CHECKING:
from ontopy.ontology import Ontology

Expand Down
4 changes: 2 additions & 2 deletions ontopy/colortest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@

from blessings import Terminal
from pygments import formatters, highlight
from pygments.lexers import (
from pygments.lexers import ( # pylint: disable=no-name-in-module
Python3TracebackLexer as Lexer,
) # pylint: disable=no-name-in-module
)


class ColourTextTestResult(TestResult):
Expand Down
52 changes: 30 additions & 22 deletions ontopy/factpluspluswrapper/factppgraph.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""# `ontopy.factpluspluswrapper.factppgraph`"""
# pylint: disable=too-few-public-methods
from rdflib import URIRef, OWL, RDF, RDFS

from ontopy.factpluspluswrapper.owlapi_interface import OwlApiInterface
Expand Down Expand Up @@ -72,58 +74,64 @@ def add_base_annotations(self):
"""Copy base annotations from original graph to the inferred graph."""
base = self.base_iri
inferred = self.inferred
for s, p, o in self.graph.triples(
for _, predicate, obj in self.graph.triples(
(self.asserted_base_iri(), None, None)
):
if p == OWL.versionIRI:
version = o.rsplit("/", 1)[-1]
o = URIRef("%s/%s" % (base, version))
inferred.add((base, p, o))
if predicate == OWL.versionIRI:
version = obj.rsplit("/", 1)[-1]
obj = URIRef(f"{base}/{version}")
inferred.add((base, predicate, obj))

def set_namespace(self):
"""Override namespace of inferred graph with the namespace of the
original graph.
"""
inferred = self.inferred
for k, v in self.namespaces.items():
inferred.namespace_manager.bind(k, v, override=True, replace=True)
for key, value in self.namespaces.items():
inferred.namespace_manager.bind(
key, value, override=True, replace=True
)

def clean_base(self):
"""Remove all relations `s? a owl:Ontology` where `s?` is not
`base_iri`.
"""
inferred = self.inferred
for s, p, o in inferred.triples((None, RDF.type, OWL.Ontology)):
inferred.remove((s, p, o))
for subject, predicate, obj in inferred.triples(
(None, RDF.type, OWL.Ontology)
):
inferred.remove((subject, predicate, obj))
inferred.add((self.base_iri, RDF.type, OWL.Ontology))

def remove_nothing_is_nothing(self):
"""Remove superfluid relation in inferred graph:
owl:Nothing rdfs:subClassOf owl:Nothing
"""
t = OWL.Nothing, RDFS.subClassOf, OWL.Nothing
triple = OWL.Nothing, RDFS.subClassOf, OWL.Nothing
inferred = self.inferred
if t in inferred:
inferred.remove(t)
if triple in inferred:
inferred.remove(triple)

def clean_ancestors(self):
"""Remove redundant rdfs:subClassOf relations in inferred graph."""
inferred = self.inferred
for s in inferred.subjects(RDF.type, OWL.Class):
if isinstance(s, URIRef):
for ( # pylint: disable=too-many-nested-blocks
subject
) in inferred.subjects(RDF.type, OWL.Class):
if isinstance(subject, URIRef):
parents = set(
p
for p in inferred.objects(s, RDFS.subClassOf)
if isinstance(p, URIRef)
parent
for parent in inferred.objects(subject, RDFS.subClassOf)
if isinstance(parent, URIRef)
)
if len(parents) > 1:
for parent in parents:
ancestors = set(
inferred.transitive_objects(parent, RDFS.subClassOf)
)
for p in parents:
if p != parent and p in ancestors:
t = s, RDFS.subClassOf, p
if t in inferred:
inferred.remove(t)
for entity in parents:
if entity != parent and entity in ancestors:
triple = subject, RDFS.subClassOf, entity
if triple in inferred:
inferred.remove(triple)
Loading

0 comments on commit af952a7

Please sign in to comment.