001 package org.dllearner.examples;
002
003 import java.io.BufferedReader;
004 import java.io.File;
005 import java.io.FileNotFoundException;
006 import java.io.FileOutputStream;
007 import java.io.FileReader;
008 import java.io.IOException;
009 import java.net.URI;
010 import java.util.HashMap;
011 import java.util.HashSet;
012 import java.util.LinkedList;
013 import java.util.Random;
014 import java.util.Set;
015 import java.util.SortedSet;
016 import java.util.StringTokenizer;
017 import java.util.TreeSet;
018
019 import org.dllearner.algorithms.refinement2.ROLComponent2;
020 import org.dllearner.core.ComponentManager;
021 import org.dllearner.core.KnowledgeSource;
022 import org.dllearner.core.LearningAlgorithm;
023 import org.dllearner.core.LearningProblem;
024 import org.dllearner.core.ReasonerComponent;
025 import org.dllearner.core.configurators.ComponentFactory;
026 import org.dllearner.core.owl.ClassAssertionAxiom;
027 import org.dllearner.core.owl.Description;
028 import org.dllearner.core.owl.Individual;
029 import org.dllearner.core.owl.KB;
030 import org.dllearner.core.owl.NamedClass;
031 import org.dllearner.core.owl.ObjectProperty;
032 import org.dllearner.core.owl.ObjectPropertyAssertion;
033 import org.dllearner.kb.KBFile;
034 import org.dllearner.learningproblems.PosNegLPStandard;
035 import org.dllearner.parser.KBParser;
036 import org.dllearner.reasoning.FastInstanceChecker;
037 import org.dllearner.reasoning.OWLAPIReasoner;
038 import org.dllearner.utilities.statistics.SimpleClock;
039
040 /*
041 * Structure
042 *
043 *
044 *
045 *
046 * */
047
048 public class KRKModular {
049
050 // REMEMBER
051 // FILES are letters
052 // RANKS are numbers
053
054 // FLAGS
055 //
056 // turn off to not write the owl, needs about 30 seconds or more
057 /*static boolean writeOWL = true;
058 static boolean writeKB = false;
059 static boolean useTransitivity = false;
060
061 static boolean writeExampleSets = true;
062 static boolean writeConciseOWLAllDifferent = false;
063 */
064 boolean useHigherThan = KRKOntologyTBox.useHigherThan;
065
066
067
068 //static boolean useInverse = false;
069 // dependent, love and marriage, horse and carriage
070 //static boolean useTripleSubProps = useInverse && false;
071
072
073 static String workingDir = "examples/krkrecognizer/";
074 static String allData = workingDir+"krkopt_no_draw.data";
075 //static String allData = workingDir+"krkopt_original_dataset.data";
076
077 static URI ontologyURI = KRKOntologyTBox.ontologyURI;
078
079 // static SortedSet<String> fileSet = new TreeSet<String>();
080 //static SortedSet<String> allInstances = new TreeSet<String>();
081 //static SortedSet<String> classSet = new TreeSet<String>();
082 //static SortedSet<String> symmetricRoleSet = new TreeSet<String>();
083
084 static HashMap<String, SortedSet<Individual>> classToInd = new HashMap<String, SortedSet<Individual>>();
085 static HashMap<Individual, String> indToClass = new HashMap<Individual, String>();
086
087 static Set<ReasonerComponent> allReasoners = new HashSet<ReasonerComponent>();
088 static int negativeExamplesAdded = 200;
089
090 // static LinkedList<String> words;
091 public KB kb;
092 public ReasonerComponent reasoner;
093
094
095 //public FastInstanceChecker fic;
096 // static HashMap<String,SortedSet<String>> classToInd;
097
098
099 public static void init(){
100 if (!new File(workingDir).exists()) {
101 System.out.println("Created directory: " + workingDir +
102 " : " + new File(workingDir).mkdir()+ ".");
103 }
104 }
105
106 public static void main(String[] args) {
107 main1(args);
108 //main2(args);
109
110 }
111
112
113 public static void main1(String[] args) {
114 init();
115 initAllInstancesWithoutReasoners();
116 System.out.println("initializing finished");
117 //String currentClass = "ZERO";
118 LinkedList<String> ll=new LinkedList<String>();
119
120 ll.add("DRAW");
121 ll.add("ZERO");
122 ll.add("ONE");
123 ll.add("TWO");
124 ll.add("THREE");
125 ll.add("FOUR");
126 ll.add("FIVE");
127 ll.add("SIX");
128 ll.add("SEVEN");
129 ll.add("EIGHT");
130 ll.add("NINE");
131 ll.add("TEN");
132 ll.add("ELEVEN");
133 ll.add("TWELVE");
134 ll.add("THIRTEEN");
135 ll.add("FOURTEEN");
136 ll.add("FIFTEEN");
137 ll.add("SIXTEEN");
138
139 String skript="";
140
141 for (int i = 0; i < ll.size(); i++) {
142 System.out.println("progress "+i+" of "+ll.size());
143 String currentClass=ll.get(i);
144 SortedSet<Individual> allPos = classToInd.get(currentClass);
145 if(classToInd.get(currentClass)==null)continue;
146 if(currentClass.equals("SIXTEEN"))continue;
147 classToInd.remove(currentClass);
148 SortedSet<Individual> neg = new TreeSet<Individual>();
149 for (SortedSet<Individual> set : classToInd.values()) {
150 neg.addAll(set);
151 }
152 SortedSet<Integer> lines = getLines(allPos, neg);
153 KB kb = getKB(lines);
154 KRKModular km=new KRKModular(kb);
155 //starting reasone
156 //km.initReasonerFact();
157 String filename="";
158 if(i==0) filename="KRK_recognizerDRAW";
159 else filename="KRK_recognizer"+(i-1);
160 km.writeOWLFile(filename+".owl");
161
162 StringBuffer buf= new StringBuffer();
163 buf.append("\nimport(\""+filename+".owl"+"\");\n\n");
164
165 buf.append("refexamples.ignoredConcepts={\n");
166 buf.append("\""+ontologyURI+"#"+currentClass+"\"");
167 for (String str : classToInd.keySet()) {
168 buf.append(",\n");
169 buf.append("\""+ontologyURI+"#"+str+"\"");
170 }
171
172 buf.append("};\n\n");
173 buf.append("algorithm = refexamples;\n"+
174 "reasoner=fastInstanceChecker;\n"+
175 "refexamples.useAllConstructor = false;\n"+
176 "refexamples.useExistsConstructor = true;\n"+
177 "refexamples.useCardinalityRestrictions = false;\n"+
178 "refexamples.useNegation = false;\n\n\n");
179
180 for (Individual ind : allPos) {
181 buf.append("+\""+ind+"\"\n");
182 }
183 buf.append("\n\n\n");
184 for (Individual ind : neg) {
185 buf.append("-\""+ind+"\"\n");
186 }
187
188 writeToFile(workingDir+filename+".conf", buf.toString());
189 skript+= "./dllearner "+workingDir+filename+".conf >> "+workingDir+filename+"result.txt\n";
190 }
191 System.out.println(skript);
192 writeToFile(workingDir+"skript.sh", skript);
193
194
195
196 }
197
198
199 /**
200 * @param args
201 */
202 public static void main2(String[] args) {
203 init();
204 initAllInstancesAndReasoners();
205 System.out.println("initializing finished");
206 String currentClass = "ZERO";
207 SortedSet<Individual> allPos = classToInd.get(currentClass);
208
209
210 //if(allPos.size()<400)negativeExamplesAdded = allPos.size();
211 //else negativeExamplesAdded = 400;
212 SortedSet<Individual> tmp = new TreeSet<Individual>();
213 for (Individual individual : indToClass.keySet()) {
214 tmp.add(individual);
215 }
216
217 SortedSet<Individual> neg = getNegativeExamples(currentClass, tmp, negativeExamplesAdded);
218 SortedSet<Integer> lines = getLines(allPos, neg);
219 KB kb = getKB(lines);
220 Description d=null;
221 try{
222 d = KBParser.parseConcept("EXISTS \"http://dl-learner.org/krk#hasPiece\".(EXISTS \"http://dl-learner.org/krk#hasLowerRankThan\".(EXISTS \"http://dl-learner.org/krk#fileDistanceLessThan1\".(\"http://dl-learner.org/krk#BKing\" AND EXISTS \"http://dl-learner.org/krk#rankDistanceLessThan2\".(\"http://dl-learner.org/krk#WKing\" OR EXISTS \"http://dl-learner.org/krk#rankDistanceLessThan1\".EXISTS \"http://dl-learner.org/krk#rankDistanceLessThan3\".\"http://dl-learner.org/krk#WKing\")) AND (\"http://dl-learner.org/krk#FileA\" OR \"http://dl-learner.org/krk#WKing\")) AND (\"http://dl-learner.org/krk#FileC\" OR (\"http://dl-learner.org/krk#BKing\" AND \"http://dl-learner.org/krk#FileD\")))");
223 }catch (Exception e) {e.printStackTrace();}
224
225
226
227 while (true){
228
229
230 SortedSet<Individual> result = retrieveAll(d);
231 System.out.println(result);
232 System.out.println("still left: " + (result.size()-allPos.size()));
233 if(verify(currentClass, result)) {
234 System.out.println("Correct solution: "+ d.toKBSyntaxString(ontologyURI+"#", null));
235 break;}
236 neg.addAll(getNegativeExamples(currentClass, result, negativeExamplesAdded));
237 lines = getLines(allPos, neg);
238 kb = getKB(lines);
239 d= learn(kb, allPos, neg);
240
241 }
242
243
244 }
245
246 static Description learn(KB kb, SortedSet<Individual> pos,SortedSet<Individual> neg){
247
248 System.out.println(pos);
249 System.out.println(neg);
250
251 ComponentManager cm = ComponentManager.getInstance();
252 LearningAlgorithm la = null;
253 try {
254 Set<KnowledgeSource> sources = new HashSet<KnowledgeSource>();
255 sources.add(new KBFile(kb));
256 ReasonerComponent r = new FastInstanceChecker(sources);
257 r.init();
258 // ReasonerComponent rs = new ReasonerComponent(r);
259
260 //cm.learningProblem(lpClass, reasoner)
261 LearningProblem lp = new PosNegLPStandard(r);
262 //cm.getConfigOptionValue(lp, "");
263 cm.applyConfigEntry(lp, "positiveExamples",pos);
264 cm.applyConfigEntry(lp, "negativeExamples",neg);
265
266 lp.init();
267
268 la = cm.learningAlgorithm(ROLComponent2.class, lp, r);
269 SortedSet<String> ignoredConcepts = getIgnoredConcepts(pos, neg);
270
271 cm.applyConfigEntry(la,"useAllConstructor",false);
272 cm.applyConfigEntry(la,"useExistsConstructor",true);
273 cm.applyConfigEntry(la,"useCardinalityRestrictions",false);
274 cm.applyConfigEntry(la,"useNegation",false);
275 //cm.applyConfigEntry(la,"quiet",false);
276 cm.applyConfigEntry(la,"ignoredConcepts",ignoredConcepts);
277
278
279 la.init();
280
281 System.out.println("start learning");
282
283 la.start();
284 //System.out.println("best"+la.getBestSolution());
285
286 }catch (Exception e) {e.printStackTrace();}
287 return la.getCurrentlyBestDescription();
288 }
289
290 static KB getKB(SortedSet<Integer> lines){
291 BufferedReader in = null;
292 try {
293 in = new BufferedReader(new FileReader(allData));
294 } catch (FileNotFoundException e) {
295 e.printStackTrace();
296 }
297
298 KRKModular km = new KRKModular();
299 try {
300 String line = "";
301 int x = 0;
302 while ((line = in.readLine()) != null) {
303 Integer tmp = new Integer(x);
304 if(lines.contains(tmp))
305 km.addOneLineToKB(x, line);
306 x++;
307 }// endWhile
308 }catch (Exception e) {e.printStackTrace();}
309 return km.kb;
310
311 }
312
313
314 static SortedSet<Integer> getLines(SortedSet<Individual> pos,SortedSet<Individual> neg){
315 SortedSet<Integer> ret = new TreeSet<Integer>();
316
317 for (Individual individual : pos) {
318 int a = Integer.parseInt(individual.getName().substring((ontologyURI+"#g").length()));
319 ret.add(new Integer(a));
320 }
321 for (Individual individual : neg) {
322 int a = Integer.parseInt(individual.getName().substring((ontologyURI+"#g").length()));
323 ret.add(new Integer(a));
324 }
325 return ret;
326
327 }
328
329 static SortedSet<String> getIgnoredConcepts(SortedSet<Individual> pos,SortedSet<Individual> neg){
330 SortedSet<String> ret = new TreeSet<String>();
331
332 for (Individual individual : pos) {
333 String tmp = indToClass.get(individual);
334 //System.out.println("pos"+tmp+individual);
335 ret.add(ontologyURI+"#"+tmp);
336 }
337 for (Individual individual : neg) {
338 //String tmp = indToClass.get((Individual)individual);
339 //System.out.println("neg"+tmp+individual);
340 for (Individual string : indToClass.keySet()) {
341 if(string.toString().equals(individual.getName())){
342 ret.add(ontologyURI+"#"+indToClass.get(string));
343 //System.out.println("aaaaaaaa"+individual.getName());
344 }
345
346 }
347
348 }
349
350 //System.out.println(indToClass);
351 return ret;
352
353 }
354
355 public KRKModular() {
356 this.kb = makeOntologyTBox();
357 }
358 public KRKModular(KB kb) {
359 this.kb = kb;
360 }
361
362 public KRKModular(String concept) {
363 this.kb = makeOntologyTBox(concept);
364 }
365
366 public static void initAllInstancesAndReasoners(){
367 // Datei oeffnen
368 BufferedReader in = null;
369 try {
370 in = new BufferedReader(new FileReader(allData));
371 } catch (FileNotFoundException e) {
372 e.printStackTrace();
373 }
374 SimpleClock sc= new SimpleClock();
375 KRKModular km =null;
376 km = new KRKModular();
377 try {
378 String line = "";
379 int x = 0;
380 while ((line = in.readLine()) != null) {
381 if (x % 1000 == 0)
382 {sc.print("Currently at line " + x+" : ");}
383 km.addOneLineToKBinit(x, line);
384 if(x%1000==0 && x!=0){
385 km.initReasonerFact();
386 allReasoners.add(km.reasoner);
387 km = new KRKModular();
388 }
389 //if(x==200)break;
390 x++;
391 }// endWhile
392
393 km.initReasonerFact();
394 allReasoners.add(km.reasoner);
395 km.writeOWLFile();
396 km = null;
397
398
399 sc.printAndSet("initialization finished");
400
401 //sc.printAndSet("nach Retrieval");
402 //km.writeOWLFile();
403 /*SortedSet<Individual> s = new TreeSet<Individual>();
404 for (int i = 0; i < x; i++) {
405 s.add(getIndividual("g"+i));
406 //if(km.check2(i))howmany++;
407 }*/
408 //writeExampleSet(s);
409
410
411 //sc.printAndSet("before ");
412 //km.initReasonerFact();
413 //sc.printAndSet("after initfact");
414
415 //SortedSet<Individual> ret = km.checkAllOWLAPI(concept, s);
416 //sc.print("totalfic ("+ret.size()+") for 1000: ");
417
418
419 } catch (Exception e) {
420 e.printStackTrace();
421 }
422
423 }
424
425 public static void initAllInstancesWithoutReasoners(){
426 // Datei oeffnen
427 BufferedReader in = null;
428 try {
429 in = new BufferedReader(new FileReader(allData));
430 } catch (FileNotFoundException e) {
431 e.printStackTrace();
432 }
433 SimpleClock sc= new SimpleClock();
434 KRKModular km =null;
435 km = new KRKModular();
436 try {
437 String line = "";
438 int x = 0;
439 while ((line = in.readLine()) != null) {
440 if (x % 1000 == 0)
441 {sc.print("Currently at line " + x+" : ");}
442 km.addOneLineToKBinit(x, line);
443
444 //if(x==200)break;
445 x++;
446 }// endWhile
447 km = null;
448 sc.printAndSet("initialization finished");
449
450
451
452 } catch (Exception e) {
453 e.printStackTrace();
454 }
455
456 }
457
458
459
460 public static SortedSet<Individual> retrieveAll(String concept){
461 Description d = null;
462 try{
463 d = KBParser.parseConcept(concept);
464 }catch (Exception e) {e.printStackTrace();}
465 return retrieveAll(d);
466 }
467
468 public static SortedSet<Individual> retrieveAll(Description d){
469 SortedSet<Individual> ret = new TreeSet<Individual>();
470 try{
471
472 for (ReasonerComponent onereasoner : allReasoners) {
473 ret.addAll(onereasoner.getIndividuals(d));
474 }
475
476 }catch (Exception e) {e.printStackTrace();}
477 return ret;
478 }
479
480
481
482
483
484 public void initReasonerFact(){
485 KBFile kbFile = new KBFile(this.kb);
486 Set<KnowledgeSource> ks = new HashSet<KnowledgeSource>();
487 ks.add(kbFile);
488
489 reasoner = ComponentFactory.getOWLAPIReasoner(ks);
490
491 ((OWLAPIReasoner)reasoner).getConfigurator().setReasonerType("fact");
492 try{
493 reasoner.init();
494 }catch (Exception e) {e.printStackTrace();}
495 }
496
497
498
499 public void initFIC(){
500 KBFile kbFile = new KBFile(this.kb);
501 Set<KnowledgeSource> ks = new HashSet<KnowledgeSource>();
502 ks.add(kbFile);
503 //System.out.println("blabla");
504 reasoner = new FastInstanceChecker(ks);
505 //fic.setReasonerType("fact");
506 try{
507 reasoner.init();
508 }catch (Exception e) {e.printStackTrace();}
509 }
510
511 public KB makeOntologyTBox(){
512
513 KRKOntologyTBox tbox = new KRKOntologyTBox();
514 return tbox.getKb();
515
516 }
517
518 public KB makeOntologyTBox(String concept){
519
520 KRKOntologyTBox tbox = new KRKOntologyTBox();
521 tbox.addConcept(concept);
522 return tbox.getKb();
523
524 }
525
526
527 public void addOneLineToKBinit(int x, String line){
528
529 String[] ar = new String[6];
530 Individual gameind = KRKOntologyTBox.getIndividual("g" + x);
531 ar = tokenize(line);
532 addToHM(ar[6], gameind);
533 addOneLineToKB( x, line);
534
535
536 }
537
538 public void addOneLineToKB(int x, String line){
539
540 Individual gameind;
541 Individual wkingind;
542 Individual wrookind;
543 Individual bkingind;
544
545 String[] ar = new String[6];
546
547 ar = tokenize(line);
548
549 //String currentclass = ar[6];
550
551 gameind = KRKOntologyTBox.getIndividual("g" + x);
552 wkingind = KRKOntologyTBox.getIndividual("wking_" + ar[0] + ar[1] + "_" + x);
553 wrookind = KRKOntologyTBox.getIndividual("wrook_" + ar[2] + ar[3] + "_" + x);
554 bkingind = KRKOntologyTBox.getIndividual("bking_" + ar[4] + ar[5] + "_" + x);
555
556
557
558 //allInstances.add(gameind+"");
559 //allInstances.add(wkingind+"");
560 //allInstances.add(wrookind+"");
561 //allInstances.add(bkingind+"");
562
563 // save it for examplegeneration
564
565 // .add(gameind.getName());
566 //classSet.add(ar[6]);
567
568 // CLASSES
569 kb.addABoxAxiom(new ClassAssertionAxiom(KRKOntologyTBox.Game, gameind));
570 kb.addABoxAxiom(new ClassAssertionAxiom(
571 getAtomicConcept(ar[6]), gameind));
572 kb.addABoxAxiom(new ClassAssertionAxiom(KRKOntologyTBox.WKing, wkingind));
573 kb.addABoxAxiom(new ClassAssertionAxiom(KRKOntologyTBox.WRook, wrookind));
574 kb.addABoxAxiom(new ClassAssertionAxiom(KRKOntologyTBox.BKing, bkingind));
575
576
577 /**Files and Ranks***/
578 // FILES are letters
579 // RANKS are numbers
580
581 //WKing
582 kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept("File"+ar[0].toUpperCase()), wkingind));
583 kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept("Rank"+ar[1]) , wkingind));
584
585 //WRook
586 kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept("File"+ar[2].toUpperCase()), wrookind));
587 kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept("Rank"+ar[3]) , wrookind));
588
589 //BKing
590 kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept("File"+ar[4].toUpperCase()), bkingind));
591 kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept("Rank"+ar[5]), bkingind));
592
593
594
595 // PROPERTIES
596 kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.hasPiece, gameind,
597 wkingind));
598 kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.hasPiece, gameind,
599 wrookind));
600 kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.hasPiece, gameind,
601 bkingind));
602
603 // labels
604
605 KRKPiece WKingPiece = new KRKPiece(wkingind, ar[0], Integer
606 .parseInt(ar[1]));
607 KRKPiece WRookPiece = new KRKPiece(wrookind, ar[2], Integer
608 .parseInt(ar[3]));
609 KRKPiece BKingPiece = new KRKPiece(bkingind, ar[4], Integer
610 .parseInt(ar[5]));
611
612 makeDistanceRoles(WKingPiece, WRookPiece);
613 makeDistanceRoles(WKingPiece, BKingPiece);
614 makeDistanceRoles(WRookPiece, BKingPiece);
615
616 }
617
618
619 /*protected static void verifySomeConcepts(OntologyCloser oc) {
620
621 ArrayList<String> test=new ArrayList<String>();
622 test.add("(EXISTS \"http://www.test.de/test#hasPiece\".EXISTS \"http://www.test.de/test#rankDistanceLessThan2\".(\"http://www.test.de/test#BKing\" AND EXISTS \"http://www.test.de/test#fileDistanceLessThan1\".(\"http://www.test.de/test#A\" OR \"http://www.test.de/test#WKing\")) AND EXISTS \"http://www.test.de/test#hasPiece\".(\"http://www.test.de/test#WKing\" AND ((\"http://www.test.de/test#C\" AND EXISTS \"http://www.test.de/test#hasLowerRankThan\".\"http://www.test.de/test#A\") OR (\"http://www.test.de/test#F3\" AND EXISTS \"http://www.test.de/test#rankDistance2\".\"http://www.test.de/test#WRook\"))))");
623 for (int i = 0; i < test.size(); i++) {
624 String conceptStr = test.get(i);
625 oc.verifyConcept(conceptStr);
626 }
627 /*conceptStr = "EXISTS \"http://www.test.de/test#hasLowerRankThan\"."+
628 "(\"http://www.test.de/test#WRook\""+
629 "AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\") ";
630
631 System.out.println();
632 }*/
633
634 public void makeDistanceRoles(KRKPiece A, KRKPiece B) {
635 int Fdist = A.getFileDistance(B);
636 int Rdist = A.getRankDistance(B);
637 String rdistance = "rankDistance";
638 String fdistance = "fileDistance";
639
640 kb.addABoxAxiom(new ObjectPropertyAssertion(getRole(rdistance + Rdist),
641 A.id, B.id));
642 kb.addABoxAxiom(new ObjectPropertyAssertion(getRole(fdistance + Fdist),
643 A.id, B.id));
644
645 if (A.meHasLowerFileThan(B)){
646 kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.fileLessThan, A.id,
647 B.id));
648 if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.fileHigherThan, B.id,
649 A.id));
650 }
651 else if (B.meHasLowerFileThan(A)){
652 kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.fileLessThan, B.id,
653 A.id));
654 if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.fileHigherThan, A.id,
655 B.id));
656 }
657
658 if (A.meHasLowerRankThan(B)){
659 kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.rankLessThan, A.id,
660 B.id));
661 if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.rankHigherThan, B.id,
662 A.id));
663 }
664 else if (B.meHasLowerRankThan(A)){
665 kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.rankLessThan, B.id,
666 A.id));
667 if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.rankHigherThan, A.id,
668 B.id));
669
670 }
671 }
672
673
674
675
676 protected static void writeExampleSet(Set<Individual> s) {
677 for (Individual individual : s) {
678 writeToFile(workingDir+"example.txt", "+\""+individual.getName()+"\"\n");
679 }
680
681 }
682
683
684
685
686
687 /*protected static void writeExampleSets() {
688 StringBuffer collect1 = new StringBuffer();
689 StringBuffer collect2 = new StringBuffer();
690 System.out.println("start writing sets");
691
692 for (String keys : classToInd.keySet()) {
693 System.out.println(keys);
694 SortedSet<String> tmpset = classToInd.get(keys);
695 for (String individuals : tmpset) {
696 collect1.append("+\"" + individuals + "\"\n");
697 collect2.append("-\"" + individuals + "\"\n");
698 }
699
700 writeToFile(workingDir+"/examples_for_" + keys + ".txt", collect1
701 + "\n\n" + collect2 + "\n");
702 collect1 = new StringBuffer();
703 collect2 = new StringBuffer();
704 }
705 // System.out.println("Sets written");
706 collect1 = new StringBuffer();
707 collect2 = new StringBuffer();
708 for (String key : classToInd.keySet()) {
709
710 SortedSet<String> tmpset = classToInd.get(key);
711
712 if (key.equals("ZERO")) {*/
713 // collect1.append("/**" + key + "**/\n");
714 /* for (String individuals : tmpset) {
715 collect1.append("+\"" + individuals + "\"\n");
716 }
717
718 continue;
719 } else { */
720 // collect2.append("/**" + key + "**/\n");
721 /* for (String individuals : tmpset) {
722 collect2.append("-\"" + individuals + "\"\n");
723 }
724 }
725
726 }
727 writeToFile(workingDir+"/examples_for_ZERO_and_Rest.txt", collect1
728 + "\n\n" + collect2 + "\n");
729 System.out.println("Example sets written");
730 }
731 */
732
733
734
735
736
737
738 /*protected void writeOWLFile(String filename) {
739
740 Iterator<String> it = classSet.iterator();
741 System.out.println("import(\"" + filename + "\");");
742 String collect = "refinement.ignoredConcepts={";
743 while (it.hasNext()) {
744 String tmp = (String) it.next();
745 collect += "\n\"" + getAtomicConcept(tmp).getName() + "\",";
746 }
747 collect = collect.substring(0, collect.length() - 1);
748 System.out.println(collect + "};");
749
750 System.out.println("Writing owl");
751 File owlfile = new File(workingDir+"/" + filename);
752 // System.out.println(kb.toString("http://www.test.de/test", new
753 // HashMap<String, String>()));
754 OWLAPIReasoner.exportKBToOWL(owlfile, kb, ontologyURI);
755
756 }*/
757
758 protected void writeOWLFile() {
759 writeOWLFile("test.owl");
760 }
761
762 protected void writeOWLFile(String filename) {
763
764 System.out.println("Writing owl");
765 File owlfile = new File(workingDir+"/" + filename);
766 OWLAPIReasoner.exportKBToOWL(owlfile, this.kb, ontologyURI);
767
768 }
769
770
771
772 protected static void writeToFile(String filename, String content) {
773 // create the file we want to use
774 File file = new File(filename);
775
776 try {
777 file.createNewFile();
778 FileOutputStream fos = new FileOutputStream(filename, true);
779 // ObjectOutputStream o = new ObjectOutputStream(fos);
780 fos.write(content.getBytes());
781 fos.flush();
782 fos.close();
783 } catch (IOException e) {
784 e.printStackTrace();
785 }
786 }
787
788 protected static void addToHM(String className, Individual ind) {
789 if (classToInd.get(className) == null)
790 classToInd.put(className, new TreeSet<Individual>());
791
792 classToInd.get(className).add(ind);
793 indToClass.put(ind, className);
794
795 }
796
797
798 protected static Individual getIndividual(String name) {
799 return new Individual(ontologyURI + "#" + name);
800 }
801
802 protected static ObjectProperty getRole(String name) {
803 return new ObjectProperty(ontologyURI + "#" + name);
804 }
805
806 protected static NamedClass getAtomicConcept(String name) {
807 return new NamedClass(ontologyURI + "#" + name);
808 }
809
810 public static String[] tokenize(String s) {
811 StringTokenizer st = new StringTokenizer(s, ",");
812
813 String tmp = "";
814 String[] ret = new String[7];
815 int x = 0;
816 while (st.hasMoreTokens()) {
817 tmp = st.nextToken();
818 if (x == 6)
819 tmp = tmp.toUpperCase();
820 ret[x] = tmp;
821 x++;
822 }
823 return ret;
824
825 }
826
827 static SortedSet<Individual> getNegativeExamples(String currentClass, SortedSet<Individual> allRetrieved, int howmany) {
828 SortedSet<Individual> ret = new TreeSet<Individual>();
829
830 //clean
831 SortedSet<Individual> allPos = classToInd.get(currentClass);
832 for (Individual individual : allPos) {
833 if(!allRetrieved.remove(individual))System.out.println("WARNING, not all positives covered");;
834 }
835
836 Random r = new Random();
837 double treshold = ((double)howmany)/allRetrieved.size();
838 //System.out.println("treshold"+howmany);
839 //System.out.println("treshold"+allRetrieved.size());
840 //System.out.println("treshold"+treshold);
841 int added=0;
842 for (Individual oneInd : allRetrieved) {
843 if(r.nextDouble()<treshold) {
844 ret.add(oneInd);
845 added++;
846 }
847 }
848 System.out.println(added+" new negs added");
849 return ret;
850 }
851 static boolean verify(String currentClass, SortedSet<Individual> allRetrieved) {
852 //clean
853 SortedSet<Individual> allPos = classToInd.get(currentClass);
854 boolean hasAll=true;
855 for (Individual individual : allPos) {
856 if(!allRetrieved.contains(individual))hasAll=false;
857 }
858 if(hasAll && allRetrieved.size()==allPos.size()){return true;}
859 else return false;
860
861 }
862
863 /*public SortedSet<Individual> checkAll(String concept, SortedSet<Individual> s){
864 try{
865 Description d = KBParser.parseConcept(concept,ontologyURI.toString()+"#");
866
867 return reasoner.instanceCheck(d, s);
868 }catch (Exception e) {e.printStackTrace();}
869 return null;
870 }
871
872 public SortedSet<Individual> checkAllOWLAPI(String concept,SortedSet<Individual> s){
873 try{
874 Description d = KBParser.parseConcept(concept,ontologyURI.toString()+"#");
875 return reasoner.instanceCheck(d, s);
876 }catch (Exception e) {e.printStackTrace();}
877 return null;
878 }
879
880 /*public SortedSet<Individual> retrieveAllowlAPI(String concept){
881 try{
882 Description d = KBParser.parseConcept(concept,ontologyURI.toString()+"#");
883 return reasoner.retrieval(d);
884 }catch (Exception e) {e.printStackTrace();}
885 return null;
886 }*/
887
888
889 }