org.semanticweb.owlapi.model.parameters.OntologyCopy Java Examples

The following examples show how to use org.semanticweb.owlapi.model.parameters.OntologyCopy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleOntology.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new SimpleOntology object using the provided OWLOntology and OWLOntologyManager. If the provided
 * OWLOntologyManager does not contain the provided OWLOntology, the provided OWLOntology is copied into the
 * OWLOntologyManager. Otherwise, the provided OWLOntology is used.
 */
protected SimpleOntology(OWLOntology ontology, OWLOntologyManager owlManager, Resource resource,
                         OntologyManager ontologyManager, SesameTransformer transformer,
                         BNodeService bNodeService, RepositoryManager repoManager, ForkJoinPool threadPool) {
    this.ontologyManager = ontologyManager;
    this.transformer = transformer;
    this.bNodeService = bNodeService;
    this.owlManager = owlManager;
    this.repoManager = repoManager;

    try {
        if (!owlManager.contains(ontology)) {
            owlOntology = owlManager.copyOntology(ontology, OntologyCopy.DEEP);
        } else {
            owlOntology = ontology;
        }
    } catch (OWLOntologyCreationException e) {
        throw new MobiOntologyException("Error in ontology creation", e);
    }

    createOntologyId(resource);
    owlReasoner = owlReasonerFactory.createReasoner(owlOntology);
}
 
Example #2
Source File: OntologyHelper.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given an ontology, a threshold, and a set of precious IRIs (or empty set), minimize the input
 * ontology's class hierarchy based on the threshold. The threshold is the minimum number of child
 * classes that an intermediate class should have. Any intermediate class that has less than the
 * threshold number of children will be removed and its children will become children of the next
 * level up. Bottom-level and top-level classes are not removed. Any class with an IRI in the
 * precious set is not removed. If not repeat, collapse will only be performed once, meaning that
 * some intermediate classes may remain.
 *
 * @param ontology OWLOntology to minimize
 * @param threshold minimum number of child classes
 * @param precious set of IRIs to keep
 * @param repeat if true, repeat collapsing until no intermediate classes remain
 */
public static void collapseOntology(
    OWLOntology ontology, int threshold, Set<IRI> precious, boolean repeat)
    throws OWLOntologyCreationException {
  OWLOntology copy =
      OWLManager.createOWLOntologyManager().copyOntology(ontology, OntologyCopy.DEEP);
  logger.debug("Classes before collapsing: " + ontology.getClassesInSignature().size());

  Set<OWLObject> removeClasses = getClassesToRemove(ontology, threshold, precious);

  boolean collapsedOnce = false;

  // Remove axioms based on classes
  // Get all axioms that involve these classes
  // Continue to get remove classes until there's no more to remove
  while (!removeClasses.isEmpty()) {
    if (collapsedOnce && !repeat) {
      break;
    }
    Set<OWLAxiom> axiomsToRemove =
        RelatedObjectsHelper.getPartialAxioms(ontology, removeClasses, null);
    OWLOntologyManager manager = ontology.getOWLOntologyManager();
    manager.removeAxioms(ontology, axiomsToRemove);
    // Span gaps to maintain hierarchy
    manager.addAxioms(
        ontology, RelatedObjectsHelper.spanGaps(copy, OntologyHelper.getObjects(ontology)));
    // Repeat until there's no more to remove
    removeClasses = getClassesToRemove(ontology, threshold, precious);
    collapsedOnce = true;
  }
  logger.debug("Classes after collapsing: " + ontology.getClassesInSignature().size());
}
 
Example #3
Source File: RemoveCommand.java    From robot with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Given an input state and command line arguments, create a new ontology with removed axioms and
 * return a new state. The input ontology is not changed.
 *
 * @param state the state from the previous command, or null
 * @param args the command-line arguments
 * @return a new state with the new ontology
 * @throws Exception on any problem
 */
