This repository was archived by the owner on Jun 18, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
2623 lines (2277 loc) · 103 KB
/
Copy pathMain.java
File metadata and controls
2623 lines (2277 loc) · 103 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
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
package gvisual;
import app.Network;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.layout.StaticLayout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.screencap.PNGDump;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeListener;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.collections15.Transformer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.xml.sax.SAXException;
/**
*
* @author user
*/
public class Main extends JFrame {
private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
private static final Color DEFAULT_BG_COLOR = Color.BLACK;
private static final Color Vertex_COLOR = Color.WHITE;
private static int DELAY = 2048;
private JSlider friendDurThreshold;
private JSlider friendNumMeetThreshold;
private JSlider classmateDurThreshold;
private JSlider classmateNumMeetThreshold;
private JSlider fsDurThreshold;
private JSlider fsNumMeetThreshold;
private JSlider strangerDurThreshold;
private JSlider strangerNumMeetThreshold;
private JSlider studyGDurThreshold;
private JSlider studyGNumMeetThreshold;
private String month;
private String date;
private String timeStamp;
private Graph<String, edge> g;
private VisualizationViewer<String, edge> vv;
private Layout<String, edge> graphLayout;
private final GraphRenderers renderers = new GraphRenderers();
/**
* Push current overlay state to the GraphRenderers instance so that
* transformers see up-to-date values on every render pass.
*/
private void syncRenderers() {
renderers.setGraph(g);
renderers.setPathState(pathEdges, pathVertices, pathSource, pathTarget);
renderers.setMstState(mstOverlayActive, mstEdges);
renderers.setCommunityState(communityOverlayActive, nodeCommunityMap);
renderers.setArticulationState(articulationOverlayActive, articulationPoints, bridgeEdges);
renderers.setEgoState(egoOverlayActive, egoCenter, egoNeighbors, egoEdges);
renderers.setOldVertices(OldVertices);
}
private List<edge> friendEdges = new ArrayList<>();
private List<edge> fsEdges = new ArrayList<>();
private List<edge> classmateEdges = new ArrayList<>();
private List<edge> strangerEdges = new ArrayList<>();
private List<edge> studyGEdges = new ArrayList<>();
private String fileName;
private Box parameterSpace;
private JPanel notesPanel;
private JPanel imagePanel;
private JMenuBar menubar;
private JSlider timeline;
private JPanel contentPanel;
private JPanel toolPanel;
private JCheckBox showFriend;
private JCheckBox showClassmate;
private JCheckBox showFS;
private JCheckBox showStranger;
private JCheckBox showStudy;
private Timer timer;
private JButton playButton;
private JButton stopButton;
private JButton pauseButton;
private JButton frShowParam;
private JButton fsShowParam;
private JButton cShowParam;
private JButton sShowParam;
private JButton sgShowParam;
private Box[] categoryPanel;
private JPanel frHpanel;
private JPanel fsHpanel;
private JPanel cHpanel;
private JPanel sHpanel;
private JPanel sgHpanel;
private int NUM_EDGES_IMP_GRAPH = 20;
private JButton prevButton;
private JButton nextButton;
private JButton slowButton;
private JButton fastButton;
private Collection<String> OldVertices;
private int prevTimeline;
private JPanel legendPanel;
private JPanel statsPanel;
private JLabel statsNodeCount;
private JLabel statsEdgeCount;
private JLabel statsFriendCount;
private JLabel statsClassmateCount;
private JLabel statsFsCount;
private JLabel statsStrangerCount;
private JLabel statsStudyGCount;
private JLabel statsDensity;
private JLabel statsAvgDegree;
private JLabel statsMaxDegree;
private JLabel statsAvgWeight;
private JLabel statsIsolated;
private JLabel statsTopNodes;
// --- Shortest path fields ---
private boolean pathFindingMode;
private String pathSource;
private String pathTarget;
private Set<String> pathVertices;
private Set<edge> pathEdges;
private JPanel pathPanel;
private JLabel pathSourceLabel;
private JLabel pathTargetLabel;
private JLabel pathResultLabel;
private JButton pathFindButton;
private JButton pathClearButton;
private JRadioButton pathByHops;
private JRadioButton pathByWeight;
// --- MST fields ---
private JPanel mstPanel;
private JButton mstComputeButton;
private JButton mstClearButton;
private JLabel mstSummaryLabel;
private JLabel mstStatsLabel;
private JLabel mstComponentsLabel;
private boolean mstOverlayActive;
private Set<edge> mstEdges;
// --- Centrality analysis fields ---
private JPanel centralityPanel;
private JButton centralityComputeButton;
private JButton centralityClearButton;
private JComboBox<String> centralityMetricCombo;
private JLabel centralityTopologyLabel;
private JLabel centralitySummaryLabel;
private JLabel centralityRankingLabel;
private boolean centralityActive;
private Map<String, NodeCentralityAnalyzer.CentralityResult> centralityResults;
// --- Community detection fields ---
private JPanel communityPanel;
private JButton communityDetectButton;
private JButton communityClearButton;
private JLabel communityCountLabel;
private JLabel communityModularityLabel;
private JLabel communityDetailsLabel;
private boolean communityOverlayActive;
private Map<String, Integer> nodeCommunityMap;
// --- Articulation point analysis fields ---
private JPanel articulationPanel;
private JButton articulationComputeButton;
private JButton articulationClearButton;
private JLabel articulationSummaryLabel;
private JLabel articulationResilienceLabel;
private JLabel articulationDetailsLabel;
private boolean articulationOverlayActive;
private Set<String> articulationPoints;
private Set<edge> bridgeEdges;
// --- Resilience analysis fields ---
private JPanel resiliencePanel;
private JButton resilienceAnalyzeButton;
private JButton resilienceExportButton;
private JLabel resilienceSummaryLabel;
private JLabel resilienceDetailsLabel;
// --- Ego network fields ---
private JPanel egoPanel;
private JTextField egoSearchField;
private JButton egoSearchButton;
private JButton egoClearButton;
private JLabel egoSummaryLabel;
private JLabel egoNeighborListLabel;
private boolean egoOverlayActive;
private String egoCenter;
private Set<String> egoNeighbors;
private Set<edge> egoEdges;
private static final Color[] COMMUNITY_COLORS = {
new Color(0, 200, 120), // Emerald green
new Color(65, 135, 255), // Bright blue
new Color(255, 100, 100), // Coral red
new Color(255, 200, 50), // Golden yellow
new Color(200, 100, 255), // Purple
new Color(255, 150, 50), // Orange
new Color(100, 220, 220), // Teal
new Color(255, 100, 200), // Pink
new Color(180, 220, 80), // Lime
new Color(150, 130, 255), // Lavender
new Color(255, 180, 150), // Salmon
new Color(100, 180, 150), // Sea green
};
/**
* Constructor
* @throws FileNotFoundException
* @throws Exception
*/
public Main() throws FileNotFoundException, Exception {
initializeContentPanel();
initializeLegendSpace();
initializeStatsPanel();
initializePathPanel();
initializeCommunityPanel();
initializeMSTPanel();
initializeCentralityPanel();
initializeArticulationPanel();
initializeResiliencePanel();
initializeEgoPanel();
initializeTimeLine();
initializeToolBar();
initializeParameterSpace();
initializeImagePanel();
initializeNotesSpace();
setJMenuBar(menubar);
showRightPane();
updateTime();
addGraph();
setTitle("Visualization");
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/**
* Returns the edge list for the given edge type.
* Used to replace the cascading if/else chain in addGraph().
*/
private List<edge> getEdgeList(EdgeType type) {
switch (type) {
case FRIEND: return friendEdges;
case CLASSMATE: return classmateEdges;
case FAMILIAR: return fsEdges;
case STRANGER: return strangerEdges;
case STUDY_GROUP: return studyGEdges;
default: return null;
}
}
/**
* Returns whether the given edge type code is currently visible
* (its checkbox is selected).
*/
private boolean isEdgeTypeVisible(String typeCode) {
EdgeType type = EdgeType.fromCode(typeCode);
if (type == null) return true; // unknown types are visible by default
switch (type) {
case FRIEND: return showFriend.isSelected();
case CLASSMATE: return showClassmate.isSelected();
case FAMILIAR: return showFS.isSelected();
case STRANGER: return showStranger.isSelected();
case STUDY_GROUP: return showStudy.isSelected();
default: return true;
}
}
/**
* Create the layout for the graph
*/
public void createLayout() {
graphLayout = new StaticLayout<String, edge>(g);
List<List<String>> clusters = new ArrayList<>();
for (int i = 0; i < 9; i++) {
clusters.add(new ArrayList<>());
}
for (String x : g.getVertices()) {
boolean isF = false;
boolean isFs = false;
boolean isC = false;
boolean isS = false;
boolean isSg = false;
int areaId;
for (edge y : g.getOutEdges(x)) {
EdgeType type = EdgeType.fromCode(y.getType());
if (type != null) {
switch (type) {
case FRIEND: isF = true; break;
case FAMILIAR: isFs = true; break;
case CLASSMATE: isC = true; break;
case STRANGER: isS = true; break;
case STUDY_GROUP: isSg = true; break;
}
}
}
// To be added study groups
if (isF && !isFs && !isC && !isS) {
areaId = 0;
} else if (isF && isFs && !isC && !isS) {
areaId = 3;
} else if (isF && !isFs && isC && !isS) {
areaId = 1;
} else if (!isF && !isFs && isC && !isS) {
areaId = 2;
} else if (!isF && !isFs && isC && isS) {
areaId = 5;
} else if (!isF && isFs && !isC && isS) {
areaId = 7;
} else if (!isF && isFs && !isC && !isS) {
areaId = 6;
} else if (!isF && !isFs && !isC && isS) {
areaId = 8;
} else {
areaId = 4;
}
clusters.get(areaId).add(x);
}
for (int i = 0; i < 9; i++) {
positionCluster(clusters.get(i), i / 3, i % 3);
}
}
/**
* Positions a given set of vertices at certain location, but at random positions in that area
* @param vertices list of vertices to cluster
* @param y y-position of cluster
* @param x x-position of cluster
*/
public void positionCluster(List<String> vertices, int y, int x) {
int delX = 0;
int delY = 0;
int curX = x * 300 + 150;
int curY = y * 200 + 100;
int signX = 0; //0 is +ve
int signY = 1; // 1 is -ve
Random generator = new Random(42);
for (String v : vertices) {
graphLayout.setLocation(v, new java.awt.Point(curX, curY));
delX = 5 + generator.nextInt(40);
delY = 5 + generator.nextInt(40);
signX = generator.nextInt(2);
signY = generator.nextInt(2);
if (signX == 0) {
curX = curX + delX;
} else if (signX == 1) {
curX = curX - delX;
}
if (signY == 0) {
curY = curY + delY;
} else if (signY == 1) {
curY = curY - delY;
}
}
}
/**
* updates the timestamp of the currently selected graph.
*
* The timeline slider value (1..92) maps to calendar dates
* March 1 – May 31, 2011. March has 31 days, April has 30,
* May has 31.
*/
public void updateTime() {
int day = timeline.getValue(); // 1..92
if (day <= 31) {
// March: days 1–31
month = "03";
} else if (day <= 61) {
// April: days 32–61 → April 1–30
month = "04";
day = day - 31;
} else {
// May: days 62–92 → May 1–31
month = "05";
day = day - 61;
}
date = (day < 10) ? ("0" + day) : Integer.toString(day);
timeStamp = "2011-" + month + "-" + date;
}
/**
* Creates a ChangeListener that refreshes the graph when the slider
* stops adjusting. Replaces the identical anonymous listener that was
* duplicated 10+ times across the category sliders and timeline.
*
* @param slider the slider whose {@code getValueIsAdjusting()} is checked
* @return a reusable ChangeListener
*/
private ChangeListener createGraphRefreshListener(final JSlider slider) {
return e -> {
if (!slider.getValueIsAdjusting()) {
try {
addGraph();
} catch (ParserConfigurationException | IOException | SAXException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
};
}
/**
* Holds the UI components for a single edge-type category row.
*/
private static class CategoryRow {
final JCheckBox checkbox;
final JPanel headerPanel;
final JSlider durationSlider;
final JSlider meetingSlider;
final JButton settingsButton;
boolean showParams;
CategoryRow(JCheckBox checkbox, JPanel headerPanel,
JSlider durationSlider, JSlider meetingSlider,
JButton settingsButton) {
this.checkbox = checkbox;
this.headerPanel = headerPanel;
this.durationSlider = durationSlider;
this.meetingSlider = meetingSlider;
this.settingsButton = settingsButton;
this.showParams = false;
}
}
/** All five category rows, indexed by EdgeType ordinal. */
private CategoryRow[] categoryRows;
/**
* Creates a fully-wired category row (checkbox + label + sliders + settings
* button) for the given edge type. This replaces the five near-identical
* blocks that previously lived in {@code initializeCategoryPanel()}.
*
* @param type the edge type this row controls
* @param edgeList the corresponding edge list (e.g. {@code friendEdges})
* @param labelText the display text for the label
* @param durMax maximum value for the duration slider
* @return a fully-initialised {@code CategoryRow}
*/
private CategoryRow createCategoryRow(final EdgeType type,
final List<edge> edgeList,
String labelText,
int durMax) {
JButton settingsBtn = new JButton(new ImageIcon("./images/settings.png"));
settingsBtn.setBorder(null);
final JCheckBox cb = new JCheckBox();
cb.setSelected(true);
cb.addActionListener(e -> {
if (cb.isSelected()) {
for (edge x : edgeList) { g.addEdge(x, x.getVertex1(), x.getVertex2()); }
} else {
for (edge x : edgeList) { g.removeEdge(x); }
}
imagePanel.setVisible(false);
imagePanel.setVisible(true);
});
JPanel header = new JPanel();
JLabel label = new JLabel(labelText, JLabel.CENTER);
label.setForeground(type.getColor());
label.setFont(new Font("SANS_SERIF", 0, 14));
header.add(cb);
header.add(label);
header.add(settingsBtn);
JSlider durSlider = new JSlider(0, durMax, type.getDefaultDurationThreshold());
JSlider meetSlider = new JSlider(0, 5, type.getDefaultMeetingThreshold());
durSlider.setBorder(BorderFactory.createTitledBorder("Duration of meeting (min)"));
meetSlider.setBorder(BorderFactory.createTitledBorder("Number of meetings in a day"));
int durMajor = durMax <= 25 ? 5 : 10;
durSlider.setMajorTickSpacing(durMajor);
durSlider.setMinorTickSpacing(1);
meetSlider.setMajorTickSpacing(1);
meetSlider.setMinorTickSpacing(1);
durSlider.setPaintTicks(true);
durSlider.setPaintLabels(true);
meetSlider.setPaintTicks(true);
meetSlider.setPaintLabels(true);
durSlider.addChangeListener(createGraphRefreshListener(durSlider));
meetSlider.addChangeListener(createGraphRefreshListener(meetSlider));
final CategoryRow row = new CategoryRow(cb, header, durSlider, meetSlider, settingsBtn);
settingsBtn.addActionListener(e -> {
row.showParams = !row.showParams;
paintCategoryPanel();
});
return row;
}
/**
* Creates the next/prev important graph according to the input direction
* @param direction next/prev
* @throws Exception
*/
public void nextOrPrevGraph(String direction) throws Exception {
boolean success = false;
while (!success) {
fileName = "./graph.txt";
int count = 0;
File database;
LineIterator lineIterator = null;
if (month.equals("05") && date.equals("31") && direction.equals("next")) {
return;
} else if (month.equals("03") && date.equals("01") && direction.equals("prev")) {
return;
} else if (direction.equals("next")) {
timeline.setValue(timeline.getValue() + 1);
updateTime();
} else if (direction.equals("prev")) {
timeline.setValue(timeline.getValue() - 1);
updateTime();
}
Network.generateFile(fileName, month, date, friendDurThreshold.getValue(), friendNumMeetThreshold.getValue(), fsDurThreshold.getValue(), fsNumMeetThreshold.getValue(), classmateDurThreshold.getValue(), classmateNumMeetThreshold.getValue(), strangerDurThreshold.getValue(), strangerNumMeetThreshold.getValue(), studyGDurThreshold.getValue(), studyGNumMeetThreshold.getValue());
database = new File(fileName);
lineIterator = FileUtils.lineIterator(database);
while (lineIterator.hasNext()) {
lineIterator.next();
count++;
}
if (count > NUM_EDGES_IMP_GRAPH) {
success = true;
}
lineIterator.close();
}
addGraph();
}
/**
* refresh the graph
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public void addGraph() throws ParserConfigurationException, IOException, SAXException {
fileName = "./graph.txt";
try {
imagePanel.removeAll();
imagePanel.repaint();
timeline.setBorder(BorderFactory.createTitledBorder(timeStamp));
Network.generateFile(fileName, month, date, friendDurThreshold.getValue(), friendNumMeetThreshold.getValue(), fsDurThreshold.getValue(), fsNumMeetThreshold.getValue(), classmateDurThreshold.getValue(), classmateNumMeetThreshold.getValue(), strangerDurThreshold.getValue(), strangerNumMeetThreshold.getValue(), studyGDurThreshold.getValue(), studyGNumMeetThreshold.getValue());
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
if (g != null && prevTimeline != timeline.getValue() && g.getEdgeCount() != 0) {
OldVertices = g.getVertices();
prevTimeline = timeline.getValue();
}
// Parse graph file using extracted parser (separates I/O from UI)
GraphFileParser.ParseResult parseResult = GraphFileParser.parse(
fileName, this::isEdgeTypeVisible);
g = parseResult.getGraph();
// Populate classified edge lists from parse result
for (EdgeType type : EdgeType.values()) {
List<edge> list = getEdgeList(type);
if (list != null) {
list.clear();
list.addAll(parseResult.getEdges(type));
}
}
createLayout();
vv = new VisualizationViewer<String, edge>(graphLayout);
vv.setSize(new Dimension(100, 0));
DefaultModalGraphMouse gm = new DefaultModalGraphMouse();
gm.setMode(ModalGraphMouse.Mode.TRANSFORMING);
vv.setGraphMouse(gm);
Transformer<edge, String> edgeLabel = (edge i) -> {
return i.getLabel();
};
vv.getRenderContext().setEdgeLabelTransformer(edgeLabel);
vv.setBackground(DEFAULT_BG_COLOR);
Transformer<String, String> vertexLabel = (String i) -> {
return i;
};
vv.setForeground(Color.white);
vv.getRenderContext().setVertexLabelTransformer(vertexLabel);
// Sync overlay state and set up rendering transformers
syncRenderers();
vv.getRenderContext().setEdgeDrawPaintTransformer(renderers.edgePaintTransformer());
vv.getRenderContext().setVertexFillPaintTransformer(renderers.vertexPaintTransformer());
vv.getRenderContext().setVertexShapeTransformer(renderers.vertexShapeTransformer());
vv.getRenderContext().setEdgeStrokeTransformer(renderers.edgeStrokeTransformer());
imagePanel.add(vv);
imagePanel.setVisible(false);
imagePanel.setVisible(true);
updateStatsPanel();
LOGGER.fine("Graph added");
}
/**
* initialize the Legend Space
*/
public final void initializeLegendSpace(){
legendPanel = new LegendPanel();
/**
* Initializes the shortest path finder panel with source/target selection,
* path mode toggle, and result display.
*/
public final void initializePathPanel() {
pathFindingMode = false;
pathSource = null;
pathTarget = null;
pathVertices = new HashSet<String>();
pathEdges = new HashSet<edge>();
pathPanel = new JPanel();
pathPanel.setLayout(new BoxLayout(pathPanel, BoxLayout.Y_AXIS));
pathPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
"Shortest Path Finder",
TitledBorder.CENTER,
TitledBorder.TOP));
Font labelFont = new Font("SansSerif", Font.PLAIN, 12);
pathSourceLabel = new JLabel("Source: (none)");
pathSourceLabel.setFont(labelFont);
pathSourceLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
pathTargetLabel = new JLabel("Target: (none)");
pathTargetLabel.setFont(labelFont);
pathTargetLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
pathResultLabel = new JLabel("<html>Click 'Select Nodes' then click two nodes on the graph.</html>");
pathResultLabel.setFont(labelFont);
pathResultLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
// Path mode radio buttons
pathByHops = new JRadioButton("Fewest hops", true);
pathByWeight = new JRadioButton("Lowest weight");
ButtonGroup pathModeGroup = new ButtonGroup();
pathModeGroup.add(pathByHops);
pathModeGroup.add(pathByWeight);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.X_AXIS));
radioPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
radioPanel.add(pathByHops);
radioPanel.add(pathByWeight);
// Buttons
pathFindButton = new JButton("Select Nodes");
pathFindButton.setAlignmentX(JButton.LEFT_ALIGNMENT);
pathFindButton.addActionListener(e -> {
if (!pathFindingMode) {
enablePathFindingMode();
} else {
disablePathFindingMode();
}
});
pathClearButton = new JButton("Clear Path");
pathClearButton.setAlignmentX(JButton.LEFT_ALIGNMENT);
pathClearButton.addActionListener(e -> {
clearPath();
});
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
buttonPanel.add(pathFindButton);
buttonPanel.add(Box.createHorizontalStrut(4));
buttonPanel.add(pathClearButton);
pathPanel.add(pathSourceLabel);
pathPanel.add(pathTargetLabel);
pathPanel.add(Box.createVerticalStrut(4));
pathPanel.add(radioPanel);
pathPanel.add(Box.createVerticalStrut(4));
pathPanel.add(buttonPanel);
pathPanel.add(Box.createVerticalStrut(4));
pathPanel.add(pathResultLabel);
}
/**
* Enables path-finding mode — switches to PICKING mode and listens for
* two node clicks (source, then target).
*/
private void enablePathFindingMode() {
pathFindingMode = true;
pathSource = null;
pathTarget = null;
pathVertices.clear();
pathEdges.clear();
pathFindButton.setText("Cancel");
pathSourceLabel.setText("Source: (click a node...)");
pathTargetLabel.setText("Target: (waiting...)");
pathResultLabel.setText("<html>Click the source node on the graph.</html>");
// Switch to picking mode for node selection
DefaultModalGraphMouse gm = new DefaultModalGraphMouse();
gm.setMode(ModalGraphMouse.Mode.PICKING);
vv.setGraphMouse(gm);
vv.addMouseListener(pathMouseListener);
refreshGraph();
}
/**
* Disables path-finding mode and restores normal interaction.
*/
private void disablePathFindingMode() {
pathFindingMode = false;
pathFindButton.setText("Select Nodes");
vv.removeMouseListener(pathMouseListener);
// Restore transform mode
DefaultModalGraphMouse gm = new DefaultModalGraphMouse();
gm.setMode(ModalGraphMouse.Mode.TRANSFORMING);
vv.setGraphMouse(gm);
}
/**
* Clears the current path highlight and resets the path panel.
*/
private void clearPath() {
pathSource = null;
pathTarget = null;
pathVertices.clear();
pathEdges.clear();
pathSourceLabel.setText("Source: (none)");
pathTargetLabel.setText("Target: (none)");
pathResultLabel.setText("<html>Click 'Select Nodes' then click two nodes on the graph.</html>");
if (pathFindingMode) {
disablePathFindingMode();
}
refreshGraph();
}
/**
* Finds the closest graph vertex to the given screen coordinates.
*/
private String findClosestVertex(int screenX, int screenY) {
String closest = null;
double minDist = Double.MAX_VALUE;
for (String vertex : g.getVertices()) {
java.awt.geom.Point2D layoutPoint = graphLayout.transform(vertex);
java.awt.geom.Point2D screenPoint = vv.getRenderContext()
.getMultiLayerTransformer()
.transform(layoutPoint);
double dx = screenPoint.getX() - screenX;
double dy = screenPoint.getY() - screenY;
double dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist < 30) { // 30px click radius
minDist = dist;
closest = vertex;
}
}
return closest;
}
/**
* Runs the shortest path algorithm and highlights the result.
*/
private void computeAndHighlightPath() {
if (pathSource == null || pathTarget == null) return;
ShortestPathFinder finder = new ShortestPathFinder(g);
ShortestPathFinder.PathResult result;
if (pathByWeight.isSelected()) {
result = finder.findShortestByWeight(pathSource, pathTarget);
} else {
result = finder.findShortestByHops(pathSource, pathTarget);
}
pathVertices.clear();
pathEdges.clear();
if (result == null) {
pathResultLabel.setText("<html><b style='color:red'>No path found!</b><br/>"
+ "Nodes are in disconnected components.</html>");
} else {
pathVertices.addAll(result.getVertices());
pathEdges.addAll(result.getEdges());
String mode = pathByWeight.isSelected() ? "weight-optimal" : "hop-optimal";
StringBuilder edgeTypes = new StringBuilder();
for (edge e : result.getEdges()) {
if (edgeTypes.length() > 0) edgeTypes.append("→");
edgeTypes.append(e.getType());
}
pathResultLabel.setText(String.format(
"<html><b style='color:#00FF00'>Path found!</b> (%s)<br/>"
+ "Hops: %d<br/>"
+ "Total weight: %.1f<br/>"
+ "Edge types: %s<br/>"
+ "Path: %s</html>",
mode,
result.getHopCount(),
result.getTotalWeight(),
edgeTypes.toString(),
buildPathString(result)));
}
disablePathFindingMode();
refreshGraph();
}
private String buildPathString(ShortestPathFinder.PathResult result) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.getVertices().size(); i++) {
if (i > 0) sb.append("→");
sb.append(result.getVertices().get(i));
}
return sb.toString();
}
/**
* Refreshes the graph visualization to show/hide path highlighting.
*/
private void refreshGraph() {
if (imagePanel != null) {
imagePanel.setVisible(false);
imagePanel.setVisible(true);
}
}
/**
* Mouse listener for path node selection.
*/
private final MouseListener pathMouseListener = new MouseListener() {
public void mouseClicked(MouseEvent e) {
if (!pathFindingMode) return;
String clicked = findClosestVertex(e.getX(), e.getY());
if (clicked == null) return;
if (pathSource == null) {
pathSource = clicked;
pathSourceLabel.setText("Source: Node " + clicked);
pathTargetLabel.setText("Target: (click another node...)");
pathResultLabel.setText("<html>Now click the target node.</html>");
refreshGraph();
} else if (pathTarget == null) {
if (clicked.equals(pathSource)) {
pathResultLabel.setText("<html>Same node — pick a different target.</html>");
return;
}
pathTarget = clicked;
pathTargetLabel.setText("Target: Node " + clicked);
computeAndHighlightPath();
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
};
/**
* Initializes the community detection panel with detect/clear buttons
* and a results display area.
*/
public final void initializeCommunityPanel() {
communityOverlayActive = false;
syncRenderers();
nodeCommunityMap = null;
communityPanel = new JPanel();
communityPanel.setLayout(new BoxLayout(communityPanel, BoxLayout.Y_AXIS));
communityPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
"Community Detection",
TitledBorder.CENTER,
TitledBorder.TOP));
Font labelFont = new Font("SansSerif", Font.PLAIN, 12);
communityCountLabel = new JLabel("Communities: —");
communityCountLabel.setFont(labelFont);
communityCountLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
communityModularityLabel = new JLabel("Modularity: —");
communityModularityLabel.setFont(labelFont);
communityModularityLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
communityDetailsLabel = new JLabel("<html>Click 'Detect' to find communities.</html>");
communityDetailsLabel.setFont(labelFont);
communityDetailsLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
communityDetectButton = new JButton("Detect");
communityDetectButton.setAlignmentX(JButton.LEFT_ALIGNMENT);
communityDetectButton.addActionListener(e -> {
runCommunityDetection();
});
communityClearButton = new JButton("Clear");
communityClearButton.setAlignmentX(JButton.LEFT_ALIGNMENT);
communityClearButton.addActionListener(e -> {
clearCommunityOverlay();
});
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
buttonPanel.add(communityDetectButton);
buttonPanel.add(Box.createHorizontalStrut(4));
buttonPanel.add(communityClearButton);
communityPanel.add(communityCountLabel);
communityPanel.add(communityModularityLabel);
communityPanel.add(Box.createVerticalStrut(4));
communityPanel.add(buttonPanel);
communityPanel.add(Box.createVerticalStrut(4));
communityPanel.add(communityDetailsLabel);
}
/**
* Runs community detection on the current graph and activates the
* community color overlay.