def instantiate_scene(scene: Scene, ontology: Ontology) -> Ontology: with ontology: def common_attributes(x: EntityInstance) -> Dict[str, Any]: result = { 'velocity': x.values.velocity, 'direction': ontology.Direction.from_string(x.values.orientation), 'length': x.values.length, 'width': x.values.width, 'height': x.values.height, 'lateral_distance': x.values.distance_lat, 'longitudinal_distance': x.values.distance_long, 'euclidean_distance': math.sqrt((x.values.distance_lat or 0) ** 2 + (x.values.distance_long or 0) ** 2) } return result entities: Dict[str, Tuple[EntityInstance, Thing]] = {} for car in [e for e in scene if e.kind == Kind.Vehicle]: car_onto = ontology.Car(car.name, **common_attributes(car)) entities[car.name] = (car, car_onto) for ped in [e for e in scene if e.kind == Kind.Pedestrian]: ped_onto = ontology.Pedestrian(ped.name, **common_attributes(ped)) entities[ped.name] = (ped, ped_onto) for ego in [e for e in scene if e.kind == Kind.Ego]: ego_onto = ontology.EgoCar(ego.name, **common_attributes(ego)) entities[ego.name] = (ego, ego_onto) return ontology
def get_ontology(base_iri='emmo-inferred.owl', verbose=False): """Returns a new Ontology from `base_iri`. If `verbose` is true, a lot of dianostics is written. """ if (not base_iri.endswith('/')) and (not base_iri.endswith('#')): base_iri = '%s#' % base_iri if base_iri in default_world.ontologies: onto = default_world.ontologies[base_iri] else: onto = Ontology(default_world, base_iri) onto._verbose = verbose return onto
def parse_ontology(ontology: Ontology, schema=OntologySchema) -> List[dict]: """ Parse an ontology from owlready2.Ontology to a list of dicts with the domain fields forOntologyTerm By default it uses the OBO Schema for the definition and synonyms annotations. :param ontology: owlready2.Ontology to parse :param schema: schema class extending OntologySchema :return ontology_terms: list of dicts containing ontology terms """ ontology_terms = [] for ontology_class in ontology.classes(): ontology_id = ontology.name ontology_term_id = ontology_class.name term_label = ontology_class.label term_definition = _collect_annotations( ontology_class, [schema.DEFINITION_ANNOTATION] ) synonyms = _collect_annotations(ontology_class, schema.SYNONYM_ANNOTATIONS) parents = [ str(parent.name) for parent in ontology_class.is_a if isinstance(parent, ThingClass) ] children = [ str(child.name) for child in ontology_class.subclasses() if isinstance(child, ThingClass) ] ontology_term = { "ontologyId": ontology_id, "ontologyTermId": ontology_term_id, "label": term_label, "description": term_definition, "synonyms": synonyms, "parents": parents, "children": children, } ontology_terms.append(ontology_term) return ontology_terms
def __build_concepts_mapping( onto: Ontology) -> Tuple[Dict, Concept, Concept]: """ Construct a mapping from full_iri to corresponding Concept objects. concept.namespace.base_iri + concept.name mappings from concepts uri to concept objects 1) full_iri:= owlready2.ThingClass.namespace.base_iri + owlready2.ThingClass.name 2) Concept: """ concepts = dict() individuals = set() T = Concept(owlready2.Thing, kwargs={'form': 'Class'}, world=onto.world) bottom = Concept(owlready2.Nothing, kwargs={'form': 'Class'}, world=onto.world) for i in onto.classes(): temp_concept = Concept(i, kwargs={'form': 'Class'}, world=onto.world) concepts[temp_concept.full_iri] = temp_concept individuals.update(temp_concept.instances) try: assert T.instances # if empty throw error. assert individuals.issubset(T.instances) except AssertionError: print('Sanity checking failed: owlready2. \ Thing does not contain any individual.\ To allivate this issue, we explicitly \ assign all individuals/instances to concept T.') T.instances = individuals concepts[T.full_iri] = T concepts[bottom.full_iri] = bottom return concepts, T, bottom
def __init__(self): name = None Ontology.__init__(self, default_world, onto.base_iri, name=name)
def __init__(self, default_world, base_iri, name=None): Ontology.__init__(self, default_world, base_iri, name=name)
def __build_hierarchy(self, onto: Ontology) -> None: """ Builds concept sub and super classes hierarchies. 1) self.top_down_concept_hierarchy is a mapping from Concept objects to a set of Concept objects that are direct subclasses of given Concept object. 2) self.down_top_concept_hierarchy is a mapping from Concept objects to set of Concept objects that are direct superclasses of given Concept object. """ # 1. (Mapping from string URI to Class Expressions, Thing Concept, Nothing Concept self.uri_to_concept, self.thing, self.nothing = parse_tbox_into_concepts( onto) assert len(self.uri_to_concept) > 2 assert self.thing.iri == 'http://www.w3.org/2002/07/owl#Thing' assert self.thing.name == '⊤' assert self.nothing.iri == 'http://www.w3.org/2002/07/owl#Nothing' assert self.nothing.name == '⊥' self.individuals = self.thing.instances self.down_top_concept_hierarchy[self.thing] = set() for IRI, concept_A in self.uri_to_concept.items( ): # second loop over concepts in the execution, assert IRI == concept_A.iri try: assert len(onto.search(iri=IRI)) == 1 except AssertionError: # Thing and Nothing is not added into hierarchy assert IRI in [ 'http://www.w3.org/2002/07/owl#Thing', 'http://www.w3.org/2002/07/owl#Nothing' ] assert concept_A.name in ['⊤', '⊥'] continue owlready_concept_A = onto.search(iri=concept_A.iri)[0] assert owlready_concept_A.iri == concept_A.iri self.__concept_hierarchy_fill(owlready_concept_A, concept_A) self.__direct_concept_hierarchy_fill(owlready_concept_A, concept_A, onto) # All concepts are subsumed by Thing. self.top_down_concept_hierarchy[self.thing].add(concept_A) self.down_top_concept_hierarchy[concept_A].add(self.thing) # All concepts subsume Nothing. self.top_down_concept_hierarchy[concept_A].add(self.nothing) self.down_top_concept_hierarchy[self.nothing].add(concept_A) self.top_down_concept_hierarchy[self.thing].add(self.nothing) self.down_top_concept_hierarchy[self.nothing].add(self.thing) ################################################################################################################ # Sanity checking # 1. Did we parse classes correctly ? owlready2_classes = {i.iri for i in onto.classes()} our_classes = {k for k, v in self.uri_to_concept.items()} try: assert our_classes.issuperset(owlready2_classes) and ( our_classes.difference(owlready2_classes) == { 'http://www.w3.org/2002/07/owl#Thing', 'http://www.w3.org/2002/07/owl#Nothing' }) except AssertionError: raise AssertionError('Assertion error => at superset checking.') try: # Thing subsumes all parsed concept except itself. assert len(self.top_down_concept_hierarchy[self.thing]) == ( len(our_classes) - 1) assert len(self.down_top_concept_hierarchy[self.nothing]) == ( len(our_classes) - 1) except AssertionError: raise AssertionError( 'Assertion error => at concept hierarchy checking.') # start from here try: assert len(self.down_top_concept_hierarchy[self.nothing]) == ( len(our_classes) - 1) assert len(self.top_down_direct_concept_hierarchy[self.thing]) >= 1 except AssertionError: raise AssertionError( 'Assertion error => total number of parsed concept checking') # 2. Did we create top down direct concept hierarchy correctly ? for concept, direct_sub_concepts in self.top_down_direct_concept_hierarchy.items( ): for dsc in direct_sub_concepts: assert concept.instances.issuperset(dsc.instances) # 3. Did we create top down concept hierarchy correctly ? for concept, direct_sub_concepts in self.top_down_concept_hierarchy.items( ): for dsc in direct_sub_concepts: assert concept.instances.issuperset(dsc.instances) # 3. Did we create down top direct concept hierarchy correctly ? for concept, direct_super_concepts in self.down_top_direct_concept_hierarchy.items( ): for dsc in direct_super_concepts: assert concept.instances.issubset(dsc.instances) # 4. Did we create down top concept hierarchy correctly ? for concept, direct_super_concepts in self.down_top_concept_hierarchy.items( ): for dsc in direct_super_concepts: try: assert concept.instances.issubset(dsc.instances) except AssertionError: raise AssertionError('Subset error')
def save_as_xml(file: str, ontology: Ontology): if not file.endswith(".rdf.xml"): file = file + ".rdf.xml" ontology.save(file)