001/*
002 * To change this license header, choose License Headers in Project Properties.
003 * To change this template file, choose Tools | Templates
004 * and open the template in the editor.
005 */
006package org.dllearner.utils.unife;
007
008import org.apache.log4j.Logger;
009import org.dllearner.algorithms.probabilistic.parameter.distributed.unife.edge.EDGEDistributedDynamic;
010import org.dllearner.core.ComponentInitException;
011import org.dllearner.core.KnowledgeSource;
012import org.dllearner.kb.OWLOntologyKnowledgeSource;
013import org.semanticweb.owlapi.apibinding.OWLManager;
014import org.semanticweb.owlapi.formats.FunctionalSyntaxDocumentFormat;
015import org.semanticweb.owlapi.formats.OWLXMLDocumentFormat;
016import org.semanticweb.owlapi.model.*;
017
018import java.io.File;
019import java.util.*;
020
021/**
022 *
023 * @author Giuseppe Cota <giuseppe.cota@unife.it>, Riccardo Zese
024 * <riccardo.zese@unife.it>
025 */
026public class OWLUtils {
027
028    private static Logger logger = Logger.getLogger(EDGEDistributedDynamic.class);
029
030    /**
031     * prefix used for the dummy class.
032     */
033    //protected static final String PREFIX = "https://sites.google.com/a/unife.it/ml/leap";
034    /**
035     * This method merges all the input knowledge sources and returns the
036     * filename of the new ontology.
037     *
038     * @param sources set of knowledge bases
039     * @return the ontology obtained from the merging of {@code sources}
040     * @throws org.dllearner.core.ComponentInitException
041     */
042    public static OWLOntology mergeOntologies(Set<KnowledgeSource> sources) throws ComponentInitException {
043        logger.info("Number of sources: " + sources.size());
044        logger.info("creating ontology through merging of the sources");
045        // list of source ontologies
046        List<OWLOntology> owlAPIOntologies = new LinkedList<>();
047
048        Set<OWLImportsDeclaration> directImports = new HashSet<>();
049        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
050
051        for (KnowledgeSource source : sources) {
052            OWLOntology ontology;
053            if (source instanceof OWLOntologyKnowledgeSource) {
054                ontology = ((OWLOntologyKnowledgeSource) source).createOWLOntology(manager);
055                owlAPIOntologies.add(ontology);
056            } else {
057                //This parameter learner requires an ontology to process
058                String message = "EDGE Parameter Learner Requires an OWLKnowledgeSource.  Received a KS of type: " + source.getClass().getName();
059                logger.error(message);
060                throw new ComponentInitException(message);
061            }
062
063            directImports.addAll(ontology.getImportsDeclarations());
064        }
065
066        //Now merge all of the knowledge sources into one ontology instance.
067        try {
068            logger.info("Merging the ontologies...");
069            //The following line illustrates a problem with using different OWLOntologyManagers.  This can manifest itself if we have multiple sources who were created with different manager instances.
070            //ontology = OWLManager.createOWLOntologyManager().createOntology(IRI.create("http://dl-learner/all"), new HashSet<OWLOntology>(owlAPIOntologies));
071//            OWLOntology allOntology = manager.createOntology(IRI.create("http://dl-learner/all"), new HashSet<OWLOntology>(owlAPIOntologies));
072            OWLOntology allOntology = manager.createOntology(IRI.generateDocumentIRI(), new HashSet<OWLOntology>(owlAPIOntologies));
073            //we have to add all import declarations manually here, because this are no axioms
074            List<OWLOntologyChange> addImports = new ArrayList<>();
075            for (OWLImportsDeclaration i : directImports) {
076                addImports.add(new AddImport(allOntology, i));
077            }
078            manager.applyChanges(addImports);
079            logger.info("Ontologies merged. Complete ontology created");
080            return allOntology;
081        } catch (OWLOntologyCreationException e1) {
082            String message = "OWLOntologyCreationException complete ontology NOT created. ";
083            logger.error(message + e1.getMessage());
084            throw new ComponentInitException(message);
085        }
086
087    }
088
089    public static OWLClass createDummyClass(IRI dummyClassIRI) {
090        // create dummy class
091//            if (classToDescribe != null) {
092//                logger.debug("Creating dummy class for " + ((OWLClass) classToDescribe).toStringID());
093//            } else {
094        logger.debug("Creating dummy class");
095
096//            }
097        // It must be very rare that a class in an ontology has the IRI defined by PREFIX#learnedClass
098        // but let's make it sure
099        int i = 0;
100        //String dummyClassStringIRI = PREFIX + "#dummyClass";
101//            String num = "";
102//            while (ontologyOWL.containsClassInSignature(IRI.create(dummyClassStringIRI + num))) {
103//                num = "" + i;
104//                i++;
105//            }
106//            dummyClass = manager.getOWLDataFactory().getOWLClass(IRI.create(dummyClassStringIRI + num));
107        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
108//            OWLClass dummyClass = manager.getOWLDataFactory().getOWLClass(IRI.create(dummyClassStringIRI));
109        OWLClass dummyClass = manager.getOWLDataFactory().getOWLClass(dummyClassIRI);
110        logger.debug("Dummy class created");
111        return dummyClass;
112    }
113
114    public static void saveOntology(OWLOntology resultOntology, String outputFile, String outFormat)
115            throws OWLOntologyStorageException {
116        OWLDocumentFormat formatter;
117        switch (outFormat) {
118            case "OWLXML":
119                formatter = new OWLXMLDocumentFormat();
120                break;
121            case "OWLFUNCTIONAL":
122                formatter = new FunctionalSyntaxDocumentFormat();
123                break;
124            default:
125                formatter = new OWLXMLDocumentFormat();
126                break;
127        }
128        resultOntology.getOWLOntologyManager().saveOntology(resultOntology, formatter, IRI.create(new File(outputFile)));
129    }
130
131    public static void saveAxioms(Set<OWLAxiom> axioms, String outputFile, String outFormat)
132            throws OWLOntologyStorageException, OWLOntologyCreationException {
133        OWLOntologyManager man = OWLManager.createOWLOntologyManager();
134        OWLOntology resultOntology = man.createOntology();
135        man.addAxioms(resultOntology, axioms);
136        OWLDocumentFormat formatter;
137        switch (outFormat) {
138            case "OWLXML":
139                formatter = new OWLXMLDocumentFormat();
140                break;
141            case "OWLFUNCTIONAL":
142                formatter = new FunctionalSyntaxDocumentFormat();
143                break;
144            default:
145                formatter = new OWLXMLDocumentFormat();
146                break;
147        }
148        resultOntology.getOWLOntologyManager().saveOntology(resultOntology, formatter, IRI.create(new File(outputFile)));
149    }
150
151    public static Set<OWLAxiom> convertIndividualsToAssertionalAxioms(
152            Set<OWLIndividual> individuals, OWLClassExpression ce) {
153        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
154        OWLDataFactory owlFactory = manager.getOWLDataFactory();
155        Set<OWLAxiom> assertionalAxioms = new HashSet<>();
156        for (OWLIndividual ind : individuals) {
157            OWLAxiom axiom = owlFactory.getOWLClassAssertionAxiom(ce, ind);
158            assertionalAxioms.add(axiom);
159        }
160        return assertionalAxioms;
161    }
162
163    public static OWLEquivalentClassesAxiom convertSubClassOfIntoEquivalentClassesAxiom(OWLSubClassOfAxiom axiom) {
164        OWLDataFactory df = OWLManager.getOWLDataFactory();
165        OWLClassExpression class1 = axiom.getSubClass();
166        OWLClassExpression class2 = axiom.getSuperClass();
167        Set<OWLAnnotation> annotations = axiom.getAnnotations();
168        OWLEquivalentClassesAxiom equivAxiom = df.getOWLEquivalentClassesAxiom(
169                class2, class2, annotations);
170        return equivAxiom;
171    }
172}