aboutsummaryrefslogtreecommitdiff
path: root/src/uk/ac/ox/cs/pagoda/rules/Program.java
blob: a0edf854ed2d89be77941b906711e25407365392 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package uk.ac.ox.cs.pagoda.rules;

import org.apache.commons.io.FilenameUtils;
import org.semanticweb.HermiT.Configuration;
import org.semanticweb.HermiT.model.*;
import org.semanticweb.HermiT.structural.OWLClausification;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.simpleETL.SimpleETL;
import uk.ac.ox.cs.pagoda.MyPrefixes;
import uk.ac.ox.cs.pagoda.approx.KnowledgeBase;
import uk.ac.ox.cs.pagoda.approx.RLPlusOntology;
import uk.ac.ox.cs.pagoda.constraints.BottomStrategy;
import uk.ac.ox.cs.pagoda.constraints.NullaryBottom;
import uk.ac.ox.cs.pagoda.constraints.PredicateDependency;
import uk.ac.ox.cs.pagoda.hermit.DLClauseHelper;
import uk.ac.ox.cs.pagoda.owl.OWLHelper;
import uk.ac.ox.cs.pagoda.util.Utility;

import java.io.*;
import java.util.*;

public abstract class Program implements KnowledgeBase {
	
	protected String ontologyDirectory = null;
	protected OWLOntology ontology; 
	protected DLOntology dlOntology;
	protected BottomStrategy botStrategy; 
	protected Collection<DLClause> clauses = new HashSet<DLClause>();
//	protected Set<DLClause> used = new HashSet<DLClause>();
protected PredicateDependency dependencyGraph;
	protected LinkedList<OWLTransitiveObjectPropertyAxiom> transitiveAxioms;
	protected LinkedList<DLClause> transitiveClauses;
	protected LinkedList<OWLSubPropertyChainOfAxiom> subPropChainAxioms;
	protected LinkedList<DLClause> subPropChainClauses;
	private String additionalDataFile = null;

	public static String toString(Collection<DLClause> clauses) {
		StringBuilder sb = new StringBuilder(DLClauseHelper.toString(clauses));
		sb.insert(0, MyPrefixes.PAGOdAPrefixes.prefixesText());
		return sb.toString();
	}

	public void load(OWLOntology o, BottomStrategy botStrategy) {
		this.botStrategy = botStrategy;
		RLPlusOntology owlOntology = new RLPlusOntology();
		owlOntology.load(o, new NullaryBottom());
		owlOntology.simplify();

		ontology = owlOntology.getTBox();
//		String ontologyPath = OWLHelper.getOntologyPath(ontology);
//		ontologyDirectory = ontologyPath.substring(0, ontologyPath.lastIndexOf(Utility.JAVA_FILE_SEPARATOR));
		String ontologyPath = ontology.getOWLOntologyManager().getOntologyDocumentIRI(ontology).toURI().getPath();
		ontologyDirectory = FilenameUtils.getFullPath(ontologyPath);
		clausify();

		String aboxOWLFile = owlOntology.getABoxPath();
		OWLOntology abox = OWLHelper.loadOntology(aboxOWLFile);
		OWLOntologyManager manager = abox.getOWLOntologyManager();
		OWLAxiom axiom;
		for (Atom atom: dlOntology.getPositiveFacts()) {
			if ((axiom = OWLHelper.getABoxAssertion(manager.getOWLDataFactory(), atom)) != null)
				manager.addAxiom(abox, axiom);
		}

		try {
			FileOutputStream out = new FileOutputStream(aboxOWLFile);
			manager.saveOntology(abox, out);
			out.close();
		} catch(IOException | OWLOntologyStorageException e) {
			e.printStackTrace();
			System.exit(1);
		}

		if (!abox.isEmpty()) {
			SimpleETL rewriter = new SimpleETL(owlOntology.getOntologyIRI(), aboxOWLFile);
			try {
				rewriter.rewrite();
			} catch (Exception e) {
				e.printStackTrace();
			}
			additionalDataFile = rewriter.getExportedFile();
			new File(aboxOWLFile).delete();
		}

	}
	
