-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSP.java
More file actions
455 lines (404 loc) · 15.4 KB
/
Copy pathCSP.java
File metadata and controls
455 lines (404 loc) · 15.4 KB
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
import org.jgrapht.Graph;
import org.jgrapht.Graphs;
import org.jgrapht.alg.color.GreedyColoring;
import org.jgrapht.graph.*;
import org.jgrapht.traverse.DepthFirstIterator;
import java.io.*;
import java.util.*;
/*
* Write a CSP algorithm to solve this coloring problem.
* The CSP algorithm should have the following components:
* x Search algorithm to solve the CSP
* - Heuristics (min remaining values, least constraining value)
* - Constraint propagation using AC3
* */
class V {
String vertex;
int color;
int mrv;
int edges;
HashSet<Integer> domain;
V ptr;
public V(String vertex, int color)
{
this.vertex = vertex;
this.color = color;
this.edges = 0;
}
public String getID() {
return this.vertex;
}
public void setDomain(int colors)
{
domain = new HashSet<>();
for (int i = 0; i < colors; i++)
{
domain.add(i);
}
}
}
class arc {
String x;
String y;
public arc (String x, String y)
{
this.x = x;
this.y = y;
}
}
public class CSP {
static int numAgenda = 0;
public static void main(String[] args) throws IOException
{
Graph<V, DefaultEdge> g = new DefaultUndirectedGraph<>(DefaultEdge.class);
int colors = getGraph(g);
HashMap<String, Integer> coloring = new HashMap<>();
getColoring2(g, colors, coloring);
}
public static int getGraph(Graph<V, DefaultEdge> g) throws IOException
{
int colors = -1;
String test = "gc_basic.txt";
File file = new File(test);
System.out.println(test);
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
// Get to the point in the .txt file where color is defined
while ((line = in.readLine()) != null) {
if (line.contains("colors = ")) {
String[] tokens = line.split(" ");
colors = Integer.parseInt(tokens[2]);
}
if ((line.contains("# Graph:"))) break;
}
HashSet<String> vertices = new HashSet<>();
while ((line = in.readLine()) != null) {
if (line.equals("")) break;
String[] tokens = line.split(",");
V v1, v2;
// Check if vertex is already in the graph
if (!vertices.contains(tokens[0]))
{
v1 = new V(tokens[0], -1);
v1.mrv = colors;
g.addVertex(v1);
vertices.add(tokens[0]);
}
else // Get the vertex which already exists
{
v1 = g.vertexSet().stream().filter(uri -> uri.getID().equals(tokens[0])).findAny().orElse(null);
}
if (!vertices.contains(tokens[1]))
{
v2 = new V(tokens[1], -1);
v2.mrv = colors;
g.addVertex(v2);
vertices.add(tokens[1]);
}
else
{
v2 = g.vertexSet().stream().filter(uri -> uri.getID().equals(tokens[1])).findAny().orElse(null);
}
// Add edge
if (g.addEdge(v1, v2) != null)
{
v1.edges++;
v2.edges++;
}
}
return colors;
}
public static void getColoring2(Graph<V, DefaultEdge> g, int colors, HashMap<String, Integer> coloring)
{
V start = g.vertexSet().stream().filter(V -> V.getID().equals("0")).findAny().orElse(null);
Iterator<V> iterator = new DepthFirstIterator<>(g, start);
ArrayList<V> set = new ArrayList<>();
ArrayList<arc> arcs = new ArrayList<>();
while (iterator.hasNext())
{
V v = iterator.next();
set.add(v);
// Set domain of each vertex
v.setDomain(colors);
// Construct arcs
List<V> neighbors = Graphs.neighborListOf(g, v);
for (V neighbor : neighbors)
{
arc arc1 = new arc(v.getID(), neighbor.getID());
//arc arc2 = new arc(neighbor.getID(), v.getID());
arcs.add(arc1);
//arcs.add(arc2);
}
//System.out.println("Domain of " + v.getID() + ": " + v.domain.toString());
}
Queue<arc> agenda = new ArrayDeque<>();
for (int i = 0; i < arcs.size(); i++)
{
agenda.add(arcs.get(i));
}
System.out.println();
System.out.println("result: " + Util(g, set, colors, coloring, 0, arcs, agenda));
int max = -1;
for (Integer color : coloring.values())
{
if (color > max) max = color;
}
max++;
System.out.println("Colors used: " + max + "\nColoring: " + coloring.toString());
System.out.println("Verifying solution is valid: " + verifyGraph(g));
/*start = g.vertexSet().stream().filter(V -> V.getID().equals("0")).findAny().orElse(null);
iterator = new DepthFirstIterator<>(g, start);
while (iterator.hasNext()) {
V v = iterator.next();
System.out.println(v.getID() + "=" + v.color);
}*/
GreedyColoring<V, DefaultEdge> CSP = new GreedyColoring<>(g);
System.out.println("What does greedy say: " + CSP.getColoring().toString());
System.out.println("Amount of times agenda was used: " + numAgenda);
//System.out.println(colors);
//System.out.println(Graphs.neighborListOf(g, "0"));
/*List<V> test = Graphs.neighborListOf(g, new V(0, -1));
for (V s : test)
{
System.out.println(s.vertex);
}*/
}
// TODO: Verify sample sets can be solved with given coloring (See set 4)
public static boolean Util(Graph<V, DefaultEdge> g, ArrayList<V> set, int colors, HashMap<String, Integer> coloring, int i, ArrayList<arc> arcs, Queue<arc> agenda)
{
/*if (i == set.size())
{
System.out.println("reached max size");
return true;
}*/
if (set.isEmpty())
{
System.out.println("Set empty");
return true;
}
//V currentVertex = set.get(i);
/*System.out.println("vertices and mrv:");
V start = g.vertexSet().stream().filter(V -> V.getID().equals("0")).findAny().orElse(null);
Iterator<V> iterator = new DepthFirstIterator<>(g, start);
while (iterator.hasNext()) {
V v = iterator.next();
System.out.println("vertex " + v.getID() + " has mrv of " + v.mrv);
}*/
// Find vertex with mrv
V currentVertex;
int index = -1;
int mrv = colors + 10;
for (int it = 0; it < set.size(); it++)
{
if (set.get(it).mrv < mrv)
{
mrv = set.get(it).mrv;
index = it;
}
}
currentVertex = set.remove(index);
//System.out.println("Got vertex: " + currentVertex.getID());
// Try to assign that vertex a color
for (int c = 0; c < colors; c++)
{
currentVertex.color = c;
if (verifyColor(g, currentVertex))
{
// We can assign color c to vertex v
// See if AC3 is satisfied
/*currentVertex.domain.clear();
currentVertex.domain.add(c);*/
if (!agenda.isEmpty()) numAgenda++;
while(!agenda.isEmpty())
{
arc temp = agenda.remove();
// Make sure there exists v1, v2, in V1, V2, such that v1 != v2
V v1 = g.vertexSet().stream().filter(V -> V.getID().equals(temp.x)).findAny().orElse(null);
V v2 = g.vertexSet().stream().filter(V -> V.getID().equals(temp.y)).findAny().orElse(null);
// No solution exists in this branch if a domain is empty
//if ((v1.domain.isEmpty()) || (v2.domain.isEmpty())) return false;
if (v2.color == -1) continue;
else
{
Boolean[] toRemove = new Boolean[colors];
Boolean domainChanged = false;
for (Integer it : v1.domain)
{
if (it == v2.color)
{
toRemove[it] = true;
}
}
for (int j = 0; j < toRemove.length; j++)
{
if ((toRemove[j] != null))
{
v1.domain.remove(j);
domainChanged = true;
}
}
// Need to check constraints with v1 on the right hand side
if (domainChanged)
{
for (arc it : arcs)
{
// Add arc back to agenda to check constraints again
if (it.y.equals(v1.getID()))
{
agenda.add(it);
}
}
}
}
if ((v1.domain.isEmpty()) || (v2.domain.isEmpty()))
{
System.out.println("returning gfalse here");
return false;
}
}
// Reset agenda to check arc consistency on next iteration
for (int j = 0; j < arcs.size(); j++)
{
agenda.add(arcs.get(i));
}
//System.out.println("Checking if vertex " + currentVertex.getID() + " can be assigned color " + c);
coloring.put(currentVertex.getID(), c);
updateMRV(g, currentVertex);
if (Util(g, set, colors, coloring, i + 1, arcs, agenda))
{
return true;
}
//System.out.println("Assigning vertex " + currentVertex.getID() + " to color " + currentVertex.color + " did not work");
coloring.remove(currentVertex.getID());
currentVertex.color = -1;
}
}
return false;
}
public static void getColoring(Graph<V, DefaultEdge> g, int colors, HashMap<String, Integer> coloring)
{
V start = g.vertexSet().stream().filter(V -> V.getID().equals("0")).findAny().orElse(null);
Iterator<V> iterator = new DepthFirstIterator<>(g, start);
ArrayList<V> set = new ArrayList<>();
while (iterator.hasNext()) {
V v = iterator.next();
set.add(v);
}
for (int i = 0; i < set.size(); i++)
{
//System.out.println(set.get(i).mrv);
}
while (!set.isEmpty())
{
/*System.out.println("vertices and mrv:");
start = g.vertexSet().stream().filter(V -> V.getID().equals("0")).findAny().orElse(null);
iterator = new DepthFirstIterator<>(g, start);
while (iterator.hasNext()) {
V v = iterator.next();
System.out.println("vertex " + v.getID() + " has mrv of " + v.mrv);
}
// Find vertex with mrv
ArrayList<V> toChooseFrom = new ArrayList<>();
V currentVertex;
int index = -1;
int mrv = colors + 10;
for (int i = 0; i < set.size(); i++)
{
if (set.get(i).mrv < mrv)
{
mrv = set.get(i).mrv;
index = i;
}
}*/
V currentVertex = set.remove(set.size()-1);
//System.out.println("About to color vertex " + currentVertex.getID());
for (int i = 0; i < colors; i++)
{
currentVertex.color = i;
if (verifyColor(g, currentVertex))
{
coloring.put(currentVertex.getID(), i);
updateMRV(g, currentVertex);
break;
}
else
{
// Try the next color
currentVertex.color = -1;
}
}
if (currentVertex.color == -1)
{
System.out.println("SETTING VERTEX TO -1: " + currentVertex.getID());
}
}
int max = -1;
for (Integer color : coloring.values())
{
if (color > max) max = color;
}
max++;
System.out.println("Colors used: " + max + "\nColoring: " + coloring.toString());
System.out.println("Verifying solution is valid: " + verifyGraph(g));
/*System.out.println("Verify edges and mrv: ");
start = g.vertexSet().stream().filter(V -> V.getID().equals("0")).findAny().orElse(null);
iterator = new DepthFirstIterator<>(g, start);
while (iterator.hasNext()) {
V v = iterator.next();
System.out.println("vertex " + v.getID() + " has " + v.edges + " edges and mrv of " + v.mrv);
}*/
}
// Updates mrv
public static void updateMRV(Graph<V, DefaultEdge> g, V v)
{
List<V> neighbors = Graphs.neighborListOf(g, v);
for (V neighbor : neighbors)
neighbor.mrv--;
}
// Ensures a vertex does not share the same color with any neighboring vertices
public static boolean verifyColor(Graph<V, DefaultEdge> g, V v)
{
List<V> neighbors = Graphs.neighborListOf(g, v);
for (V neighbor : neighbors)
{
if (v.color == neighbor.color) return false;
}
return true;
}
// Iterates through each vertex in the graph and ensures no nodes have the same neighbor
public static boolean verifyGraph(Graph<V, DefaultEdge> g)
{
V start = g.vertexSet().stream().filter(V -> V.getID().equals("0")).findAny().orElse(null);
Iterator<V> iterator = new DepthFirstIterator<>(g, start);
while (iterator.hasNext()) {
V v = iterator.next();
if (v.color == -1)
{
System.out.println("Did not color vertex " + v.getID());
System.out.println("check neighbors of " + v.getID());
List<V> neighbors = Graphs.neighborListOf(g, v);
System.out.println("Vertex " + v.getID() + " color: " + v.color);
for (V neighbor : neighbors)
{
System.out.println("neighbor " + neighbor.getID() + " color: " + neighbor.color);
}
return false;
}
if (!verifyColor(g, v))
{
System.out.println("check neighbors of " + v.getID());
List<V> neighbors = Graphs.neighborListOf(g, v);
for (V neighbor : neighbors)
{
if (v.color == neighbor.color)
{
System.out.println("Vertex " + v.getID() + " color: " + v.color);
System.out.println("neighbor " + neighbor.getID() + " color: " + neighbor.color);
}
}
return false;
}
}
return true;
}
}