-
Notifications
You must be signed in to change notification settings - Fork 0
/
FactWindow.java
1130 lines (1016 loc) · 48.9 KB
/
FactWindow.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 2018–2022 University of Tübingen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.tuebingen.sfs.psl.gui;
import de.tuebingen.sfs.psl.engine.PslProblem;
import de.tuebingen.sfs.psl.engine.RuleAtomGraph;
import de.tuebingen.sfs.psl.talk.ConstantRenderer;
import de.tuebingen.sfs.psl.talk.rule.TalkingConstraint;
import de.tuebingen.sfs.psl.talk.pred.TalkingPredicate;
import de.tuebingen.sfs.psl.talk.rule.TalkingRuleOrConstraint;
import de.tuebingen.sfs.psl.util.color.ColorUtils;
import de.tuebingen.sfs.psl.util.color.HslColor;
import de.tuebingen.sfs.psl.util.data.RankingEntry;
import de.tuebingen.sfs.psl.util.data.Tuple;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Orientation;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
import org.h2.util.StringUtils;
import org.linqs.psl.model.rule.GroundRule;
import org.linqs.psl.model.rule.Rule;
import java.awt.*;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class FactWindow {
protected static final Pattern ATOM_START_PATTERN = Pattern.compile("\\w{4,}\\(");
protected static final String PERCENTAGE_FORMAT = "%.0f %%";
// Display choices
protected boolean showOnlyRagAtoms;
protected boolean showRuleVerbalization = true;
protected Set<String> ragAtoms;
protected Set<String> scoreMapAtoms;
protected Set<String> unusedAtoms;
protected Set<String> uninterestingAtoms;
protected boolean reloadingSidebar = false;
protected PslProblem pslProblem;
protected Map<Rule, String> ruleToName = new HashMap<>();
protected Map<String, TalkingPredicate> talkingPreds;
protected Map<String, TalkingRuleOrConstraint> talkingRules;
@FXML
protected HBox detailBox; // used by EtinenFactWindow
@FXML
protected Button back;
@FXML
protected Button fwrd;
@FXML
protected TextFlow atomTitle;
@FXML
protected TextFlow atomVerbalizationPane;
@FXML
protected VBox whyNotBox;
@FXML
protected ScrollPane whyNotScrollPane;
@FXML
protected VBox whyBox;
@FXML
protected ScrollPane whyScrollPane;
@FXML
protected Label beliefValueLabel;
@FXML
protected Label sortLabel;
@FXML
protected CheckMenuItem unusedAtomsChoice;
@FXML
protected CheckMenuItem internalRuleRepChoice;
@FXML
protected CheckMenuItem distToSatisfactionChoice;
@FXML
protected CheckMenuItem counterfactualChoice;
// JavaFX
protected Text atomText;
protected VBox container;
protected Stage stage;
protected Stage selectedItemStage;
protected ScrollPane scrollAtomPane;
@FXML
protected ListView<String> displayedAtomsListView;
@FXML
protected GridPane atomFilter;
// Observables
protected ObservableList<String> displayedAtoms;
protected StringProperty currentAtom = new SimpleStringProperty();
protected DoubleProperty currentScore = new SimpleDoubleProperty(-1.0);
protected RuleAtomGraph graph;
// Java variables
protected Stack<String> nextAtoms;
protected Stack<String> previousAtoms;
protected boolean presortSidebar;
protected boolean displayDistToSatisfaction = true;
protected boolean displayCounterfactual;
protected boolean printPaneContentsToConsole;
// Maps for atom elements
protected Map<String, Double> scoreMap;
protected Map<String, String> atomToPredicate;
protected Map<String, List<String>> atomToDisplayArguments;
// For correctly displaying EtinenTalkingRules/Predicates.
protected ConstantRenderer constantRenderer;
protected Map<String, String> encodedAtomToSurface = new HashMap<>();
protected Map<String, String> surfaceAtomToEncoded = new HashMap<>();
protected FactWindow() {
// For subclasses.
}
public FactWindow(PslProblem pslProblem, RuleAtomGraph graph, Map<String, Double> scoreMap) {
this(pslProblem, graph, scoreMap, true);
}
public FactWindow(PslProblem pslProblem, RuleAtomGraph graph, Map<String, Double> scoreMap,
boolean showOnlyRagAtoms) {
this(null, pslProblem, null, graph, scoreMap, null, null, null, null, showOnlyRagAtoms);
}
public FactWindow(ConstantRenderer renderer, RuleAtomGraph rag, Map<String, TalkingPredicate> talkingPreds,
Map<String, TalkingRuleOrConstraint> talkingRules, Map<String, Double> result,
boolean presortSidebar, boolean printPaneContentsToConsole) {
this(renderer, null, null, rag, result, talkingPreds, talkingRules, presortSidebar, printPaneContentsToConsole,
null);
}
// 2 options:
// - StandaloneFactViewer: pslProblem, graph, scoreMap
// - RagViewer: graph, scoreMap, talkingPreds, talkingRules
protected FactWindow(ConstantRenderer constantRenderer, PslProblem pslProblem, String atomName, RuleAtomGraph graph,
Map<String, Double> scoreMap, Map<String, TalkingPredicate> talkingPreds,
Map<String, TalkingRuleOrConstraint> talkingRules, Boolean presortSidebar,
Boolean printPaneContentsToConsole, Boolean showOnlyRagAtoms) {
this.pslProblem = pslProblem; // Can be null.
this.graph = graph;
this.scoreMap = scoreMap;
if (atomName == null) atomName = "";
atomToPredicate = null;
if (pslProblem == null) {
this.talkingPreds = talkingPreds;
this.talkingRules = talkingRules;
} else {
this.talkingPreds = pslProblem.getTalkingPredicates();
this.talkingRules = pslProblem.getTalkingRules();
for (TalkingRuleOrConstraint rule : this.talkingRules.values()) {
ruleToName.put(rule.getRule(), rule.getName());
}
}
System.err.println(this.talkingPreds);
this.presortSidebar = presortSidebar != null && presortSidebar;
this.printPaneContentsToConsole = printPaneContentsToConsole != null && printPaneContentsToConsole;
this.showOnlyRagAtoms = showOnlyRagAtoms == null || showOnlyRagAtoms;
updateAtoms();
setRenderer(constantRenderer); // Can be null.
setCurrentAtom(atomName);
}
public static double getToneForAtom(String atomRepresentation, Map<String, Double> scoreMap) {
// System.err.println("getToneForAtom(" + atomRepresentation + ")");
if (scoreMap == null) return 0.0;
else {
Double alpha = scoreMap.get(atomRepresentation);
if (alpha == null) return 0.0;
if (alpha >= 0 && alpha <= 1) return 1.0 - alpha;
return alpha;
}
}
// MorphView: Copy this method.
public static String getBackgroundColorForScore(HslColor baseColor, Map<String, Double> scoreMap, String atom) {
double toneForAtom = getToneForAtom(atom, scoreMap);
return getBackgroundColorForScore(baseColor, toneForAtom);
}
public static String getBackgroundColorForScore(HslColor baseColor, double toneForAtom) {
if (toneForAtom == Double.POSITIVE_INFINITY) {
return "#000000";
} else if (toneForAtom == 2.0) {
return "#006400";
} else if (toneForAtom == -1.0) {
return "#ff8c00";
} else if (toneForAtom == Double.NEGATIVE_INFINITY) {
return "#ffffff";
} else {
Color resultColor = baseColor.adjustLuminance(
baseColor.getLuminance() + (float) (toneForAtom * (100 - baseColor.getLuminance())));
return ColorUtils.colorHTML(resultColor);
}
}
protected void updateAtoms() {
ragAtoms = graph.getAtomNodes();
scoreMapAtoms = scoreMap.keySet();
unusedAtoms = new TreeSet<>();
unusedAtoms.addAll(scoreMapAtoms);
unusedAtoms.removeAll(ragAtoms);
unusedAtoms.addAll(graph.getRagFilter().getHiddenAtoms());
uninterestingAtoms = new TreeSet<>();
uninterestingAtoms.addAll(ragAtoms);
uninterestingAtoms.removeAll(scoreMapAtoms);
uninterestingAtoms.addAll(graph.getRagFilter().getHiddenAtoms());
}
public Set<String> setRenderer(ConstantRenderer constantRenderer) {
this.constantRenderer = constantRenderer;
atomToPredicate = new TreeMap<>();
atomToDisplayArguments = new TreeMap<>();
encodedAtomToSurface = new TreeMap<>();
surfaceAtomToEncoded = new TreeMap<>();
System.err.println("Start setting up the atom maps.");
Set<String> allAtoms = new TreeSet<>();
allAtoms.addAll(scoreMapAtoms);
allAtoms.addAll(ragAtoms);
if (constantRenderer == null) {
for (String atom : allAtoms) {
encodedAtomToSurface.put(atom, atom);
surfaceAtomToEncoded.put(atom, atom);
List<String> atomElems = getAtomElements(atom);
atomToPredicate.put(atom, atomElems.get(0));
atomToDisplayArguments.put(atom, atomElems.subList(1, atomElems.size()));
}
} else {
for (String atom : allAtoms) {
processAtom(atom);
}
}
System.err.println("DONE setting up the atom maps.");
return allAtoms;
}
protected void processAtom(String atom) {
List<String> atomElems = getAtomElements(atom);
TalkingPredicate pred = getTalkingPredicate(atomElems.get(0));
String surface = atom;
List<String> args = atomElems.subList(1, atomElems.size());
if (constantRenderer != null && pred != null) {
args = pred.retrieveArguments(constantRenderer, args.toArray(new String[atomElems.size() - 1]));
surface = atomElems.get(0) + "(" + String.join(", ", args) + ")";
}
encodedAtomToSurface.put(atom, surface);
surfaceAtomToEncoded.put(surface, atom);
atomToPredicate.put(atom, atomElems.get(0));
atomToDisplayArguments.put(atom, args);
}
public void update(String atom) {
update(atom, false);
}
public void update(String atom, boolean forceUpdate) {
setCurrentAtom(atom);
updateInfo();
}
public void updateInfo() {
ScoreService scoreService = new ScoreService();
scoreService.start();
}
public FactWindow getWindow() {
return this;
}
@FXML
public void initialize() {
update(currentAtom.get());
scrollAtomPane = new ScrollPane();
scrollAtomPane.setPannable(true);
scrollAtomPane.setFitToWidth(true);
beliefValueLabel.setFont(Font.font("Verdana", FontWeight.BOLD, 14));
atomText = updateAtomText(new Text());
// tf.getChildren().add(atomText);
// atomVerbalizationPane.getChildren().add(atomText);
// onFormSelection(currentAtom.get());
// Display options in the MenuBar
unusedAtomsChoice.setSelected(!showOnlyRagAtoms);
unusedAtomsChoice.setOnAction((ActionEvent event) -> {
showOnlyRagAtoms = !unusedAtomsChoice.isSelected();
reloadingSidebar = true;
updateInfo();
reloadingSidebar = false;
});
internalRuleRepChoice.setSelected(false);
internalRuleRepChoice.setOnAction((ActionEvent event) -> {
showRuleVerbalization = !internalRuleRepChoice.isSelected();
setFacts(graph);
});
distToSatisfactionChoice.setSelected(true);
distToSatisfactionChoice.setOnAction((ActionEvent event) -> {
displayDistToSatisfaction = distToSatisfactionChoice.isSelected();
setFacts(graph);
});
counterfactualChoice.setSelected(false);
counterfactualChoice.setOnAction((ActionEvent event) -> {
displayCounterfactual = counterfactualChoice.isSelected();
setFacts(graph);
});
previousAtoms = new Stack<>();
back.setMaxWidth(Double.MAX_VALUE);
back.setOnAction(event -> {
if (!previousAtoms.empty()) {
nextAtoms.push(currentAtom.get());
onFormSelection(previousAtoms.pop(), false);
}
});
nextAtoms = new Stack<>();
fwrd.setMaxWidth(Double.MAX_VALUE);
fwrd.setOnAction(event -> {
if (!nextAtoms.empty()) {
previousAtoms.push(currentAtom.get());
onFormSelection(nextAtoms.pop(), false);
}
});
// Set various display possibilities for atom belief
beliefValueLabel.textProperty().bind(Bindings.when(currentAtom.isEmpty()).then("").otherwise(
Bindings.when(currentScore.greaterThan(1.0)).then("+").otherwise(
Bindings.when(currentScore.lessThan(0.0)).then("-").otherwise(
Bindings.format(Locale.ENGLISH, PERCENTAGE_FORMAT, currentScore.multiply(100))))));
}
public void setStage(Stage stage) {
this.stage = stage;
}
protected TalkingPredicate getTalkingPredicate(String predicateName) {
String encoded = getInternalForm(predicateName);
if (pslProblem != null) return pslProblem.getTalkingPredicates().get(encoded);
return talkingPreds.get(encoded);
}
protected Pair<TalkingPredicate, String[]> getTalkingPredicateWithArgs(String atom) {
String[] parts = surfaceAtomToEncoded.getOrDefault(atom, atom).split("\\(");
String[] args = parts[1].substring(0, parts[1].length() - 1).split(",\\s?");
return new Pair<>(getTalkingPredicate(parts[0]), args);
}
protected Map<String, TalkingRuleOrConstraint> getTalkingRules() {
if (pslProblem != null) return pslProblem.getTalkingRules();
return talkingRules;
}
protected List<String> getAtomElements(String atomString) {
String[] elems = atomString.split("\\(");
String[] args = elems[1].substring(0, elems[1].length() - 1).split(", ");
List<String> atomElems = new ArrayList<>(args.length + 1);
atomElems.add(elems[0]);
atomElems.addAll(Arrays.asList(args));
return atomElems;
}
// Switch to the form of the atom that should be displayed to the user
// (Based on the EtinenConstantRenderer)
protected String getDisplayForm(String atom) {
return encodedAtomToSurface.getOrDefault(atom, atom);
}
// To be sure you're using the correct version of an atom string,
// use the following methods to interact with some of the instance variables.
// Switch to the internally encoded form of the atom (with
// IndexedObjectStore-encoded arguments).
// Use this when interacting with any of the atom-based maps (or use the
// dedicated functions below)
// and when using Actions/Events or when passing atom information to the
// GuiPresenter.
protected String getInternalForm(String atom) {
return surfaceAtomToEncoded.getOrDefault(atom, atom);
}
protected void setCurrentAtom(String atom) {
if (atom == null || atom.isEmpty()) currentAtom.set("");
else currentAtom.set(getDisplayForm(atom));
}
protected Double getScore(String atom) {
Double score = scoreMap.get(getInternalForm(atom));
if (score == null)
// Non-persisted atom
score = graph.getValue(atom);
return score;
}
protected List<String> getDisplayArguments(String atom) {
List<String> args = atomToDisplayArguments.get(getInternalForm(atom));
if (args == null) {
processAtom(atom);
args = atomToDisplayArguments.get(getInternalForm(atom));
System.err.println("Encountered new atom " + atom +
" and updated the atom maps accordingly. (This should not have happened.)");
}
return args;
}
protected String getPredicate(String atom) {
String pred = atomToPredicate.get(getInternalForm(atom));
if (pred == null) {
processAtom(atom);
pred = atomToPredicate.get(getInternalForm(atom));
System.err.println("Encountered new atom " + atom +
" and updated the atom maps accordingly. (This should not have happened.)");
}
return pred;
}
protected Text updateAtomText(Text atomText) {
atomText.textProperty().bind(currentAtom);
// atomText.setFont(Font.font("Verdana", FontWeight.NORMAL, 14));
atomText.setStyle("-fx-font-style: italic");
atomText.setStyle("-fx-font: 20 arial");
return atomText;
}
public void setFacts(RuleAtomGraph rag) {
whyBox.getChildren().clear();
whyNotBox.getChildren().clear();
List<String> notUnderPressureList = new ArrayList<>();
for (RankingEntry<String> s : rag.rankGroundingsByPressure(Double.NEGATIVE_INFINITY)) {
notUnderPressureList.add(s.key);
}
String currentAtom = getInternalForm(this.currentAtom.get());
List<Explanation> whyRules = new ArrayList<>();
List<Explanation> whyNotRules = new ArrayList<>();
// If the atom's value wasn't inferred, we can hardcode the explanation:
boolean canHaveWhyInfluence = true;
boolean canHaveWhyNotInfluence = true;
if (graph.isFixed(currentAtom)) {
canHaveWhyInfluence = false;
canHaveWhyNotInfluence = false;
whyRules.add(Explanation.createFixedExplanation("The value of this atom was fixed before the inference."));
whyNotRules.add(
Explanation.createFixedExplanation("The value of this atom was fixed before the inference."));
} else if (Math.abs(currentScore.get()) < RuleAtomGraph.DISSATISFACTION_PRECISION) {
canHaveWhyInfluence = false;
whyRules.add(Explanation.createFixedExplanation("This atom has taken the lowest value it can take."));
} else if (Math.abs(currentScore.get() - 1) < RuleAtomGraph.DISSATISFACTION_PRECISION) {
canHaveWhyNotInfluence = false;
whyNotRules.add(Explanation.createFixedExplanation("This atom has taken the highest value it can take."));
}
for (Tuple tup : rag.getOutgoingLinks(currentAtom)) {
String rule = tup.get(1);
if (notUnderPressureList.contains(rule)) {
String ruleName = rule.substring(0, rule.indexOf('['));
List<Tuple> atomToStatus = rag.getLinkedAtomsForGroundingWithLinkStatusAsList(rule);
String[] groundAtoms = new String[atomToStatus.size()];
int currentAtomIndex = -1;
for (int i = 0; i < groundAtoms.length; i++) {
groundAtoms[i] = atomToStatus.get(i).get(0);
if (groundAtoms[i].equals(currentAtom)) currentAtomIndex = i;
}
String status = atomToStatus.get(currentAtomIndex).get(1);
if (rag.isEqualityRule(rule) || status.equals("+")) {
whyRules.add(
generateWeightedExplanation(ruleName, rule, currentAtom, rag, true, canHaveWhyInfluence));
}
if (rag.isEqualityRule(rule) || status.equals("-")) {
whyNotRules.add(generateWeightedExplanation(ruleName, rule, currentAtom, rag, false,
canHaveWhyNotInfluence));
}
}
}
if (printPaneContentsToConsole) {
if (currentAtom.isEmpty()) {
System.out.println("[Empty atom.]");
} else {
System.out.println("Atom: " + getPredicate(currentAtom) + getDisplayArguments(currentAtom));
}
System.out.println("WHY ? (WHY NOT LESS LIKELY / Rules pushing belief upwards)");
}
setExplanationBox(whyRules, whyBox);
if (printPaneContentsToConsole) {
System.out.println("WHY NOT ? (WHY NOT MORE LIKELY / Rules pushing belief downwards)");
}
setExplanationBox(whyNotRules, whyNotBox);
if (printPaneContentsToConsole) {
System.out.println("---------\n");
}
}
protected Explanation generateWeightedExplanation(String ruleName, String groundingName, String contextAtom,
RuleAtomGraph rag, boolean whyExplanation,
boolean canHaveInfluence) {
String text = generateExplanation(talkingRules, ruleName, groundingName, contextAtom, rag, whyExplanation);
double dist = rag.distanceToSatisfaction(groundingName);
boolean active = canHaveInfluence && rag.putsPressureOnGrounding(contextAtom, groundingName);
Explanation expl;
if (talkingRules.get(ruleName) instanceof TalkingConstraint) {
expl = Explanation.createConstraintExplanation(text, dist, active);
} else {
expl = Explanation.createRuleExplanation(text, dist, active);
}
double score = scoreMap.get(contextAtom);
if (!(Math.abs(score - 1.0) < RuleAtomGraph.DISSATISFACTION_PRECISION && !whyExplanation) &&
!(Math.abs(score) < RuleAtomGraph.DISSATISFACTION_PRECISION && whyExplanation)) {
Double counterfactualDist = graph.getCounterfactual(contextAtom, groundingName);
if (displayCounterfactual && (score > 0.0 || score < 1.0)) {
if (counterfactualDist == null) {
double[] counterfactualDistances = rag.getCounterfactualsForEqualityRule(contextAtom,
groundingName);
if (whyExplanation) {
generateCounterfactualExplanation(expl, counterfactualDistances[0], dist,
score - RuleAtomGraph.COUNTERFACTUAL_OFFSET, contextAtom);
} else {
generateCounterfactualExplanation(expl, counterfactualDistances[1], dist,
score + RuleAtomGraph.COUNTERFACTUAL_OFFSET, contextAtom);
}
} else {
double counterfactualAtomVal =
score + (whyExplanation ? -1.0 : 1.0) * RuleAtomGraph.COUNTERFACTUAL_OFFSET;
generateCounterfactualExplanation(expl, counterfactualDist, dist, counterfactualAtomVal,
contextAtom);
}
}
}
return expl;
}
protected void generateCounterfactualExplanation(Explanation expl, double counterfactualDist, double dist,
double counterfactualAtomVal, String contextAtom) {
expl.setCounterfactualDissatisfaction(counterfactualDist);
StringBuilder sb = new StringBuilder("\n");
if (showRuleVerbalization) {
Pair<TalkingPredicate, String[]> predAndArgs = getTalkingPredicateWithArgs(contextAtom);
sb.append("If ").append(predAndArgs.first.verbalizeIdeaAsNP(constantRenderer, predAndArgs.second));
sb.append(" had had a value of ");
sb.append(formatAsPercentage(counterfactualAtomVal));
sb.append(", then the distance to satisfaction would have ");
if (expl.counterfactualIsDissatisfied()) {
sb.append("been ").append(expl.getDisplayableCounterfactualDissatisfaction()).append(".");
} else {
sb.append("stayed at 0.");
}
} else {
sb.append(" ").append(expl.getDisplayableCounterfactualDissatisfaction());
sb.append(": if value were ");
sb.append(formatValue(counterfactualAtomVal));
}
expl.setText(expl.getText() + sb.toString());
}
protected String getNameForRule(Rule rule) {
if (pslProblem != null) return pslProblem.getNameForRule(rule);
return ruleToName.getOrDefault(rule, "<missing rule name>");
}
protected String generateExplanation(Map<String, TalkingRuleOrConstraint> talkingRules, String ruleName,
String groundingName, String contextAtom, RuleAtomGraph rag,
boolean whyExplanation) {
if (!showRuleVerbalization) {
StringBuilder sb = new StringBuilder();
GroundRule rule = graph.getRuleForGrounding(groundingName);
sb.append(getNameForRule(rule.getRule()));
String ruleStr = rule.toString().replaceAll("', '", "','").strip();
if (ruleStr.endsWith(")")) {
String[] weightAndRule = ruleStr.substring(0, ruleStr.length() - 1).split("\\(", 2);
sb.append(" (×").append(weightAndRule[0].replace(":", "").strip()).append(")");
ruleStr = weightAndRule[1];
}
sb.append(": ");
boolean prevWasOpeningQuote = false;
for (String element : ruleStr.split("\\s+")) {
Matcher matcher = ATOM_START_PATTERN.matcher(element);
if (matcher.find()) {
element = element.replaceAll("','", "', '");
String pred = TalkingPredicate.getPredNameFromAllCaps(element.split("\\(")[0]);
String[] argsWithApostrophe = TalkingPredicate.extractArgs(element);
String[] args = new String[argsWithApostrophe.length];
for (int i = 0; i < args.length; i++) {
args[i] = argsWithApostrophe[i].substring(1, argsWithApostrophe[i].length() - 1);
}
String atom = pred + "(" + de.tuebingen.sfs.psl.util.data.StringUtils.join(args, ", ") + ")";
sb.append("\\url[").append(getDisplayForm(atom)).append("]{");
sb.append(atom).append("} [");
Double belief = scoreMap.get(atom);
if (belief == null) {
sb.append("???");
} else {
sb.append(formatValue(belief));
}
sb.append("]");
} else {
sb.append(element);
prevWasOpeningQuote = element.endsWith("(");
}
if (!prevWasOpeningQuote) {
sb.append(" ");
}
}
if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
return talkingRules.get(ruleName)
.generateExplanation(constantRenderer, groundingName, contextAtom, rag, whyExplanation);
}
protected void setExplanationBox(List<Explanation> entries, VBox vbox) {
vbox.getChildren().clear();
Collections.sort(entries);
for (Explanation entry : entries) {
String explanation = entry.getText();
// explanation = entry.getSummary() + explanation;
if (displayDistToSatisfaction && !entry.isFixed() && entry.isDissatisfied()) {
explanation = entry.getDisplayableDissatisfaction() + " " + explanation;
}
if (entry.isConstraint()) {
explanation = "⬛ " + explanation;
} else if (!entry.isFixed()) {
explanation = "⬜ " + explanation;
}
TextFlow textFlow = new TextFlow();
AtomVerbalizationRenderer.fillTextFlow(explanation, textFlow, FactWindow.this);
textFlow.prefWidthProperty().bind(whyNotScrollPane.widthProperty().subtract(40));
ContextMenu menu = new ContextMenu();
MenuItem copyItem = new MenuItem("Copy explanation to clipboard");
menu.getItems().add(copyItem);
final String finalExplanation = explanation;
copyItem.setOnAction((ActionEvent e) -> {
final Clipboard clipboard = Clipboard.getSystemClipboard();
final ClipboardContent content = new ClipboardContent();
content.putString(finalExplanation);
clipboard.setContent(content);
});
textFlow.setOnContextMenuRequested(event -> menu.show(textFlow, event.getScreenX(), event.getScreenY()));
if (!entry.isActive()) {
textFlow.setOpacity(0.6);
}
vbox.getChildren().add(textFlow);
// Add a horizontal line as separator
final Separator separator = new Separator(Orientation.HORIZONTAL);
separator.prefWidthProperty().bind(textFlow.widthProperty());
vbox.getChildren().add(separator);
if (printPaneContentsToConsole) {
System.out.println(explanation);
}
}
// Remove the last separator
int nChildren = vbox.getChildren().size();
if (nChildren > 1) {
vbox.getChildren().remove(nChildren - 1, nChildren);
}
}
/**
* A method for opening CogsetWindow on the form selection
*/
public void onFormSelection(String atomString) {
onFormSelection(atomString, true);
}
public String onFormSelection(String atomString, boolean addToHistory) {
if (addToHistory) {
previousAtoms.push(currentAtom.get());
nextAtoms.clear();
}
String internalForm = getInternalForm(atomString);
setCurrentAtom(getDisplayForm(atomString));
Double score = getScore(currentAtom.get());
currentScore.setValue(score);
String pred = getPredicate(internalForm);
TalkingPredicate tPred = getTalkingPredicate(pred);
String verbalization = verbalizeAtom(tPred, internalForm, score);
atomVerbalizationPane.getChildren().clear();
AtomVerbalizationRenderer.fillTextFlow(verbalization, atomVerbalizationPane, this);
setFacts(graph);
return internalForm;
}
protected String verbalizeAtom(TalkingPredicate tPred, String internalForm, Double score) {
if (internalForm.isEmpty()) return "";
String verbalization;
if (constantRenderer == null) {
List<String> args = getDisplayArguments(internalForm);
verbalization = tPred.verbalizeIdeaAsSentence(null, score, args.toArray(new String[args.size()]));
} else {
List<String> args = getAtomElements(internalForm);
args = args.subList(1, args.size());
verbalization = tPred.verbalizeIdeaAsSentence(constantRenderer, score,
args.toArray(new String[args.size()]));
}
return verbalization.substring(0, 1).toUpperCase() + verbalization.substring(1) +
(verbalization.endsWith(".") ? "" : ".");
}
public static String formatValue(double value) {
return String.format(Locale.ENGLISH, "%.2f", value);
}
public static String formatAsPercentage(double value) {
return String.format(Locale.ENGLISH, PERCENTAGE_FORMAT, value * 100);
}
public static class ExitHandler implements EventHandler<ActionEvent> {
Stage stage;
public ExitHandler(Stage stage) {
this.stage = stage;
}
@Override
public void handle(ActionEvent arg0) {
stage.close();
}
}
public class GraphTask extends Task<RuleAtomGraph> {
@Override
protected RuleAtomGraph call() {
return getRag();
}
}
protected RuleAtomGraph getRag() {
return graph;
}
public class ScoreTask extends Task<Map<String, Double>> {
@Override
protected Map<String, Double> call() {
return getScoreMap();
}
}
protected Map<String, Double> getScoreMap() {
return scoreMap;
}
public class ScoreService extends javafx.concurrent.Service<Map<String, Double>> {
ScoreTask task;
int boxInd;
int ordinal;
public Task<Map<String, Double>> createTask() {
if (container != null) {
container.getChildren().clear();
}
sortLabel.setPrefWidth(Double.MAX_VALUE);
task = new ScoreTask();
ordinal = 0;
task.setOnSucceeded((WorkerStateEvent e) -> {
scoreMap = task.getValue();
displayedAtoms = FXCollections.observableArrayList();
if (!currentAtom.get().isEmpty()) {
onFormSelection(currentAtom.get(), false);
}
String firstSelected = "";
Set<String> sidebarAtoms = new TreeSet<>(ragAtoms);
sidebarAtoms.removeAll(uninterestingAtoms);
if (!showOnlyRagAtoms) sidebarAtoms.addAll(scoreMapAtoms);
for (String atom : sidebarAtoms) {
if (!graph.renderAtomInGui(atom)) {
continue;
}
atom = getDisplayForm(atom);
if (atom.equals(currentAtom.get())) {
firstSelected = atom;
}
displayedAtoms.add(atom);
}
if (reloadingSidebar) firstSelected = currentAtom.get();
// listView.setPrefHeight(Double.MAX_VALUE);
FilteredList<String> filteredData = new FilteredList<>(displayedAtoms, s -> true);
displayedAtomsListView.setItems(filteredData);
Text atomText = updateAtomText(new Text());
atomTitle.getChildren().clear();
atomTitle.getChildren().add(atomText);
if (!firstSelected.trim().isEmpty()) {
if (displayedAtoms.contains(firstSelected)) {
displayedAtomsListView.getSelectionModel().select(firstSelected);
displayedAtomsListView.scrollTo(firstSelected);
}
String encoded = getInternalForm(firstSelected);
TalkingPredicate tPred = getTalkingPredicate(getPredicate(encoded));
Double score = getScore(firstSelected);
String verbalization = verbalizeAtom(tPred, encoded, score);
atomVerbalizationPane.getChildren().clear();
atomVerbalizationPane.setStyle("-fx-padding: 3 0 0 0;");
AtomVerbalizationRenderer.fillTextFlow(verbalization, atomVerbalizationPane, getWindow());
}
// listView.set .setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// FOR the morpheme tabs, also copy the methods
displayedAtomsListView.setCellFactory(param -> new ListCell<>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
setStyle("-fx-background-color:white;");
} else {
if (displayedAtoms.contains(getDisplayForm(item))) {
String encoded = getInternalForm(item);
boolean deleted = isDeleted(encoded);
String backgroundColor;
if (!showOnlyRagAtoms && unusedAtoms.contains(encoded))
backgroundColor = "#bebebe"; // grey
else backgroundColor = getBackgroundColorForScore(
graph.atomToBaseColor(encoded, deleted), scoreMap, encoded);
setStyle("-fx-background-color:" + backgroundColor + ";");
getStyleClass().remove("white-font");
getStyleClass().add("black-font");
getStyleClass().add("lw-cell-no-border");
double belief = scoreMap.get(encoded);
if (deleted) {
getStyleClass().add("table-row-deleted");
} else if (belief > 1.0 || belief < 0.0) {
getStyleClass().remove("black-font");
getStyleClass().add("white-font");
}
String displayForm = getDisplayForm(item);
if (priorApplied(encoded)) displayForm = "(+) " + displayForm;
setText(displayForm);
Label fixedRep = new Label();
if (graph.isFixed(encoded)) {
fixedRep.setText("⚫");
fixedRep.setOpacity(0.4);
} else {
fixedRep.setText("⚪");
}
fixedRep.getStyleClass().add("black-font");
setGraphic(fixedRep);
}
}
}
@Override
public void updateSelected(boolean selected) {
super.updateSelected(selected);
if (selected) {
getStyleClass().remove("lw-cell-no-border");
getStyleClass().add("lw-cell-border");
} else {
getStyleClass().remove("lw-cell-border");
getStyleClass().add("lw-cell-no-border");
}
}
});
displayedAtomsListView.getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
if (selectedItemStage != null) {
selectedItemStage.close();
}
if (newValue != null) {
onFormSelection(newValue);
}
});
ImageView sortIcon = new ImageView(new Image(getClass().getResource("/sort.png").toExternalForm()));
ImageView sortIconUp = new ImageView(
new Image(getClass().getResource("/sort-up.png").toExternalForm()));
ImageView sortIconDown = new ImageView(
new Image(getClass().getResource("/sort-down.png").toExternalForm()));
Label arrow = new Label("");
arrow.setGraphic(sortIcon);
sortLabel.setText("");
sortLabel.setGraphic(arrow);
sortLabel.setContentDisplay(ContentDisplay.LEFT);
// Initial "not sorted" comparator
Comparator<String> nullComparator = Comparator.comparing(String::toString);
Comparator<String> comparator = Comparator.comparing(String::toString,
(f1, f2) -> getScore(f1).compareTo(getScore(f2)));
// Mouse events for clicking the sorting symbol
sortLabel.setOnMouseClicked((MouseEvent event) -> {
if (ordinal == 0) {
// change to ascending
displayedAtoms.sort(comparator);
ordinal = 1;
arrow.setGraphic(sortIconUp);
} else if (ordinal == 1) {
// change to descending
displayedAtoms.sort(comparator.reversed());
ordinal = 2;
arrow.setGraphic(sortIconDown);
} else {
// change to the initial state
displayedAtoms.sort(nullComparator);
arrow.setGraphic(sortIcon);
ordinal = 0;
}
});
if (presortSidebar) {
displayedAtoms.sort(comparator.reversed());
ordinal = 2;
arrow.setGraphic(sortIconDown);
}
// The (nested) list of options for specifying a predicate and its arguments.
atomFilter.getChildren().clear();
ColumnConstraints cc = new ColumnConstraints();
cc.setPercentWidth(100);
atomFilter.getColumnConstraints().add(cc);
// Initial set-up.
ComboBox<String> predNameBox = new ComboBox<>();
predNameBox.setPrefWidth(Double.MAX_VALUE);
SortedSet<String> sortedPredNames = displayedAtoms.stream().map(FactWindow.this::getPredicate).sorted()
.collect(Collectors.toCollection(TreeSet::new));
predNameBox.getItems().add(""); // default value
predNameBox.getItems().addAll(sortedPredNames);
// cb.setEditable(true);
atomFilter.add(predNameBox, 0, 0);
predNameBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
// Filter by predicate.
if (newValue == null || newValue.isEmpty()) {
filteredData.setPredicate(s -> true);
} else {
filteredData.setPredicate(s -> getPredicate(s).equals(newValue));
}
// If a predicate name has been selected,
// infer the number of args from the filtered list of atoms.
int argNum = 0;
if (!filteredData.isEmpty() && predNameBox.getSelectionModel().getSelectedItem() != null &&
!predNameBox.getSelectionModel().getSelectedItem().isEmpty()) {
argNum = getDisplayArguments(filteredData.get(0)).size();
}
// Add the predNameBox again.
atomFilter.getChildren().clear();
double percentages = 100.0 / (argNum + 1);