public CommandState execute(CommandState state, String[] args) throws Exception {
  CommandLine line = CommandLineHelper.getCommandLine(getUsage(), getOptions(), args);
  if (line == null) {
    return null;
  }

  IOHelper ioHelper = CommandLineHelper.getIOHelper(line);
  state = CommandLineHelper.updateInputOntology(ioHelper, state, line);
  OWLOntology ontology = state.getOntology();
  OWLOntologyManager manager = ontology.getOWLOntologyManager();

  // Get a set of relation types, or annotations to select
  List<String> selects = CommandLineHelper.getOptionalValues(line, "select");

  // If the select option wasn't provided, default to self
  if (selects.isEmpty()) {
    selects.add("self");
  }

  // Selects should be processed in order, allowing unions in one --select
  List<List<String>> selectGroups = new ArrayList<>();
  boolean anonymous = false;
  for (String select : selects) {
    // The single group is a split of the one --select
    List<String> selectGroup = CommandLineHelper.splitSelects(select);
    // Imports should be handled separately
    if (selectGroup.contains("imports")) {
      OntologyHelper.removeImports(ontology);
      selectGroup.remove("imports");
    }
    if (selectGroup.contains("ontology")) {
      OntologyHelper.removeOntologyAnnotations(ontology);
      selectGroup.remove("ontology");
    }
    if (selectGroup.contains("anonymous")) {
      anonymous = true;
    }
    if (!selectGroup.isEmpty()) {
      selectGroups.add(selectGroup);
    }
  }

  // Get the objects to remove
  Set<OWLObject> relatedObjects = getObjects(line, ioHelper, ontology, selectGroups);
  if (relatedObjects.isEmpty()) {
    // nothing to remove - save and exit
    CommandLineHelper.maybeSaveOutput(line, ontology);
    state.setOntology(ontology);
    return state;
  }

  // Copy the unchanged ontology to reserve for filling gaps later
  OWLOntology copy =
      OWLManager.createOWLOntologyManager().copyOntology(ontology, OntologyCopy.DEEP);

  // Remove specific axioms
  List<String> axiomSelectors = CommandLineHelper.cleanAxiomStrings(line);
  List<String> baseNamespaces = CommandLineHelper.getBaseNamespaces(line, ioHelper);
  boolean trim = CommandLineHelper.getBooleanValue(line, "trim", true);
  boolean signature = CommandLineHelper.getBooleanValue(line, "signature", false);
  manager.removeAxioms(
      ontology,
      RelatedObjectsHelper.filterAxioms(
          ontology.getAxioms(), relatedObjects, axiomSelectors, baseNamespaces, trim, signature));

  // Handle gaps
  boolean preserveStructure = CommandLineHelper.getBooleanValue(line, "preserve-structure", true);
  if (preserveStructure) {
    // Since we are preserving the structure between the objects that were NOT removed, we need to
    // get the complement of the removed object set and build relationships between those objects.
    Set<OWLObject> complementObjects =
        RelatedObjectsHelper.select(ontology, ioHelper, relatedObjects, "complement");
    manager.addAxioms(
        ontology, RelatedObjectsHelper.spanGaps(copy, complementObjects, anonymous));
  }

  // Save the changed ontology and return the state
  CommandLineHelper.maybeSaveOutput(line, ontology);
  state.setOntology(ontology);
  return state;
}
 
Example #4
Source File: SolrCommandRunner.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void loadEachModelAnnotation(ParserWrapper pwr, File legoFile, String url, Set<String> modelStateFilter,
		boolean removeDeprecatedModels, boolean removeTemplateModels, boolean removeUnsatisfiableModels,
		boolean exitIfUnsatisfiable, boolean exitIfLoadFails) throws IOException {
	String fname = legoFile.getName();
	OWLReasoner currentReasoner = null;
	OWLOntologyManager manager = pwr.getManager();

	OWLOntology model = null;
	ModelAnnotationSolrDocumentLoader loader = null;

	try {
		model = pwr.parseOWL(IRI.create(legoFile));

		// Skip deprecated models
		boolean isDeprecated = isDeprecated(model);
		if (isDeprecated) {
			LOG.warn("Skipping deprecated model: " + fname);
			return;
		}

		/**
		 * DEEP-COPIES OWLOntology instance.
		 * Note that most serialization libraries such as Kryo or Cloner DO NOT work for
		 * copying OWLOntology or reasoner instance. In other words, deep-copying ontology 
		 * should be done via "copyOntology" method. This allows preventing memory leaks, i.e., 
		 * running reasoners affects the model (OWLOntology instance) but the changes only happen 
		 * over copied instance, which can be safely disposed without blowing out of memory.
		 */
		OWLOntologyManager tempOWLManager = OWLManager.createOWLOntologyManager();
		OWLOntology tModel = tempOWLManager.copyOntology(model, OntologyCopy.DEEP);

		// Some sanity checks--some of the generated ones are problematic.
		// We need a consistent ontology for the closure calculations!
		OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();
		currentReasoner = reasonerFactory.createReasoner(tModel);
		boolean consistent = currentReasoner.isConsistent();
		if(consistent == false){
			LOG.warn("Skip since inconsistent: " + fname);
			return;
		}

		LOG.info("Trying complex annotation load of: " + fname);
		boolean isMock = false;
		String modelUrl = legoModelPrefix + fname;

		if (url.equals("mock")) {
			loader = new MockModelAnnotationSolrDocumentLoader(url, tModel, currentReasoner, modelUrl, 
					modelStateFilter, removeDeprecatedModels, removeTemplateModels);
			isMock = true;
		}
		else {
			loader = new ModelAnnotationSolrDocumentLoader(url, tModel, currentReasoner, modelUrl, 
					modelStateFilter, removeDeprecatedModels, removeTemplateModels);
		}

		loader.load();

		if (isMock) {
			showMockDocs((MockModelAnnotationSolrDocumentLoader) loader);
		}

		currentReasoner.dispose();
		tempOWLManager.removeOntology(tModel);
	} catch (Exception e) {
		LOG.info("Complex annotation load of " + fname + " at " + url + " failed!");
		e.printStackTrace();

		if (exitIfLoadFails)
			System.exit(1);
	} finally {
		manager.removeOntology(model);
		if (loader != null) {
			loader.close();
			loader = null;
			LOG.info("Closing the current loader...");
		}
	}
}