	public String getAdditionalDataFile() {
		return additionalDataFile;
	}

	@Override
	public void transform() {
		for(DLClause dlClause : dlOntology.getDLClauses()) {
			DLClause simplifiedDLClause = DLClauseHelper.removeNominalConcept(dlClause);
			simplifiedDLClause = removeAuxiliaryBodyAtoms(simplifiedDLClause);
			simplifiedDLClause = DLClauseHelper.replaceWithDataValue(simplifiedDLClause);
			convert(simplifiedDLClause);
		}

		addingTransitiveAxioms();
		addingSubPropertyChainAxioms();

		Collection<DLClause> botRelated = new LinkedList<DLClause>();
		Variable X = Variable.create("X");
		botRelated.add(DLClause.create(new Atom[0], new Atom[]{Atom.create(Inequality.INSTANCE, X, X)}));
		clauses.addAll(botStrategy.process(botRelated));

		if(this instanceof GeneralProgram)
			Utility.logDebug("The number of rules: " + (clauses.size() - 1));
	}
	
	@Override
	public void save() {
		try {
			BufferedWriter ruleWriter = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(getOutputPath())));
			ruleWriter.write(toString());
			ruleWriter.close();
		} catch(IOException e) {
			e.printStackTrace();
		}
		Utility.logInfo("The rules are saved in " + getOutputPath() + ".");
	}

	@Override
	public String toString() {
		return toString(clauses);
	}

	public final void convert(DLClause clause) {
		Collection<DLClause> tempClauses = convert2Clauses(clause);
		clauses.addAll(tempClauses);
	}

	public abstract Collection<DLClause> convert2Clauses(DLClause clause);

	public abstract String getOutputPath();

	public OWLOntology getOntology() {
		return ontology;
	}

	public Collection<DLClause> getClauses() {
		return clauses;
	}

	public Collection<DLClause> getClauses(DLClause queryClause) {
//		if (true) return new HashSet<DLClause>(clauses);
		Set<DLPredicate> predicates = new HashSet<DLPredicate>();
		predicates.addAll(dependencyGraph.collectPredicate(queryClause.getBodyAtoms()));

		Set<DLPredicate> dependence = new HashSet<DLPredicate>();
		for(DLPredicate predicate : predicates)
			dependence.addAll(dependencyGraph.getAncesters(predicate));

		Collection<DLClause> relevantClauses = new LinkedList<DLClause>();
		for(DLClause clause : clauses) {
			if(relevant(clause, dependence))
				relevantClauses.add(clause);

		}
		return relevantClauses;
	}

	public PredicateDependency buildDependencyGraph() {
		if(dependencyGraph == null)
			return dependencyGraph = new PredicateDependency(clauses);
		else
			return dependencyGraph;
	}

	public void getDependencyGraph(PredicateDependency g) {
		dependencyGraph = g;
	}

	public final String getDirectory() {
		return Utility.getGlobalTempDirAbsolutePath();
	}

	public void deleteABoxTurtleFile() {
		if(additionalDataFile != null)
			new File(additionalDataFile).delete();
	}

	/**
	 * clone all information of another program after load()
	 *
	 * @param program
	 */
	void clone(Program program) {
		this.ontologyDirectory = program.ontologyDirectory;
		this.ontology = program.ontology;
		this.dlOntology = program.dlOntology;
		this.botStrategy = program.botStrategy;
		this.additionalDataFile = program.additionalDataFile;
		this.transitiveAxioms = program.transitiveAxioms;
		this.transitiveClauses = program.transitiveClauses;
		this.subPropChainAxioms = program.subPropChainAxioms;
		this.subPropChainClauses = program.subPropChainClauses;
	}

	private void clausify() {
		Configuration conf = new Configuration();
		OWLClausification clausifier = new OWLClausification(conf);
		OWLOntology filteredOntology = null;
		OWLOntologyManager manager = ontology.getOWLOntologyManager();
		try {
			filteredOntology = manager.createOntology();
		} catch(OWLOntologyCreationException e) {
			e.printStackTrace();
		}

		transitiveAxioms = new LinkedList<OWLTransitiveObjectPropertyAxiom>();
		subPropChainAxioms = new LinkedList<OWLSubPropertyChainOfAxiom>();

		OWLDatatype date = ontology.getOWLOntologyManager()
								   .getOWLDataFactory()
								   .getOWLDatatype(IRI.create("http://www.w3.org/2001/XMLSchema#date"));
		int noOfDataPropertyRangeAxioms = 0, noOfAxioms = 0;
		for(OWLOntology onto : ontology.getImportsClosure())
			for(OWLAxiom axiom : onto.getAxioms()) {
				if(axiom instanceof OWLTransitiveObjectPropertyAxiom)
					transitiveAxioms.add((OWLTransitiveObjectPropertyAxiom) axiom);
				else if(axiom instanceof OWLSubPropertyChainOfAxiom)
					subPropChainAxioms.add((OWLSubPropertyChainOfAxiom) axiom);
					// TODO to filter out datatype axioms
				else if(axiom instanceof OWLDataPropertyRangeAxiom) {
					++noOfDataPropertyRangeAxioms;
					Utility.logInfo("The axiom: " + axiom + " is being ignored.");
				}
				else {
					if(axiom.getDatatypesInSignature().contains(date)) {
						Utility.logInfo("The axiom: " + axiom + " is being ignored.");
					}
					else manager.addAxiom(filteredOntology, axiom);
				}

				if(axiom instanceof OWLAnnotationAssertionAxiom ||
						axiom instanceof OWLSubAnnotationPropertyOfAxiom ||
						axiom instanceof OWLDeclarationAxiom ||
						axiom instanceof OWLDataPropertyRangeAxiom) {
				}
				else {
//					System.out.println(axiom);
					++noOfAxioms;
				}

			}
		Utility.logInfo("The number of data property range axioms that are ignored: " + noOfDataPropertyRangeAxioms + "(" + noOfAxioms + ")");

		dlOntology = (DLOntology) clausifier.preprocessAndClausify(filteredOntology, null)[1];
		clausifier = null;
	}

	private DLClause removeAuxiliaryBodyAtoms(DLClause dlClause) {
		Collection<Atom> newBodyAtoms = new LinkedList<Atom>();
		DLPredicate p;
		for(Atom bodyAtom : dlClause.getBodyAtoms()) {
			p = bodyAtom.getDLPredicate();
			if(p instanceof AtomicConcept ||
					p instanceof AtomicRole || p instanceof InverseRole ||
					p instanceof Equality || p instanceof AnnotatedEquality || p instanceof Inequality)
				newBodyAtoms.add(bodyAtom);
		}
		LinkedList<Atom> newHeadAtoms = new LinkedList<Atom>();
		Map<Variable, Term> assign = new HashMap<Variable, Term>();
		for(Atom headAtom : dlClause.getHeadAtoms()) {
			p = headAtom.getDLPredicate();
			if(p instanceof AtomicNegationDataRange) {
				AtomicDataRange positive = ((AtomicNegationDataRange) p).getNegatedDataRange();
				if(!(positive instanceof ConstantEnumeration))
					newBodyAtoms.add(Atom.create(positive, headAtom.getArgument(0)));
				else if(((ConstantEnumeration) positive).getNumberOfConstants() == 1) {
					assign.put((Variable) headAtom.getArgument(0), ((ConstantEnumeration) positive).getConstant(0));
//					newBodyAtoms.add(Atom.create(Equality.INSTANCE, headAtom.getArgument(0), ((ConstantEnumeration) positive).getConstant(0)));
				}
				else newHeadAtoms.add(headAtom);
			}
			else
				newHeadAtoms.add(headAtom);
		}

		if(assign.isEmpty() && newHeadAtoms.isEmpty() && newBodyAtoms.size() == dlClause.getBodyLength())
			return dlClause;

		Atom[] headArray =
				newHeadAtoms.size() == dlClause.getHeadLength() ? dlClause.getHeadAtoms() : newHeadAtoms.toArray(new Atom[0]);
		Atom[] bodyArray =
				newBodyAtoms.size() == dlClause.getBodyLength() ? dlClause.getBodyAtoms() : newBodyAtoms.toArray(new Atom[0]);
		if(!assign.isEmpty()) {
			for(int i = 0; i < headArray.length; ++i)
				headArray[i] = DLClauseHelper.getInstance(headArray[i], assign);
			for(int i = 0; i < bodyArray.length; ++i)
				bodyArray[i] = DLClauseHelper.getInstance(bodyArray[i], assign);
		}
		return DLClause.create(headArray, bodyArray);
	}

	private void addingTransitiveAxioms() {
		DLClause transitiveClause;
		Atom headAtom;
		Variable X = Variable.create("X"), Y = Variable.create("Y"), Z = Variable.create("Z");
		transitiveClauses = new LinkedList<DLClause>();
		for(OWLTransitiveObjectPropertyAxiom axiom : transitiveAxioms) {
			OWLObjectPropertyExpression objExp = axiom.getProperty();
			headAtom = getAtom(objExp, X, Z);
			Atom[] bodyAtoms = new Atom[2];
			bodyAtoms[0] = getAtom(objExp, X, Y);
			bodyAtoms[1] = getAtom(objExp, Y, Z);
			transitiveClause = DLClause.create(new Atom[]{headAtom}, bodyAtoms);
			clauses.add(transitiveClause);
			transitiveClauses.add(transitiveClause);
		}
	}

	private Atom getAtom(OWLObjectPropertyExpression exp, Variable x, Variable y) {
		if(exp instanceof OWLObjectProperty)
			return Atom.create(AtomicRole.create(((OWLObjectProperty) exp).toStringID()), x, y);
		// TODO fixed, test it
		OWLObjectPropertyExpression inverseOf;
		if(exp instanceof OWLObjectInverseOf && (inverseOf = (
				(OWLObjectInverseOf) exp).getInverse()) instanceof OWLObjectProperty)
			return Atom.create(AtomicRole.create(((OWLObjectProperty) inverseOf).toStringID()), x, y);
		return null;
	}

	private void addingSubPropertyChainAxioms() {
		DLClause dlClause;
		subPropChainClauses = new LinkedList<DLClause>();
		Atom headAtom;
		Iterator<OWLObjectPropertyExpression> iterExp;
		OWLObjectPropertyExpression objExp;
		for(OWLSubPropertyChainOfAxiom axiom : subPropChainAxioms) {
			objExp = axiom.getSuperProperty();
			List<OWLObjectPropertyExpression> objs = axiom.getPropertyChain();
			headAtom = getAtom(objExp, Variable.create("X"), Variable.create("X" + objs.size()));
			iterExp = objs.iterator();
			int index = 1;
			Atom[] bodyAtoms = new Atom[objs.size()];
			bodyAtoms[0] = getAtom(iterExp.next(), Variable.create("X"), Variable.create("X1"));
			while(index < objs.size()) {
				bodyAtoms[index] =
						getAtom(iterExp.next(), Variable.create("X" + index), Variable.create("X" + (index + 1)));
				++index;
			}
			dlClause = DLClause.create(new Atom[]{headAtom}, bodyAtoms);
			clauses.add(dlClause);
			subPropChainClauses.add(dlClause);
		}
	}

	private boolean relevant(DLClause clause, Set<DLPredicate> set) {
		for(DLPredicate p : dependencyGraph.collectPredicate(clause.getHeadAtoms()))
			if(set.contains(p))
				return true;
		return false;
	}

}