-
Notifications
You must be signed in to change notification settings - Fork 113
/
Grasp.java
343 lines (275 loc) · 11 KB
/
Grasp.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
package edu.cmu.tetrad.search;
import edu.cmu.tetrad.data.IKnowledge;
import edu.cmu.tetrad.data.Knowledge2;
import edu.cmu.tetrad.graph.Graph;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.util.NumberFormatUtil;
import edu.cmu.tetrad.util.TetradLogger;
import org.jetbrains.annotations.NotNull;
import java.text.NumberFormat;
import java.util.*;
import static java.lang.Double.NEGATIVE_INFINITY;
import static java.util.Collections.*;
/**
* Implements the GRASP algorithms, with various execution flags.
*
* @author bryanandrews
* @author josephramsey
*/
public class Grasp {
private final List<Node> variables;
private Score score;
private IndependenceTest test;
private IKnowledge knowledge = new Knowledge2();
private TeyssierScorer scorer;
private long start;
// flags
private boolean useScore = true;
private boolean usePearl;
private boolean ordered;
private boolean verbose;
private boolean cachingScores = true;
private int uncoveredDepth = 1;
private int nonSingularDepth = 1;
private boolean useDataOrder = true;
// other params
private int depth = 4;
private int numStarts = 1;
public Grasp(@NotNull Score score) {
this.score = score;
this.variables = new ArrayList<>(score.getVariables());
this.useScore = true;
}
public Grasp(@NotNull IndependenceTest test) {
this.test = test;
this.variables = new ArrayList<>(test.getVariables());
this.useScore = false;
}
public Grasp(@NotNull IndependenceTest test, Score score) {
this.test = test;
this.score = score;
this.variables = new ArrayList<>(test.getVariables());
}
public List<Node> bestOrder(@NotNull List<Node> order) {
long start = System.currentTimeMillis();
order = new ArrayList<>(order);
this.scorer = new TeyssierScorer(this.test, this.score);
this.scorer.setUseVermaPearl(this.usePearl);
if (this.usePearl) {
this.scorer.setUseScore(false);
} else {
this.scorer.setUseScore(this.useScore && !(this.score instanceof GraphScore));
}
this.scorer.setKnowledge(this.knowledge);
this.scorer.clearBookmarks();
this.scorer.setCachingScores(this.cachingScores);
List<Node> bestPerm = null;
double best = NEGATIVE_INFINITY;
this.scorer.score(order);
for (int r = 0; r < this.numStarts; r++) {
if (Thread.interrupted()) break;
if ((r == 0 && !this.useDataOrder) || r > 0) {
shuffle(order);
}
this.start = System.currentTimeMillis();
makeValidKnowledgeOrder(order);
this.scorer.score(order);
List<Node> perm = grasp(this.scorer);
this.scorer.score(perm);
if (this.scorer.score() > best) {
best = this.scorer.score();
bestPerm = perm;
}
}
this.scorer.score(bestPerm);
long stop = System.currentTimeMillis();
if (this.verbose) {
TetradLogger.getInstance().forceLogMessage("Final order = " + this.scorer.getPi());
TetradLogger.getInstance().forceLogMessage("Elapsed time = " + (stop - start) / 1000.0 + " s");
}
return bestPerm;
}
public int getNumEdges() {
return this.scorer.getNumEdges();
}
private void makeValidKnowledgeOrder(List<Node> order) {
if (!this.knowledge.isEmpty()) {
order.sort((o1, o2) -> {
if (o1.getName().equals(o2.getName())) {
return 0;
} else if (this.knowledge.isRequired(o1.getName(), o2.getName())) {
return 1;
} else if (this.knowledge.isRequired(o2.getName(), o1.getName())) {
return -1;
} else if (this.knowledge.isForbidden(o2.getName(), o1.getName())) {
return -1;
} else if (this.knowledge.isForbidden(o1.getName(), o2.getName())) {
return 1;
} else {
return 1;
}
});
}
}
public List<Node> grasp(@NotNull TeyssierScorer scorer) {
scorer.clearBookmarks();
List<int[]> depths = new ArrayList<>();
// GRaSP-TSP
if (this.ordered && this.uncoveredDepth != 0 && this.nonSingularDepth != 0) {
depths.add(new int[]{this.depth < 1 ? Integer.MAX_VALUE : this.depth, 0, 0});
}
// GRaSP-ESP
if (this.ordered && this.nonSingularDepth != 0) {
depths.add(new int[]{this.depth < 1 ? Integer.MAX_VALUE : this.depth,
this.uncoveredDepth < 0 ? Integer.MAX_VALUE : this.uncoveredDepth, 0});
}
// GRaSP
depths.add(new int[]{this.depth < 1 ? Integer.MAX_VALUE : this.depth,
this.uncoveredDepth < 0 ? Integer.MAX_VALUE : this.uncoveredDepth,
this.nonSingularDepth < 0 ? Integer.MAX_VALUE : this.nonSingularDepth});
double sNew = scorer.score();
double sOld;
for (int[] depth : depths) {
do {
sOld = sNew;
graspDfs(scorer, sOld, depth, 1, new HashSet<>(), new HashSet<>());
sNew = scorer.score();
} while (sNew > sOld);
}
if (this.verbose) {
TetradLogger.getInstance().forceLogMessage("# Edges = " + scorer.getNumEdges()
+ " Score = " + scorer.score()
+ " (GRaSP)"
+ " Elapsed " + ((System.currentTimeMillis() - this.start) / 1000.0 + " s"));
}
return scorer.getPi();
}
private void graspDfs(@NotNull TeyssierScorer scorer, double sOld, int[] depth, int currentDepth,
Set<Set<Node>> tucks, Set<Set<Set<Node>>> dfsHistory) {
for (Node y : scorer.getShuffledVariables()) {
Set<Node> ancestors = scorer.getAncestors(y);
List<Node> parents = new ArrayList<>(scorer.getParents(y));
shuffle(parents);
for (Node x : parents) {
boolean covered = scorer.coveredEdge(x, y);
boolean singular = true;
Set<Node> tuck = new HashSet<>();
tuck.add(x);
tuck.add(y);
if (covered && tucks.contains(tuck)) continue;
if (currentDepth > depth[1] && !covered) continue;
int[] idcs = new int[] {scorer.index(x), scorer.index(y)};
int i = idcs[0];
scorer.bookmark(currentDepth);
boolean first = true;
List<Node> Z = new ArrayList<>(scorer.getOrderShallow().subList(i + 1, idcs[1]));
Iterator<Node> zItr = Z.iterator();
do {
if (first) {
scorer.moveToNoUpdate(y, i);
first = false;
} else {
Node z = zItr.next();
if (ancestors.contains(z)) {
if (scorer.getParents(z).contains(x)) {
singular = false;
}
scorer.moveToNoUpdate(z, i++);
}
}
} while (zItr.hasNext());
scorer.updateScores(idcs[0], idcs[1]);
if (currentDepth > depth[2] && !singular) {
scorer.goToBookmark(currentDepth);
continue;
}
if (violatesKnowledge(scorer.getPi())) continue;
double sNew = scorer.score();
if (sNew > sOld) {
if (verbose) {
System.out.printf("Edges: %d \t|\t Score Improvement: %f \t|\t Tucks Performed: %s %s \n",
scorer.getNumEdges(), sNew - sOld, tucks, tuck);
}
return;
}
if (sNew == sOld && currentDepth < depth[0]) {
tucks.add(tuck);
if (currentDepth > depth[1]) {
if (!dfsHistory.contains(tucks)) {
dfsHistory.add(new HashSet<>(tucks));
graspDfs(scorer, sOld, depth, currentDepth + 1, tucks, dfsHistory);
}
} else {
graspDfs(scorer, sOld, depth, currentDepth + 1, tucks, dfsHistory);
}
tucks.remove(tuck);
}
if (scorer.score() > sOld) return;
scorer.goToBookmark(currentDepth);
}
}
}
@NotNull
public Graph getGraph(boolean cpDag) {
if (this.scorer == null) throw new IllegalArgumentException("Please run algorithm first.");
Graph graph = this.scorer.getGraph(cpDag);
NumberFormat nf = NumberFormatUtil.getInstance().getNumberFormat();
graph.addAttribute("score ", nf.format(this.scorer.score()));
return graph;
}
public void setCacheScores(boolean cachingScores) {
this.cachingScores = cachingScores;
}
public void setNumStarts(int numStarts) {
this.numStarts = numStarts;
}
public List<Node> getVariables() {
return this.variables;
}
public boolean isVerbose() {
return this.verbose;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
this.test.setVerbose(verbose);
}
public void setKnowledge(IKnowledge knowledge) {
this.knowledge = knowledge;
}
public void setDepth(int depth) {
if (depth < -1) throw new IllegalArgumentException("Depth should be >= -1.");
this.depth = depth;
}
public void setUncoveredDepth(int uncoveredDepth) {
if (this.depth < -1) throw new IllegalArgumentException("Uncovered depth should be >= -1.");
this.uncoveredDepth = uncoveredDepth;
}
public void setNonSingularDepth(int nonSingularDepth) {
if (this.depth < -1) throw new IllegalArgumentException("Non-singular depth should be >= -1.");
this.nonSingularDepth = nonSingularDepth;
}
public void setUseScore(boolean useScore) {
this.useScore = useScore;
}
private boolean violatesKnowledge(List<Node> order) {
if (!this.knowledge.isEmpty()) {
for (int i = 0; i < order.size(); i++) {
for (int j = i + 1; j < order.size(); j++) {
if (this.knowledge.isForbidden(order.get(i).getName(), order.get(j).getName())) {
return true;
}
}
}
}
return false;
}
public void setOrdered(boolean ordered) {
this.ordered = ordered;
}
public void setUseRaskuttiUhler(boolean usePearl) {
this.usePearl = usePearl;
}
public void setUseDataOrder(boolean useDataOrder) {
this.useDataOrder = useDataOrder;
}
}