-
Notifications
You must be signed in to change notification settings - Fork 34
/
PRConvergenceExperiment.java
1810 lines (1519 loc) · 73.6 KB
/
PRConvergenceExperiment.java
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (C) 2007 - 2016, Jens Lehmann
*
* This file is part of DL-Learner.
*
* DL-Learner is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* DL-Learner is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dllearner.algorithms.qtl.experiments;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.*;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.jamonapi.Monitor;
import com.jamonapi.MonitorFactory;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.aksw.jena_sparql_api.cache.core.QueryExecutionFactoryCacheEx;
import org.aksw.jena_sparql_api.core.QueryExecutionFactory;
import org.apache.commons.collections15.ListUtils;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.apache.commons.math3.random.RandomDataGenerator;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.apache.commons.math3.stat.descriptive.SynchronizedDescriptiveStatistics;
import org.apache.commons.math3.util.Pair;
import org.apache.jena.graph.Node;
import org.apache.jena.query.*;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.sparql.core.Var;
import org.apache.jena.sparql.expr.ExprAggregator;
import org.apache.jena.sparql.expr.ExprVar;
import org.apache.jena.sparql.expr.aggregate.AggCountVarDistinct;
import org.apache.jena.sparql.syntax.Element;
import org.apache.jena.sparql.syntax.ElementGroup;
import org.apache.jena.vocabulary.RDF;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.dllearner.algorithms.qtl.QTL2Disjunctive;
import org.dllearner.algorithms.qtl.QTL2DisjunctiveMultiThreaded;
import org.dllearner.algorithms.qtl.QueryTreeUtils;
import org.dllearner.algorithms.qtl.datastructures.impl.EvaluatedRDFResourceTree;
import org.dllearner.algorithms.qtl.datastructures.impl.RDFResourceTree;
import org.dllearner.algorithms.qtl.heuristics.QueryTreeHeuristic;
import org.dllearner.algorithms.qtl.heuristics.QueryTreeHeuristicSimple;
import org.dllearner.algorithms.qtl.impl.QueryTreeFactoryBaseInv;
import org.dllearner.algorithms.qtl.operations.lgg.LGGGenerator;
import org.dllearner.algorithms.qtl.operations.lgg.LGGGeneratorSimple;
import org.dllearner.algorithms.qtl.util.Entailment;
import org.dllearner.algorithms.qtl.util.filters.PredicateExistenceFilter;
import org.dllearner.algorithms.qtl.util.statistics.TimeMonitors;
import org.dllearner.core.ComponentAnn;
import org.dllearner.core.ComponentInitException;
import org.dllearner.core.EvaluatedDescription;
import org.dllearner.core.StringRenderer;
import org.dllearner.core.StringRenderer.Rendering;
import org.dllearner.kb.sparql.*;
import org.dllearner.learningproblems.Heuristics;
import org.dllearner.learningproblems.Heuristics.HeuristicType;
import org.dllearner.learningproblems.PosNegLPStandard;
import org.dllearner.utilities.QueryUtils;
import org.semanticweb.owlapi.io.OWLObjectRenderer;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.slf4j.LoggerFactory;
import uk.ac.manchester.cs.owl.owlapi.OWLNamedIndividualImpl;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* @author Lorenz Buehmann
*
*/
@SuppressWarnings("unchecked")
public class PRConvergenceExperiment {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(PRConvergenceExperiment.class.getName());
private static final ParameterizedSparqlString superClassesQueryTemplate2 = new ParameterizedSparqlString(
"PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> PREFIX owl: <http://www.w3.org/2002/07/owl#> "
+ "SELECT ?sup WHERE {"
+ "?sub ((rdfs:subClassOf|owl:equivalentClass)|^owl:equivalentClass)+ ?sup .}");
private static final ParameterizedSparqlString superClassesQueryTemplate = new ParameterizedSparqlString(
"PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> PREFIX owl: <http://www.w3.org/2002/07/owl#> "
+ "SELECT ?sup WHERE {"
+ "?sub (rdfs:subClassOf|owl:equivalentClass)+ ?sup .}");
private static final DecimalFormat dfPercent = new DecimalFormat("0.00%");
enum Baseline {
RANDOM, MOST_POPULAR_TYPE_IN_KB, MOST_FREQUENT_TYPE_IN_EXAMPLES, MOST_INFORMATIVE_EDGE_IN_EXAMPLES, LGG, MOST_FREQUENT_EDGE_IN_EXAMPLES
}
private QueryExecutionFactory qef;
private org.dllearner.algorithms.qtl.impl.QueryTreeFactory queryTreeFactory;
private ConciseBoundedDescriptionGenerator cbdGen;
private RandomDataGenerator rnd = new RandomDataGenerator();
private EvaluationDataset dataset;
private Map<String, List<String>> cache = new HashMap<>();
private int kbSize;
private boolean splitComplexQueries = true;
private PredicateExistenceFilter filter;
// the directory where all files, results etc. are maintained
private File benchmarkDirectory;
// whether to write eval results to a database
private boolean write2DB;
// DB related objects
private Connection conn;
private PreparedStatement psInsertOverallEval;
private PreparedStatement psInsertDetailEval;
// max. time for each QTL run
private int maxExecutionTimeInSeconds = 600;
private int minNrOfPositiveExamples = 9;
private int maxTreeDepth = 2;
private NoiseGenerator.NoiseMethod noiseMethod = NoiseGenerator.NoiseMethod.RANDOM;
private NoiseGenerator noiseGenerator;
// whether to override existing results
private boolean override = false;
// parameters
private int[] nrOfExamplesIntervals = {
// 5,
// 10,
// 15,
20,
// 25,
// 30
};
private double[] noiseIntervals = {
0.0,
// 0.1,
// 0.2,
// 0.3,
// 0.4,
// 0.6
};
private QueryTreeHeuristic[] heuristics = {
new QueryTreeHeuristicSimple(),
// new QueryTreeHeuristicComplex(qef)
};
private HeuristicType[] measures = {
HeuristicType.PRED_ACC,
// HeuristicType.FMEASURE,
// HeuristicType.MATTHEWS_CORRELATION
};
private final Map<String, ExampleCandidates> query2Examples = new HashMap<>();
private File cacheDirectory;
private boolean useEmailNotification = false;
private int nrOfThreads;
OWLObjectRenderer owlRenderer = new org.dllearner.utilities.owl.DLSyntaxObjectRenderer();
DescriptiveStatistics treeSizeStats = new DescriptiveStatistics();
private long timeStamp;
Set<String> queriesToProcessTokens = Sets.newHashSet(
// "Natalie_Portman"
// "Pakistan"
// "Lou_Reed"
);
Set<String> queriesToOmitTokens = Sets.newHashSet(
// "Lou_Reed"
// "Pakistan"
);
String databaseName;
public PRConvergenceExperiment(EvaluationDataset dataset, File benchmarkDirectory, boolean write2DB, boolean override, int maxQTLRuntime, boolean useEmailNotification, int nrOfThreads) {
this.dataset = dataset;
this.benchmarkDirectory = benchmarkDirectory;
this.write2DB = write2DB;
this.override = override;
this.maxExecutionTimeInSeconds = maxQTLRuntime;
this.useEmailNotification = useEmailNotification;
this.nrOfThreads = nrOfThreads;
queryTreeFactory = new QueryTreeFactoryBaseInv();
queryTreeFactory.setMaxDepth(maxTreeDepth);
// add some filters to avoid resources with namespaces like http://dbpedia.org/property/
List<Predicate<Statement>> var = dataset.getQueryTreeFilters();
queryTreeFactory.addDropFilters((Predicate<Statement>[]) var.toArray(new Predicate[var.size()]));
qef = dataset.getKS().getQueryExecutionFactory();
cbdGen = new SymmetricConciseBoundedDescriptionGeneratorImpl(qef);
cbdGen = new TreeBasedConciseBoundedDescriptionGenerator(qef);
rnd.reSeed(123);
noiseGenerator = new NoiseGenerator(qef, rnd);
kbSize = getKBSize();
timeStamp = System.currentTimeMillis();
if(write2DB) {
setupDatabase();
}
cacheDirectory = new File(benchmarkDirectory, "cache");
filter = dataset.getPredicateFilter();
databaseName = "QTL_" + dataset.getName() + "_" + timeStamp;
}
private void setupDatabase() {
try {
Properties config = new Properties();
config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("org/dllearner/algorithms/qtl/qtl-eval-config.properties"));
String url = config.getProperty("url");
String username = config.getProperty("username");
String password = config.getProperty("password");
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
java.sql.Statement stmt = conn.createStatement();
// create database
logger.info("Creating database " + databaseName + "'");
String sql = "CREATE DATABASE IF NOT EXISTS" + databaseName;
stmt.executeUpdate(sql);
logger.info("Database created successfully.");
// switch to database
conn.setCatalog(databaseName);
stmt = conn.createStatement();
// // empty tables if override
// if(override) {
// sql = "DROP TABLE IF EXISTS eval_overall,eval_detailed;";
// sql = "ALTER TABLE IF EXISTS eval_overall DROP PRIMARY KEY;";
// stmt.execute(sql);
// }
// create tables if not exist
sql = "CREATE TABLE IF NOT EXISTS eval_overall (" +
"heuristic VARCHAR(100), " +
"heuristic_measure VARCHAR(100), " +
"nrOfExamples TINYINT, " +
"noise DOUBLE, " +
"avg_fscore_best_returned DOUBLE, " +
"avg_precision_best_returned DOUBLE, " +
"avg_recall_best_returned DOUBLE, " +
"avg_predacc_best_returned DOUBLE, " +
"avg_mathcorr_best_returned DOUBLE, " +
"avg_position_best DOUBLE, " +
"avg_fscore_best DOUBLE, " +
"avg_precision_best DOUBLE, " +
"avg_recall_best DOUBLE, " +
"avg_predacc_best DOUBLE, " +
"avg_mathcorr_best DOUBLE, " +
"avg_fscore_baseline DOUBLE, " +
"avg_precision_baseline DOUBLE, " +
"avg_recall_baseline DOUBLE, " +
"avg_predacc_baseline DOUBLE, " +
"avg_mathcorr_baseline DOUBLE, " +
"avg_runtime_best_returned DOUBLE, " +
"PRIMARY KEY(heuristic, heuristic_measure, nrOfExamples, noise))";
stmt.execute(sql);
sql = "CREATE TABLE IF NOT EXISTS eval_detailed (" +
"target_query VARCHAR(700)," +
"nrOfExamples TINYINT, " +
"noise DOUBLE, " +
"heuristic VARCHAR(50), " +
"heuristic_measure VARCHAR(50), " +
"query_top LONGTEXT, " +
"fscore_top DOUBLE, " +
"precision_top DOUBLE, " +
"recall_top DOUBLE, " +
"best_query LONGTEXT," +
"best_rank SMALLINT, " +
"best_fscore DOUBLE, " +
"best_precision DOUBLE, " +
"best_recall DOUBLE, " +
"baseline_query TEXT," +
"baseline_fscore DOUBLE, " +
"baseline_precision DOUBLE, " +
"baseline_recall DOUBLE, " +
"runtime_top INT, " +
"PRIMARY KEY(target_query, nrOfExamples, noise, heuristic, heuristic_measure)) ENGINE=MyISAM";
stmt.execute(sql);
sql = "INSERT INTO eval_overall ("
+ "heuristic, heuristic_measure, nrOfExamples, noise, "
+ "avg_fscore_best_returned, avg_precision_best_returned, avg_recall_best_returned,"
+ "avg_predacc_best_returned, avg_mathcorr_best_returned, "
+ "avg_position_best, avg_fscore_best, avg_precision_best, avg_recall_best, avg_predacc_best, avg_mathcorr_best,"
+ "avg_fscore_baseline, avg_precision_baseline, avg_recall_baseline, avg_predacc_baseline, avg_mathcorr_baseline,"
+ "avg_runtime_best_returned"
+ ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
if(override) {
sql += " ON DUPLICATE KEY UPDATE ";
sql += "avg_fscore_best_returned = VALUES(avg_fscore_best_returned),";
sql += "avg_precision_best_returned = VALUES(avg_precision_best_returned),";
sql += "avg_recall_best_returned = VALUES(avg_recall_best_returned),";
sql += "avg_predacc_best_returned = VALUES(avg_predacc_best_returned),";
sql += "avg_mathcorr_best_returned = VALUES(avg_mathcorr_best_returned),";
sql += "avg_position_best = VALUES(avg_position_best),";
sql += "avg_fscore_best = VALUES(avg_fscore_best),";
sql += "avg_precision_best = VALUES(avg_precision_best),";
sql += "avg_recall_best = VALUES(avg_recall_best),";
sql += "avg_predacc_best = VALUES(avg_predacc_best),";
sql += "avg_mathcorr_best = VALUES(avg_mathcorr_best),";
sql += "avg_fscore_baseline = VALUES(avg_fscore_baseline),";
sql += "avg_precision_baseline = VALUES(avg_precision_baseline),";
sql += "avg_recall_baseline = VALUES(avg_recall_baseline),";
sql += "avg_predacc_baseline = VALUES(avg_predacc_baseline),";
sql += "avg_mathcorr_baseline = VALUES(avg_mathcorr_baseline),";
sql += "avg_runtime_best_returned = VALUES(avg_runtime_best_returned)";
}
psInsertOverallEval = conn.prepareStatement(sql);
sql = "INSERT INTO eval_detailed ("
+ "target_query, nrOfExamples, noise, heuristic, heuristic_measure, "
+ "query_top, fscore_top, precision_top, recall_top,"
+ "best_query, best_rank, best_fscore, best_precision, best_recall, "
+ "baseline_query,baseline_fscore, baseline_precision, baseline_recall,"
+ "runtime_top"
+ ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
if(override) {
sql += " ON DUPLICATE KEY UPDATE ";
sql += "query_top = VALUES(query_top),";
sql += "fscore_top = VALUES(fscore_top),";
sql += "precision_top = VALUES(precision_top),";
sql += "recall_top = VALUES(recall_top),";
sql += "best_query = VALUES(best_query),";
sql += "best_rank = VALUES(best_rank),";
sql += "best_fscore = VALUES(best_fscore),";
sql += "best_precision = VALUES(best_precision),";
sql += "best_recall = VALUES(best_recall),";
sql += "baseline_query = VALUES(baseline_query),";
sql += "baseline_fscore = VALUES(baseline_fscore),";
sql += "baseline_precision = VALUES(baseline_precision),";
sql += "baseline_recall = VALUES(baseline_recall),";
sql += "runtime_top = VALUES(runtime_top)";
}
psInsertDetailEval = conn.prepareStatement(sql);
} catch (Exception e) {
throw new RuntimeException("Database setup failed", e);
}
}
private int getKBSize() {
String query = "SELECT (COUNT(DISTINCT ?s) AS ?cnt) WHERE {?s a ?type . ?type a <http://www.w3.org/2002/07/owl#Class> .}";
QueryExecution qe = qef.createQueryExecution(query);
ResultSet rs = qe.execSelect();
int size = rs.next().get("cnt").asLiteral().getInt();
qe.close();
return size;
}
public void setQueriesToOmitTokens(Collection<String> queriesToOmitTokens) {
this.queriesToOmitTokens.addAll(queriesToOmitTokens);
}
public void setQueriesToOmitTokens(Set<String> queriesToOmitTokens) {
this.queriesToOmitTokens = queriesToOmitTokens;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public void run(int maxNrOfProcessedQueries, int maxTreeDepth, int[] exampleInterval, double[] noiseInterval, HeuristicType[] measures) throws Exception{
this.maxTreeDepth = maxTreeDepth;
queryTreeFactory.setMaxDepth(maxTreeDepth);
if(exampleInterval != null) {
nrOfExamplesIntervals = exampleInterval;
}
if(noiseInterval != null) {
this.noiseIntervals = noiseInterval;
}
if(measures != null) {
this.measures = measures;
}
boolean noiseEnabled = noiseIntervals.length > 1 || noiseInterval[0] > 0;
boolean posOnly = noiseEnabled ? false : true;
logger.info("Started QTL evaluation...");
long t1 = System.currentTimeMillis();
List<String> queries = dataset.getSparqlQueries().values().stream().map(q -> q.toString()).collect(Collectors.toList());
logger.info("#loaded queries: " + queries.size());
// filter for debugging purposes
queries = queries.stream().filter(q -> queriesToProcessTokens.stream().noneMatch(t -> !q.contains(t))).collect(Collectors.toList());
queries = queries.stream().filter(q -> queriesToOmitTokens.stream().noneMatch(t -> q.contains(t))).collect(Collectors.toList());
if(maxNrOfProcessedQueries == -1) {
maxNrOfProcessedQueries = queries.size();
}
// queries = filter(queries, (int) Math.ceil((double) maxNrOfProcessedQueries / maxTreeDepth));
// queries = queries.subList(0, Math.min(queries.size(), maxNrOfProcessedQueries));
logger.info("#queries to process: " + queries.size());
// generate examples for each query
logger.info("precomputing pos. and neg. examples...");
for (String query : queries) {//if(!(query.contains("Borough_(New_York_City)")))continue;
query2Examples.put(query, generateExamples(query, posOnly, noiseEnabled));
}
logger.info("precomputing pos. and neg. examples finished.");
// check for queries that do not return any result (should not happen, but we never know)
Set<String> emptyQueries = query2Examples.entrySet().stream()
.filter(e -> e.getValue().correctPosExampleCandidates.isEmpty())
.map(e -> e.getKey())
.collect(Collectors.toSet());
logger.info("got {} empty queries.", emptyQueries.size());
queries.removeAll(emptyQueries);
// min. pos examples
int min = 3;
Set<String> lowNrOfExamplesQueries = query2Examples.entrySet().stream()
.filter(e -> e.getValue().correctPosExampleCandidates.size() < min)
.map(e -> e.getKey())
.collect(Collectors.toSet());
logger.info("got {} queries with < {} pos. examples.", emptyQueries.size(), min);
queries.removeAll(lowNrOfExamplesQueries);
queries = queries.subList(0, Math.min(80, queries.size()));
CBDStructureTree defaultCbdStructure = CBDStructureTree.fromTreeString("root:[out:[out:[]],in:[in:[],out:[]]]");
final int totalNrOfQTLRuns = heuristics.length * this.measures.length * nrOfExamplesIntervals.length * noiseIntervals.length * queries.size();
logger.info("#QTL runs: " + totalNrOfQTLRuns);
final AtomicInteger currentNrOfFinishedRuns = new AtomicInteger(0);
// loop over heuristics
for(final QueryTreeHeuristic heuristic : heuristics) {
final String heuristicName = heuristic.getClass().getAnnotation(ComponentAnn.class).shortName();
// loop over heuristics measures
for (HeuristicType measure : this.measures) {
final String measureName = measure.toString();
heuristic.setHeuristicType(measure);
double[][] data = new double[nrOfExamplesIntervals.length][noiseIntervals.length];
// loop over number of positive examples
for (int i = 0; i < nrOfExamplesIntervals.length; i++) {
final int nrOfExamples = nrOfExamplesIntervals[i];
// loop over noise value
for (int j = 0; j < noiseIntervals.length; j++) {
final double noise = noiseIntervals[j];
// check if not already processed
File logFile = new File(benchmarkDirectory, "qtl2-" + nrOfExamples + "-" + noise + "-" + heuristicName + "-" + measureName + ".log");
File statsFile = new File(benchmarkDirectory, "qtl2-" + nrOfExamples + "-" + noise + "-" + heuristicName + "-" + measureName + ".stats");
if(!override && logFile.exists() && statsFile.exists()) {
logger.info("Eval config already processed. For re-running please remove corresponding output files.");
continue;
}
FileAppender appender = null;
try {
appender = new FileAppender(new SimpleLayout(), logFile.getPath(), false);
Logger.getRootLogger().addAppender(appender);
} catch (IOException e) {
e.printStackTrace();
}
logger.info("#examples: " + nrOfExamples + " noise: " + noise);
final DescriptiveStatistics nrOfReturnedSolutionsStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics baselinePrecisionStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics baselineRecallStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics baselineFMeasureStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics baselinePredAccStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics baselineMathCorrStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionPrecisionStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionRecallStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionFMeasureStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionPredAccStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionMathCorrStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionRuntimeStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionPrecisionStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionRecallStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionFMeasureStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionPredAccStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionMathCorrStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionPositionStats = new SynchronizedDescriptiveStatistics();
MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).reset();
MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).reset();
ExecutorService tp = Executors.newFixedThreadPool(nrOfThreads);
// indicates if the execution for some of the queries failed
final AtomicBoolean failed = new AtomicBoolean(false);
Set<String> queriesToProcess = new TreeSet<>(queries);
queriesToProcess.retainAll(
query2Examples.entrySet().stream()
.filter(e -> e.getValue().correctPosExampleCandidates.size() >= nrOfExamples)
.map(e -> e.getKey())
.collect(Collectors.toSet()));
// loop over SPARQL queries
for (final String sparqlQuery : queriesToProcess) {
// CBDStructureTree cbdStructure = defaultCbdStructure;//QueryUtils.getOptimalCBDStructure(QueryFactory.create(sparqlQuery));
CBDStructureTree cbdStructure = QueryUtils.getOptimalCBDStructure(QueryFactory.create(sparqlQuery));
tp.submit(() -> {
logger.info("CBD tree:" + cbdStructure.toStringVerbose());
logger.info("##############################################################");
logger.info("Processing query\n" + sparqlQuery);
// we repeat it n times with different permutations of examples
int nrOfPermutations = 1;
if(nrOfExamples >= query2Examples.get(sparqlQuery).correctPosExampleCandidates.size()){
nrOfPermutations = 1;
}
for(int perm = 1; perm <= nrOfPermutations; perm++) {
logger.info("Run {}/{}", perm, nrOfPermutations);
try {
ExamplesWrapper examples = getExamples(sparqlQuery, nrOfExamples, nrOfExamples, noise, cbdStructure);
logger.info("pos. examples:\n" + Joiner.on("\n").join(examples.correctPosExamples));
logger.info("neg. examples:\n" + Joiner.on("\n").join(examples.correctNegExamples));
// write examples to disk
File dir = new File(benchmarkDirectory, "data/" + hash(sparqlQuery));
dir.mkdirs();
Files.write(Joiner.on("\n").join(examples.correctPosExamples),
new File(dir, "examples" + perm + "_" + nrOfExamples + "_" + noise + ".tp"), Charsets.UTF_8);
Files.write(Joiner.on("\n").join(examples.correctNegExamples),
new File(dir, "examples" + perm + "_" + nrOfExamples + "_" + noise + ".tn"), Charsets.UTF_8);
Files.write(Joiner.on("\n").join(examples.falsePosExamples),
new File(dir, "examples" + perm + "_" + nrOfExamples + "_" + noise + ".fp"), Charsets.UTF_8);
// compute baseline
RDFResourceTree baselineSolution = applyBaseLine(examples, Baseline.MOST_INFORMATIVE_EDGE_IN_EXAMPLES);
logger.info("Evaluating baseline...");
Score baselineScore = computeScore(sparqlQuery, baselineSolution, noise);
logger.info("Baseline score:\n" + baselineScore);
String baseLineQuery = QueryTreeUtils.toSPARQLQueryString(
baselineSolution, dataset.getBaseIRI(), dataset.getPrefixMapping());
baselinePrecisionStats.addValue(baselineScore.precision);
baselineRecallStats.addValue(baselineScore.recall);
baselineFMeasureStats.addValue(baselineScore.fmeasure);
baselinePredAccStats.addValue(baselineScore.predAcc);
baselineMathCorrStats.addValue(baselineScore.mathCorr);
// run QTL
PosNegLPStandard lp = new PosNegLPStandard();
lp.setPositiveExamples(examples.posExamplesMapping.keySet());
lp.setNegativeExamples(examples.negExamplesMapping.keySet());
// QTL2Disjunctive la = new QTL2Disjunctive(lp, qef);
QTL2DisjunctiveMultiThreaded la = new QTL2DisjunctiveMultiThreaded(lp, qef);
la.setRenderer(new org.dllearner.utilities.owl.DLSyntaxObjectRenderer());
la.setReasoner(dataset.getReasoner());
la.setEntailment(Entailment.SIMPLE);
la.setTreeFactory(queryTreeFactory);
la.setPositiveExampleTrees(examples.posExamplesMapping);
la.setNegativeExampleTrees(examples.negExamplesMapping);
la.setNoise(noise);
la.setHeuristic(heuristic);
la.setMaxExecutionTimeInSeconds(maxExecutionTimeInSeconds);
la.setMaxTreeComputationTimeInSeconds(maxExecutionTimeInSeconds);
la.init();
la.start();
List<EvaluatedRDFResourceTree> solutions = new ArrayList<>(la.getSolutions());
// List<EvaluatedRDFResourceTree> solutions = generateSolutions(examples, noise, heuristic);
nrOfReturnedSolutionsStats.addValue(solutions.size());
// the best returned solution by QTL
EvaluatedRDFResourceTree bestSolution = solutions.get(0);
logger.info("Got " + solutions.size() + " query trees.");
// logger.info("Best computed solution:\n" + render(bestSolution.asEvaluatedDescription()));
logger.info("QTL Score:\n" + bestSolution.getTreeScore());
long runtimeBestSolution = la.getTimeBestSolutionFound();
bestReturnedSolutionRuntimeStats.addValue(runtimeBestSolution);
// convert to SPARQL query
RDFResourceTree tree = bestSolution.getTree();
tree = filter.apply(tree);
String learnedSPARQLQuery = QueryTreeUtils.toSPARQLQueryString(
tree, dataset.getBaseIRI(), dataset.getPrefixMapping());
// compute score
Score score = computeScore(sparqlQuery, tree, noise);
bestReturnedSolutionPrecisionStats.addValue(score.precision);
bestReturnedSolutionRecallStats.addValue(score.recall);
bestReturnedSolutionFMeasureStats.addValue(score.fmeasure);
bestReturnedSolutionPredAccStats.addValue(score.predAcc);
bestReturnedSolutionMathCorrStats.addValue(score.mathCorr);
logger.info(score.toString());
// find the extensionally best matching tree in the list
Pair<EvaluatedRDFResourceTree, Score> bestMatchingTreeWithScore = findBestMatchingTreeFast(solutions, sparqlQuery, noise, examples);
EvaluatedRDFResourceTree bestMatchingTree = bestMatchingTreeWithScore.getFirst();
Score bestMatchingScore = bestMatchingTreeWithScore.getSecond();
// position of best tree in list of solutions
int positionBestScore = solutions.indexOf(bestMatchingTree);
bestSolutionPositionStats.addValue(positionBestScore);
Score bestScore = score;
if (positionBestScore > 0) {
logger.info("Position of best covering tree in list: " + positionBestScore);
logger.info("Best covering solution:\n" + render(bestMatchingTree.asEvaluatedDescription()));
logger.info("Tree score: " + bestMatchingTree.getTreeScore());
bestScore = bestMatchingScore;
logger.info(bestMatchingScore.toString());
} else {
logger.info("Best returned solution was also the best covering solution.");
}
bestSolutionRecallStats.addValue(bestScore.recall);
bestSolutionPrecisionStats.addValue(bestScore.precision);
bestSolutionFMeasureStats.addValue(bestScore.fmeasure);
bestSolutionPredAccStats.addValue(bestScore.predAcc);
bestSolutionMathCorrStats.addValue(bestScore.mathCorr);
for (RDFResourceTree negTree : examples.negExamplesMapping.values()) {
if (QueryTreeUtils.isSubsumedBy(negTree, bestMatchingTree.getTree())) {
Files.append(sparqlQuery + "\n", new File("/tmp/negCovered.txt"), Charsets.UTF_8);
break;
}
}
String bestQuery = QueryFactory.create(QueryTreeUtils.toSPARQLQueryString(
filter.apply(bestMatchingTree.getTree()),
dataset.getBaseIRI(), dataset.getPrefixMapping())).toString();
if (write2DB) {
write2DB(sparqlQuery, nrOfExamples, examples, noise,
baseLineQuery, baselineScore,
heuristicName, measureName,
QueryFactory.create(learnedSPARQLQuery).toString(), score, runtimeBestSolution,
bestQuery, positionBestScore, bestScore);
}
} catch (Exception e) {
failed.set(true);
logger.error("Error occured for query\n" + sparqlQuery, e);
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
Files.append(sparqlQuery + "\n" + sw.toString(), new File(benchmarkDirectory, "failed-" + nrOfExamples + "-" + noise + "-" + heuristicName + "-" + measureName + ".txt"), Charsets.UTF_8);
} catch (IOException e1) {
e1.printStackTrace();
}
} finally {
int cnt = currentNrOfFinishedRuns.incrementAndGet();
logger.info("***********Evaluation Progress:"
+ NumberFormat.getPercentInstance().format((double) cnt / totalNrOfQTLRuns)
+ "(" + cnt + "/" + totalNrOfQTLRuns + ")"
+ "***********");
}
}
});
}
tp.shutdown();
tp.awaitTermination(12, TimeUnit.HOURS);
Logger.getRootLogger().removeAppender(appender);
if(!failed.get()) {
String result = "";
result += "\nBaseline Precision:\n" + baselinePrecisionStats;
result += "\nBaseline Recall:\n" + baselineRecallStats;
result += "\nBaseline F-measure:\n" + baselineFMeasureStats;
result += "\nBaseline PredAcc:\n" + baselinePredAccStats;
result += "\nBaseline MathCorr:\n" + baselineMathCorrStats;
result += "#Returned solutions:\n" + nrOfReturnedSolutionsStats;
result += "\nOverall Precision:\n" + bestReturnedSolutionPrecisionStats;
result += "\nOverall Recall:\n" + bestReturnedSolutionRecallStats;
result += "\nOverall F-measure:\n" + bestReturnedSolutionFMeasureStats;
result += "\nOverall PredAcc:\n" + bestReturnedSolutionPredAccStats;
result += "\nOverall MathCorr:\n" + bestReturnedSolutionMathCorrStats;
result += "\nTime until best returned solution found:\n" + bestReturnedSolutionRuntimeStats;
result += "\nPositions of best solution:\n" + Arrays.toString(bestSolutionPositionStats.getValues());
result += "\nPosition of best solution stats:\n" + bestSolutionPositionStats;
result += "\nOverall Precision of best solution:\n" + bestSolutionPrecisionStats;
result += "\nOverall Recall of best solution:\n" + bestSolutionRecallStats;
result += "\nOverall F-measure of best solution:\n" + bestSolutionFMeasureStats;
result += "\nCBD generation time(total):\t" + MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).getTotal() + "\n";
result += "CBD generation time(avg):\t" + MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).getAvg() + "\n";
result += "Tree generation time(total):\t" + MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).getTotal() + "\n";
result += "Tree generation time(avg):\t" + MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).getAvg() + "\n";
result += "Tree size(avg):\t" + treeSizeStats.getMean() + "\n";
logger.info(result);
try {
Files.write(result, statsFile, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
data[i][j] = bestReturnedSolutionFMeasureStats.getMean();
if(write2DB) {
write2DB(heuristicName, measureName, nrOfExamples, noise,
bestReturnedSolutionFMeasureStats.getMean(),
bestReturnedSolutionPrecisionStats.getMean(),
bestReturnedSolutionRecallStats.getMean(),
bestReturnedSolutionPredAccStats.getMean(),
bestReturnedSolutionMathCorrStats.getMean(),
bestSolutionPositionStats.getMean(),
bestSolutionFMeasureStats.getMean(),
bestSolutionPrecisionStats.getMean(),
bestSolutionRecallStats.getMean(),
bestSolutionPredAccStats.getMean(),
bestSolutionMathCorrStats.getMean(),
baselineFMeasureStats.getMean(),
baselinePrecisionStats.getMean(),
baselineRecallStats.getMean(),
baselinePredAccStats.getMean(),
baselineMathCorrStats.getMean(),
bestReturnedSolutionRuntimeStats.getMean()
);
}
}
}
}
String content = "###";
String separator = "\t";
for (double noiseInterval1 : noiseIntervals) {
content += separator + noiseInterval1;
}
content += "\n";
for(int i = 0; i < nrOfExamplesIntervals.length; i++) {
content += nrOfExamplesIntervals[i];
for(int j = 0; j < noiseIntervals.length; j++) {
content += separator + data[i][j];
}
content += "\n";
}
File examplesVsNoise = new File(benchmarkDirectory, "examplesVsNoise-" + heuristicName + "-" + measureName + ".tsv");
try {
Files.write(content, examplesVsNoise, Charsets.UTF_8);
} catch (IOException e) {
logger.error("failed to write stats to file", e);
}
}
}
if(write2DB) {
conn.close();
}
if(useEmailNotification) {
sendFinishedMail();
}
long t2 = System.currentTimeMillis();
long duration = t2 - t1;
logger.info("QTL evaluation finished in " + DurationFormatUtils.formatDurationHMS(duration) + "ms.");
}
private ExamplesWrapper getExamples(String query, int maxNrOfPosExamples, int maxNrOfNegExamples, double noise, CBDStructureTree cbdStructure) {
return query2Examples
.get(query)
.get(maxNrOfPosExamples, maxNrOfNegExamples, noise, cbdStructure);
}
private String render(EvaluatedDescription ed) {
return owlRenderer.render(ed.getDescription()) + dfPercent.format(ed.getAccuracy());
}
private void sendFinishedMail() throws EmailException, IOException {
Properties config = new Properties();
config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("org/dllearner/algorithms/qtl/qtl-mail.properties"));
Email email = new SimpleEmail();
email.setHostName(config.getProperty("hostname"));
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(config.getProperty("username"), config.getProperty("password")));
email.setSSLOnConnect(true);
email.setFrom(config.getProperty("from"));
email.setSubject("QTL evaluation finished.");
email.setMsg("QTL evaluation finished.");
email.addTo(config.getProperty("to"));
email.send();
}
/*
* Compute a baseline solution.
*
* From simple to more complex:
*
* 1. random type
* 2. most popular type in KB
* 3. most frequent type in pos. examples
* 4. most informative edge, e.g. based on information gain
* 5. LGG of all pos. examples
*
*/
private RDFResourceTree applyBaseLine(ExamplesWrapper examples, Baseline baselineApproach) {
logger.info("Computing baseline...");
Collection<RDFResourceTree> posExamples = examples.posExamplesMapping.values();
Collection<RDFResourceTree> negExamples = examples.negExamplesMapping.values();
RDFResourceTree solution = null;
switch (baselineApproach) {
case RANDOM:// 1.
String query = "SELECT ?cls WHERE {?cls a owl:Class .} ORDER BY RAND() LIMIT 1";
QueryExecution qe = qef.createQueryExecution(query);
ResultSet rs = qe.execSelect();
if(rs.hasNext()) {
QuerySolution qs = rs.next();
Resource cls = qs.getResource("cls");
solution = new RDFResourceTree();
solution.addChild(new RDFResourceTree(cls.asNode()), RDF.type.asNode());
}
break;
case MOST_POPULAR_TYPE_IN_KB:// 2.
query = "SELECT ?cls WHERE {?cls a owl:Class . ?s a ?cls .} ORDER BY DESC(COUNT(?s)) LIMIT 1";
qe = qef.createQueryExecution(query);
rs = qe.execSelect();
if(rs.hasNext()) {
QuerySolution qs = rs.next();
Resource cls = qs.getResource("cls");
solution = new RDFResourceTree();
solution.addChild(new RDFResourceTree(cls.asNode()), RDF.type.asNode());
}
break;
case MOST_FREQUENT_TYPE_IN_EXAMPLES:// 3.
Multiset<Node> types = HashMultiset.create();
for (RDFResourceTree ex : posExamples) {
List<RDFResourceTree> children = ex.getChildren(RDF.type.asNode());
for (RDFResourceTree child : children) {
types.add(child.getData());
}
}
Node mostFrequentType = Ordering.natural().onResultOf(new Function<Multiset.Entry<Node>, Integer>() {
@Override
public Integer apply(Multiset.Entry<Node> entry) {
return entry.getCount();
}
}).max(types.entrySet()).getElement();
solution = new RDFResourceTree();
solution.addChild(new RDFResourceTree(mostFrequentType), RDF.type.asNode());
break;
case MOST_FREQUENT_EDGE_IN_EXAMPLES:// 4.
Multiset<Pair<Node, Node>> pairs = HashMultiset.create();
for (RDFResourceTree ex : posExamples) {
SortedSet<Node> edges = ex.getEdges();
for (Node edge : edges) {
List<RDFResourceTree> children = ex.getChildren(edge);
for (RDFResourceTree child : children) {
pairs.add(new Pair<>(edge, child.getData()));
}
}
}
Pair<Node, Node> mostFrequentPair = Ordering.natural().onResultOf(new Function<Multiset.Entry<Pair<Node, Node>>, Integer>() {
@Override
public Integer apply(Multiset.Entry<Pair<Node, Node>> entry) {
return entry.getCount();
}
}).max(pairs.entrySet()).getElement();
solution = new RDFResourceTree();
solution.addChild(new RDFResourceTree(mostFrequentPair.getValue()), mostFrequentPair.getKey());
break;
case MOST_INFORMATIVE_EDGE_IN_EXAMPLES:
// get all p-o in pos examples
Multiset<Pair<Node, Node>> edgeObjectPairs = HashMultiset.create();
for (RDFResourceTree ex : posExamples) {
SortedSet<Node> edges = ex.getEdges();
for (Node edge : edges) {
List<RDFResourceTree> children = ex.getChildren(edge);
for (RDFResourceTree child : children) {
edgeObjectPairs.add(new Pair<>(edge, child.getData()));
}
}
}
double bestAccuracy = -1;
solution = new RDFResourceTree();
for (Pair<Node, Node> pair : edgeObjectPairs.elementSet()) {
Node edge = pair.getKey();
Node childValue = pair.getValue();
// compute accuracy
int tp = edgeObjectPairs.count(pair);
int fn = posExamples.size() - tp;
int fp = 0;
for (RDFResourceTree ex : negExamples) { // compute false positives
List<RDFResourceTree> children = ex.getChildren(edge);
if(children != null) {
for (RDFResourceTree child : children) {
if(child.getData().equals(childValue)) {
fp++;
break;
}
}
}
}
int tn = negExamples.size() - fp;
double accuracy = Heuristics.getPredictiveAccuracy(
posExamples.size(),
negExamples.size(),
tp,
tn,
1.0);
// update best solution
if(accuracy >= bestAccuracy) {
solution = new RDFResourceTree();
solution.addChild(new RDFResourceTree(childValue), edge);