-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsave_rds_from_prototype.R
More file actions
3741 lines (3246 loc) · 145 KB
/
save_rds_from_prototype.R
File metadata and controls
3741 lines (3246 loc) · 145 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
# Auto-generated script to extract and save .rds objects from Prototype.qmd
library(tidyverse)
library(igraph)
library(ggraph)
library(tidygraph)
# Set output directory
dir.create("rds_objects", showWarnings = FALSE)
# ------------------
library(shiny)
library(wordcloud)
library(RColorBrewer)
# Data and color palette
word <- c("vessels", "mining", "funding", "music", "reef", "conservation", "turtles",
"fuel", "permit", "?", "suspicious", "tourism", "lighting", "meetings",
"council", "harbor", "relationships", "communications", "operation", "underwater")
freq <- c(5, 8, 7, 8, 9, 5, 6, 10, 8, 4, 3, 3, 5, 2, 3, 2, 5, 8, 3, 4)
word_data_wc <- data.frame(word = word, freq = freq)
ocean_colors_lp <- c(
"#1B1B3A", "#0072B2", "#009E73", "#D55E00", "#CC79A7",
"#882255", "#AA4499", "#004D40", "#333333"
)
# Define UI
ui <- fluidPage(
titlePanel(" "),
plotOutput("wordcloudPlot", height = "500px") # Increased height
)
# Define Server
server <- function(input, output, session) {
output$wordcloudPlot <- renderPlot({
par(bg = "#f0f0fb") # Set background inside renderPlot
wordcloud(
words = word_data_wc$word,
freq = word_data_wc$freq,
min.freq = 1,
max.words = 200,
random.order = FALSE,
colors = ocean_colors_lp,
rot.per = 0.20,
scale = c(4, 0.8)
)
})
}
# Launch App
shinyApp(ui, server)
saveRDS(server, file = file.path("rds_objects", "server.rds"))
saveRDS(word, file = file.path("rds_objects", "word.rds"))
saveRDS(freq, file = file.path("rds_objects", "freq.rds"))
saveRDS(ui, file = file.path("rds_objects", "ui.rds"))
saveRDS(ocean_colors_lp, file = file.path("rds_objects", "ocean_colors_lp.rds"))
saveRDS(word_data_wc, file = file.path("rds_objects", "word_data_wc.rds"))
# ------------------
#| code-fold: true
#| code-summary: "Show the code"
pacman::p_load(
jsonlite, tidyverse, ggtext,
knitr, lubridate, hms, scales,
tidytext, dplyr, tm, SnowballC,
patchwork, ggraph,
tidygraph, igraph, ggiraph,
SmartEDA, plotly, wordcloud,
ggh4x, visNetwork, ggplot2,
RColorBrewer, circlize,
stringr, wordcloud2, ggalluvial,
reactable, readr)
# ------------------
#| code-fold: true
#| code-summary: "Show the code"
mc3_data <- fromJSON("data/mc3_graph.json")
mc3_schema <- fromJSON("data/MC3_schema.json")
saveRDS(mc3_data, file = file.path("rds_objects", "mc3_data.rds"))
saveRDS(mc3_schema, file = file.path("rds_objects", "mc3_schema.rds"))
# ------------------
node_legend_colors_plot <- c(
"Person" = "#88CCEE",
"Vessel" = "#D55E00",
"Organization" = "#117733",
"Location" = "#AA4499",
"Group"= "#CC79A7",
"Event" = "#DDCC77",
"Relationship" = "#AF8DC3",
"Nadia Conti" = "red"
)
node_legend_shapes_plot <- c(
"Person" = "dot",
"Vessel" = "triangle",
"Organization" = "square",
"Location" = "diamond",
"Group" = "circle plus",
"Event" = "star",
"Relationship" = "square x",
"Nadia Conti" = "star"
)
STYLES <- list(
node_label_dark = "black",
font_family = "Roboto Condensed"
)
saveRDS(node_legend_shapes_plot, file = file.path("rds_objects", "node_legend_shapes_plot.rds"))
saveRDS(node_legend_colors_plot, file = file.path("rds_objects", "node_legend_colors_plot.rds"))
saveRDS(STYLES, file = file.path("rds_objects", "STYLES.rds"))
# ------------------
glimpse(mc3_data)
# ------------------
mc3_nodes_raw <- as_tibble(mc3_data$nodes)
mc3_edges_raw <- as_tibble(mc3_data$edges)
saveRDS(mc3_edges_raw, file = file.path("rds_objects", "mc3_edges_raw.rds"))
saveRDS(mc3_nodes_raw, file = file.path("rds_objects", "mc3_nodes_raw.rds"))
# ------------------
ExpData(data=mc3_nodes_raw,type=2)
# ------------------
ExpData(data=mc3_edges_raw,type=2)
# ------------------
library(shiny)
library(ggplot2)
# Run ExpCatViz once at the top to avoid recomputing
ExpCatViz(data=mc3_nodes_raw,
col="navyblue")
# ------------------
# Step 1: Count and reorder
mc3_nodes_ordered <- mc3_nodes_raw %>%
count(sub_type) %>%
arrange((n)) %>%
mutate(sub_type = factor(sub_type, levels = sub_type))
# Step 2: Plot with navy bars, sorted, and horizontal
ggplot(mc3_nodes_ordered, aes(x = sub_type, y = n)) +
geom_col(fill = "navy") +
coord_flip() +
labs(x = "Sub_type", y = "Count",
title = "Distribution of Subtypes") +
theme_minimal()
saveRDS(mc3_nodes_ordered, file = file.path("rds_objects", "mc3_nodes_ordered.rds"))
# ------------------
# Step 1: Filter for type == "Entity", count sub_type, sort
relationship_subtypes <- mc3_nodes_raw %>%
filter(type == "Entity") %>%
count(sub_type) %>%
arrange(n) %>%
mutate(sub_type = factor(sub_type, levels = sub_type))
# Step 2: Plot
ggplot(relationship_subtypes, aes(x = sub_type, y = n)) +
geom_col(fill = "navy") +
coord_flip() +
labs(
x = "Entity Subtype",
y = "Count",
title = "Distribution of Entity Subtypes"
) +
theme_minimal()
saveRDS(relationship_subtypes, file = file.path("rds_objects", "relationship_subtypes.rds"))
# ------------------
# Step 1: Filter for type == "Event", count sub_type, sort
relationship_subtypes <- mc3_nodes_raw %>%
filter(type == "Event") %>%
count(sub_type) %>%
arrange(n) %>%
mutate(sub_type = factor(sub_type, levels = sub_type))
# Step 2: Plot
ggplot(relationship_subtypes, aes(x = sub_type, y = n)) +
geom_col(fill = "navy") +
coord_flip() +
labs(
x = "Event Subtype",
y = "Count",
title = "Distribution of Event Subtypes"
) +
theme_minimal()
saveRDS(relationship_subtypes, file = file.path("rds_objects", "relationship_subtypes.rds"))
# ------------------
# Step 1: Filter for type == "Relationship", count sub_type, sort
relationship_subtypes <- mc3_nodes_raw %>%
filter(type == "Relationship") %>%
count(sub_type) %>%
arrange(n) %>%
mutate(sub_type = factor(sub_type, levels = sub_type))
# Step 2: Plot
ggplot(relationship_subtypes, aes(x = sub_type, y = n)) +
geom_col(fill = "navy") +
coord_flip() +
labs(
x = "Relationship Subtype",
y = "Count",
title = "Distribution of Relationship Subtypes"
) +
theme_minimal()
saveRDS(relationship_subtypes, file = file.path("rds_objects", "relationship_subtypes.rds"))
# ------------------
ExpCatViz(data=mc3_edges_raw,
col="navyblue")
# ------------------
# Step 1: Filter for type == "sent"
filtered_edges <- mc3_edges_raw %>%
filter(type == "sent") %>%
count(source) %>%
arrange(desc(n)) %>%
mutate(source = factor(source, levels = rev(unique(source)))) # descending
# Step 2: Plot
ggplot(filtered_edges, aes(x = source, y = n)) +
geom_col(fill = "navy") +
coord_flip() +
labs(
title = "Distribution of 'sent' Edges type by Source",
x = "Source",
y = "Count"
) +
theme_minimal()
saveRDS(filtered_edges, file = file.path("rds_objects", "filtered_edges.rds"))
# ------------------
mc3_nodes_cleaned <- mc3_nodes_raw %>%
mutate(id = as.character(id)) %>%
filter(!is.na(id)) %>%
distinct(id, .keep_all = TRUE) %>%
select(-thing_collected, -time, -date, -friendship_type)
saveRDS(mc3_nodes_cleaned, file = file.path("rds_objects", "mc3_nodes_cleaned.rds"))
# ------------------
# Find the number of unique types in each column and sort descending
unique_counts <- mc3_nodes_cleaned %>%
summarise_all(n_distinct) %>%
pivot_longer(cols = everything(), names_to = "column", values_to = "unique_count") %>%
arrange(desc(unique_count)) # sort by unique_count in descending order
# Print the result
print(unique_counts)
saveRDS(unique_counts, file = file.path("rds_objects", "unique_counts.rds"))
# ------------------
mc3_edges_cleaned <- mc3_edges_raw %>%
rename(from_id = source,
to_id = target) %>%
mutate(across(c(from_id, to_id), as.character)) %>%
# Parse to_id to get supertype and sub_type for target nodes (e.g., Event_Communication)
separate(to_id, into = c("to_id_supertype", "to_id_sub_type", "to_id_num"),
sep = "_", remove = FALSE, fill = "right", extra = "merge") %>%
# Filter to ensure from_id and to_id exist in mc3_nodes_cleaned (prevent orphaned edges)
filter(from_id %in% mc3_nodes_cleaned$id,
to_id %in% mc3_nodes_cleaned$id) %>%
filter(!is.na(from_id), !is.na(to_id))
print("Columns in mc3_edges_cleaned after initial cleaning:")
print(colnames(mc3_edges_cleaned))
print("Head of mc3_edges_cleaned after initial cleaning:")
print(head(mc3_edges_cleaned))
saveRDS(mc3_edges_cleaned, file = file.path("rds_objects", "mc3_edges_cleaned.rds"))
# ------------------
# Find the number of unique types in each column
unique_counts <- mc3_edges_cleaned %>%
summarise_all(n_distinct) %>%
pivot_longer(cols = everything(), names_to = "column", values_to = "unique_count")
# Print the unique counts for each column
print(unique_counts)
saveRDS(unique_counts, file = file.path("rds_objects", "unique_counts.rds"))
# ------------------
node_index_lookup <- mc3_nodes_cleaned %>%
mutate(.row_id = row_number()) %>%
select(id, .row_id)
saveRDS(node_index_lookup, file = file.path("rds_objects", "node_index_lookup.rds"))
# ------------------
mc3_edges_indexed <- mc3_edges_cleaned %>%
left_join(node_index_lookup, by = c("from_id" = "id")) %>%
rename(from = .row_id) %>%
left_join(node_index_lookup, by = c("to_id" = "id")) %>%
rename(to = .row_id) %>%
# Filter out edges where either source or target node was not found
filter(!is.na(from) & !is.na(to)) %>%
# Select all columns to carry forward to mc3_edges_final
select(from, to, id, is_inferred, type, # Original edge attributes
from_id, to_id, to_id_supertype, to_id_sub_type, to_id_num # Original IDs and parsed target type
)
saveRDS(mc3_edges_indexed, file = file.path("rds_objects", "mc3_edges_indexed.rds"))
# ------------------
used_node_indices <- sort(unique(c(mc3_edges_indexed$from, mc3_edges_indexed$to)))
mc3_nodes_final <- mc3_nodes_cleaned %>%
slice(used_node_indices) %>%
mutate(new_index = row_number())
saveRDS(mc3_nodes_final, file = file.path("rds_objects", "mc3_nodes_final.rds"))
saveRDS(used_node_indices, file = file.path("rds_objects", "used_node_indices.rds"))
# ------------------
old_to_new_index <- tibble(
old_index = used_node_indices,
new_index = seq_along(used_node_indices)
)
saveRDS(old_to_new_index, file = file.path("rds_objects", "old_to_new_index.rds"))
# ------------------
mc3_edges_final <- mc3_edges_indexed %>%
left_join(old_to_new_index, by = c("from" = "old_index")) %>%
rename(from_new = new_index) %>%
left_join(old_to_new_index, by = c("to" = "old_index")) %>%
rename(to_new = new_index) %>%
# Explicitly select all columns that are needed downstream
select(from = from_new, to = to_new,
id, is_inferred, type,
from_id, to_id, to_id_supertype, to_id_sub_type, to_id_num)
saveRDS(mc3_edges_final, file = file.path("rds_objects", "mc3_edges_final.rds"))
# ------------------
mc3_graph <- tbl_graph(
nodes = mc3_nodes_final,
edges = mc3_edges_final,
directed = TRUE
)
saveRDS(mc3_graph, file = file.path("rds_objects", "mc3_graph.rds"))
# ------------------
str(mc3_graph)
# ------------------
# ---- 1. Define styles and legends ----
event_subtypes <- c(
"Communication", "Monitoring", "VesselMovement", "Assessment",
"Collaborate", "Endorsement", "TourActivity", "TransponderPing",
"Harbor Report", "Fishing", "Criticize"
)
relationship_subtypes <- c(
"Coordinates", "AccessPermission", "Operates", "Colleagues",
"Suspicious", "Reports", "Jurisdiction", "Unfriendly", "Friends"
)
node_legend_colors_plot <- c(
"Person" = "#88CCEE",
"Vessel" = "#D55E00",
"Organization" = "#117733",
"Location" = "#AA4499",
"Group"= "#CC79A7",
"Event" = "#DDCC77", # type level
"Relationship" = "#AF8DC3" # type level
)
node_legend_shapes_plot <- c(
"Person" = "dot",
"Vessel" = "triangle",
"Organization" = "square",
"Location" = "diamond",
"Group" = "circle plus",
"Event" = "star", # type level
"Relationship" = "square x" # type level
)
STYLES <- list(
node_label_dark = "black",
font_family = "Roboto Condensed"
)
# ---- 2. Prepare nodes ----
nodes <- mc3_nodes_final %>%
mutate(
label = ifelse(is.na(name), id, name),
# These parts are for pulling the related data from other fields
tooltip_extra = case_when(
type == "Event" & sub_type == "Communication" ~ content,
type == "Event" & sub_type == "Monitoring" ~ findings,
type == "Event" & sub_type == "VesselMovement" ~ destination,
type == "Event" & sub_type == "Assessment" ~ results,
type == "Relationship" & sub_type == "Coordinates" ~ coordination_type,
type == "Relationship" & sub_type == "Operates" ~ operational_role,
type == "Relationship" & sub_type == "Jurisdiction" ~ jurisdiction_type,
TRUE ~ NA_character_
),
title = paste0(
"<b>", label, "</b><br>",
"Type: ", type, "<br>",
"Sub-type: ", sub_type, "<br>",
ifelse(!is.na(tooltip_extra), paste0("<br><b>Details:</b> ", tooltip_extra), "")
),
# Fallback logic: if sub_type is NA or not in styling list, use type instead
group = ifelse(sub_type %in% names(node_legend_colors_plot), sub_type, type)
) %>%
select(id, label, group, title) %>%
distinct()
# ---- 3. Prepare directed edges (type == "sent") ----
edges <- mc3_edges_final %>%
filter(from_id %in% nodes$id & to_id %in% nodes$id) %>%
select(from = from_id, to = to_id)
# ---- 4. Build visNetwork ----
net <- visNetwork(nodes, edges, width = "100%", height = "600px") %>%
visEdges(arrows = list(to = list(enabled = TRUE, scaleFactor = 1.5))) %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE) %>%
visIgraphLayout(layout = "layout_with_fr") %>%
visNodes(font = list(
size = 14,
color = STYLES$node_label_dark,
face = STYLES$font_family,
vadjust = -15
))
# ---- 5. Apply shape and color per group ----
for (group_name in names(node_legend_colors_plot)) {
net <- net %>% visGroups(
groupname = group_name,
color = node_legend_colors_plot[[group_name]],
shape = node_legend_shapes_plot[[group_name]]
)
}
# ---- 6. Add legend ----
used_groups <- unique(nodes$group)
legend_df <- tibble::tibble(
label = used_groups,
shape = node_legend_shapes_plot[used_groups],
color = node_legend_colors_plot[used_groups]
) %>%
distinct(label, .keep_all = TRUE) # remove duplicates just in case
net <- net %>% visLegend(
addNodes = legend_df,
ncol = 2, # number of columns
position = "left",
main = "Entity (Sub)Types", # title
useGroups = FALSE # show custom legend entries
)
# ---- 7. Render ----
net
saveRDS(nodes, file = file.path("rds_objects", "nodes.rds"))
saveRDS(relationship_subtypes, file = file.path("rds_objects", "relationship_subtypes.rds"))
saveRDS(node_legend_shapes_plot, file = file.path("rds_objects", "node_legend_shapes_plot.rds"))
saveRDS(legend_df, file = file.path("rds_objects", "legend_df.rds"))
saveRDS(used_groups, file = file.path("rds_objects", "used_groups.rds"))
saveRDS(node_legend_colors_plot, file = file.path("rds_objects", "node_legend_colors_plot.rds"))
saveRDS(net, file = file.path("rds_objects", "net.rds"))
saveRDS(event_subtypes, file = file.path("rds_objects", "event_subtypes.rds"))
saveRDS(STYLES, file = file.path("rds_objects", "STYLES.rds"))
saveRDS(edges, file = file.path("rds_objects", "edges.rds"))
# ------------------
#| code-fold: true
#| code-summary: "Show the code"
# ---- 1. Define styles and legends ----
event_subtypes <- c(
"Communication", "Monitoring", "VesselMovement", "Assessment",
"Collaborate", "Endorsement", "TourActivity", "TransponderPing",
"Harbor Report", "Fishing", "Criticize"
)
relationship_subtypes <- c(
"Coordinates", "AccessPermission", "Operates", "Colleagues",
"Suspicious", "Reports", "Jurisdiction", "Unfriendly", "Friends"
)
node_legend_colors_plot <- c(
"Person" = "#88CCEE",
"Vessel" = "#D55E00",
"Organization" = "#117733",
"Location" = "#AA4499",
"Group"= "#CC79A7",
"Event" = "#DDCC77", # type level
"Relationship" = "#AF8DC3" # type level
)
node_legend_shapes_plot <- c(
"Person" = "dot",
"Vessel" = "triangle",
"Organization" = "square",
"Location" = "diamond",
"Group" = "circle plus",
"Event" = "star", # type level
"Relationship" = "square x" # type level
)
STYLES <- list(
node_label_dark = "black",
font_family = "Roboto Condensed"
)
# ---- 2. Prepare nodes ----
nodes <- mc3_nodes_final %>%
mutate(
label = ifelse(is.na(name), id, name),
# These parts are for pulling the related data from other fields
tooltip_extra = case_when(
type == "Event" & sub_type == "Communication" ~ content,
type == "Event" & sub_type == "Monitoring" ~ findings,
type == "Event" & sub_type == "VesselMovement" ~ destination,
type == "Event" & sub_type == "Assessment" ~ results,
type == "Relationship" & sub_type == "Coordinates" ~ coordination_type,
type == "Relationship" & sub_type == "Operates" ~ operational_role,
type == "Relationship" & sub_type == "Jurisdiction" ~ jurisdiction_type,
TRUE ~ NA_character_
),
title = paste0(
"<b>", label, "</b><br>",
"Type: ", type, "<br>",
"Sub-type: ", sub_type, "<br>",
ifelse(!is.na(tooltip_extra), paste0("<br><b>Details:</b> ", tooltip_extra), "")
),
# Fallback logic: if sub_type is NA or not in styling list, use type instead
group = ifelse(sub_type %in% names(node_legend_colors_plot), sub_type, type)
) %>%
select(id, label, group, title) %>%
distinct()
# ---- 3. Prepare directed edges (type == "sent") ----
edges <- mc3_edges_final %>%
filter(from_id %in% nodes$id & to_id %in% nodes$id) %>%
select(from = from_id, to = to_id)
# ---- 4. Build visNetwork ----
net <- visNetwork(nodes, edges, width = "100%", height = "600px") %>%
visEdges(arrows = list(to = list(enabled = TRUE, scaleFactor = 1.5))) %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE) %>%
visIgraphLayout(layout = "layout_with_fr") %>%
visNodes(font = list(
size = 14,
color = STYLES$node_label_dark,
face = STYLES$font_family,
vadjust = -15
))
# ---- 5. Apply shape and color per group ----
for (group_name in names(node_legend_colors_plot)) {
net <- net %>% visGroups(
groupname = group_name,
color = node_legend_colors_plot[[group_name]],
shape = node_legend_shapes_plot[[group_name]]
)
}
# ---- 6. Add legend ----
used_groups <- unique(nodes$group)
legend_df <- tibble::tibble(
label = used_groups,
shape = node_legend_shapes_plot[used_groups],
color = node_legend_colors_plot[used_groups]
) %>%
distinct(label, .keep_all = TRUE) # remove duplicates just in case
net <- net %>% visLegend(
addNodes = legend_df,
ncol = 2, # number of columns
position = "left",
main = "Entity (Sub)Types", # title
useGroups = FALSE # show custom legend entries
)
# ---- 7. Render ----
net
saveRDS(nodes, file = file.path("rds_objects", "nodes.rds"))
saveRDS(relationship_subtypes, file = file.path("rds_objects", "relationship_subtypes.rds"))
saveRDS(node_legend_shapes_plot, file = file.path("rds_objects", "node_legend_shapes_plot.rds"))
saveRDS(legend_df, file = file.path("rds_objects", "legend_df.rds"))
saveRDS(used_groups, file = file.path("rds_objects", "used_groups.rds"))
saveRDS(node_legend_colors_plot, file = file.path("rds_objects", "node_legend_colors_plot.rds"))
saveRDS(net, file = file.path("rds_objects", "net.rds"))
saveRDS(event_subtypes, file = file.path("rds_objects", "event_subtypes.rds"))
saveRDS(STYLES, file = file.path("rds_objects", "STYLES.rds"))
saveRDS(edges, file = file.path("rds_objects", "edges.rds"))
# ------------------
mc3_nodes_cleaned %>%
group_by(type, sub_type) %>%
summarize(count = n()) %>%
arrange(-count) %>%
kable()
# ------------------
# Split the 'from_id' column
mc3_edges_cleaned <- mc3_edges_cleaned %>%
separate(from_id, into = c("from_id_supertype", "from_id_sub_type", "from_id_id"), sep = "_", remove = FALSE, extra = "drop")
# Split the 'target' column into
mc3_edges_cleaned <- mc3_edges_cleaned %>%
separate(to_id, into = c("to_id_supertype", "to_id_sub_type","to_id_id"), sep = "_", remove = FALSE, extra = "drop")
# Find the number of unique types in each column
unique_counts <- mc3_edges_cleaned %>%
summarise_all(n_distinct) %>%
pivot_longer(cols = everything(), names_to = "column", values_to = "unique_count")
# Print the unique counts for each column
print(unique_counts)
saveRDS(unique_counts, file = file.path("rds_objects", "unique_counts.rds"))
saveRDS(mc3_edges_cleaned, file = file.path("rds_objects", "mc3_edges_cleaned.rds"))
# ------------------
# Check the mapping
mc3_edges_cleaned %>%
group_by(from_id_supertype, from_id_sub_type) %>%
summarize(count = n()) %>%
arrange(-count) %>%
kable()
# Check the mapping
mc3_edges_cleaned %>%
group_by(to_id_supertype, to_id_sub_type) %>%
summarize(count = n()) %>%
arrange(-count) %>%
kable()
# ------------------
# checking for duplicates
duplicate_values1 <- mc3_nodes_cleaned %>%
count(content) %>%
filter(n > 1)
# View duplicates
print(duplicate_values1)
saveRDS(duplicate_values1, file = file.path("rds_objects", "duplicate_values1.rds"))
# ------------------
# --- 1. Extract All Communications ---
# Logic: Sender (source) --sent--> Event_Communication (target) --received--> Recipient (target)
# This extracts all communication events
# --- 2. Clean and Prepare Nodes ---
mc3_nodes_cleaned <- mc3_nodes_raw %>%
mutate(id = as.character(id)) %>%
filter(!is.na(id)) %>%
distinct(id, .keep_all = TRUE) %>%
# Rename 'type' to 'supertype' to reduce confusion with communication type
rename(supertype = type) %>%
# Select only columns that are needed and are consistently present
select(id, name, sub_type, content, timestamp)
# --- 3. Clean and Prepare Edges ---
# Rename 'type' in edges to 'edge_type' to avoid conflict with node 'supertype'
mc3_edges_cleaned <- mc3_edges_raw %>%
rename(from_id = source,
to_id = target,
edge_type = type) %>% # Renamed 'type' to 'edge_type'
mutate(across(c(from_id, to_id), as.character)) %>%
# Filter out any edges where from_id or to_id are not in cleaned nodes
filter(from_id %in% mc3_nodes_cleaned$id,
to_id %in% mc3_nodes_cleaned$id)
other_communications_df <- mc3_edges_cleaned %>%
filter(edge_type == "sent") %>% # Start with 'sent' edges
# Join with nodes to get content and timestamp of the Event_Communication node
left_join(mc3_nodes_cleaned %>% select(id, content, timestamp),
by = c("to_id" = "id")) %>%
rename(event_id = to_id, event_content = content, event_timestamp = timestamp) %>%
# Now, find the recipient of this communication event
left_join(mc3_edges_cleaned %>%
filter(edge_type == "received") %>%
select(event_id_match = from_id, recipient_id = to_id),
by = c("event_id" = "event_id_match")) %>%
# Join with nodes to get the sender's name and sub_type
left_join(mc3_nodes_cleaned %>% select(id, name, sub_type),
by = c("from_id" = "id")) %>%
rename(sender_id_actual = from_id, sender_name = name, sender_sub_type = sub_type) %>%
# Join with nodes to get the recipient's name and sub_type
left_join(mc3_nodes_cleaned %>% select(id, name, sub_type),
by = c("recipient_id" = "id")) %>%
rename(recipient_name = name, recipient_sub_type = sub_type) %>%
# Select and rename final columns for all communications
select(
communication_type = edge_type, # This will be "sent" from original filter
sender_id = sender_id_actual,
sender_name,
sender_sub_type,
recipient_id,
recipient_name,
recipient_sub_type,
event_id,
content = event_content,
timestamp = event_timestamp
)
# create a timeline visualization or inspect content.
print(knitr::kable(head(other_communications_df %>%
select(timestamp, sender_name,
recipient_name, content), 10),
format = "markdown", align = "l"))
saveRDS(mc3_edges_cleaned, file = file.path("rds_objects", "mc3_edges_cleaned.rds"))
saveRDS(other_communications_df, file = file.path("rds_objects", "other_communications_df.rds"))
saveRDS(mc3_nodes_cleaned, file = file.path("rds_objects", "mc3_nodes_cleaned.rds"))
# ------------------
# --- Step 1: Build communication matrix ---
sent_df <- other_communications_df %>%
filter(communication_type == "sent") %>%
count(sender_name, recipient_name, name = "sent")
received_df <- other_communications_df %>%
filter(communication_type == "received") %>%
count(sender_name = recipient_name, recipient_name = sender_name, name = "received")
combined_df <- full_join(sent_df, received_df, by = c("sender_name", "recipient_name")) %>%
mutate(across(c(sent, received), ~replace_na(., 0)),
total = sent + received)
comm_matrix <- xtabs(total ~ sender_name + recipient_name, data = combined_df)
# --- Step 2: Assign color per entity sub-type ---
type_lookup <- other_communications_df %>%
select(name = sender_name, type = sender_sub_type) %>%
bind_rows(other_communications_df %>% select(name = recipient_name, type = recipient_sub_type)) %>%
distinct(name, .keep_all = TRUE)
# Define pastel Set2 colors for each type
type_colors_palette <- brewer.pal(n = 4, name = "Set2")
names(type_colors_palette) <- c("Person", "Organization", "Vessel", "Location")
# Map to nodes in the matrix
grid_colors <- type_colors_palette[type_lookup$type]
names(grid_colors) <- type_lookup$name
grid_colors <- grid_colors[rownames(comm_matrix)]
# --- Step 3: Plot chord diagram ---
circos.clear()
par(mar = c(4, 2, 8, 10)) # bottom, left, top, right
chordDiagram(
comm_matrix,
grid.col = grid_colors,
transparency = 0.25,
annotationTrack = "grid",
preAllocateTracks = list(track.height = 0.1)
)
# Add readable sector names
circos.trackPlotRegion(
track.index = 1,
panel.fun = function(x, y) {
name <- get.cell.meta.data("sector.index")
circos.text(
x = mean(get.cell.meta.data("xlim")),
y = 0,
labels = str_wrap(name, 10),
facing = "clockwise",
niceFacing = TRUE,
adj = c(0, 0.5),
cex = 0.6
)
},
bg.border = NA
)
# --- Step 4: Title, subtitle ---
title(
main = "Chord Diagram of Communication Flows",
cex.main = 1.6,
font.main = 2,
line = 5
)
mtext("Each ribbon shows volume of sent + received messages", side = 3, line = 3, cex = 1, col = "gray30")
mtext("Note. Group subtype is excluded from this diagram", side = 1, line = 3, cex = 0.8, col = "gray40")
# --- Step 5: Custom Legend ---
legend_items <- names(type_colors_palette)
legend(
x = 1.1, y = 0.85, legend = legend_items,
fill = type_colors_palette,
border = "gray30",
bty = "n",
cex = 0.7,
pt.cex = 0.7,
title = "Entity Sub-Type"
)
saveRDS(combined_df, file = file.path("rds_objects", "combined_df.rds"))
saveRDS(sent_df, file = file.path("rds_objects", "sent_df.rds"))
saveRDS(received_df, file = file.path("rds_objects", "received_df.rds"))
saveRDS(grid_colors, file = file.path("rds_objects", "grid_colors.rds"))
saveRDS(comm_matrix, file = file.path("rds_objects", "comm_matrix.rds"))
saveRDS(type_colors_palette, file = file.path("rds_objects", "type_colors_palette.rds"))
#saveRDS(name, file = file.path("rds_objects", "name.rds"))
saveRDS(legend_items, file = file.path("rds_objects", "legend_items.rds"))
saveRDS(type_lookup, file = file.path("rds_objects", "type_lookup.rds"))
# ------------------
# Step 1: Count interactions
adj_df <- other_communications_df %>%
count(sender_name, recipient_name, name = "count")
# Step 2: Compute total sent and received counts
sender_order <- adj_df %>%
group_by(sender_name) %>%
summarise(total_sent = sum(count)) %>%
arrange(desc(total_sent)) %>%
pull(sender_name)
recipient_order <- adj_df %>%
group_by(recipient_name) %>%
summarise(total_received = sum(count)) %>%
arrange(desc(total_received)) %>%
pull(recipient_name)
# Step 3: Reorder factor levels
adj_df <- adj_df %>%
mutate(
sender_name = factor(sender_name, levels = sender_order),
recipient_name = factor(recipient_name, levels = recipient_order)
)
# Step 4: Plot heatmap
ggplot(adj_df, aes(x = recipient_name, y = sender_name, fill = count)) +
geom_tile(color = "white") +
scale_fill_gradient(low = "white", high = "navyblue") +
labs(
title = "Sender-Recipient Communication Heatmap",
subtitle = "Top communicators sorted to bottom-left",
x = "Recipient",
y = "Sender",
fill = "Messages"
) +
theme_minimal(base_size = 10) +
theme(
axis.text.x = element_text(angle = 45, hjust = 1),
plot.title = element_text(size = 12, face = "bold"),
plot.subtitle = element_text(size = 10),
panel.grid = element_blank()
)
saveRDS(recipient_order, file = file.path("rds_objects", "recipient_order.rds"))
saveRDS(adj_df, file = file.path("rds_objects", "adj_df.rds"))
saveRDS(sender_order, file = file.path("rds_objects", "sender_order.rds"))
# ------------------
sender_names_by_type <- other_communications_df %>%
group_by(sender_sub_type) %>%
summarise(
unique_senders = n_distinct(sender_name),
sender_names = paste(sort(unique(sender_name)), collapse = ", ")
) %>%
arrange(desc(unique_senders)) # sort from largest to smallest
# View the table
print(sender_names_by_type)
saveRDS(sender_names_by_type, file = file.path("rds_objects", "sender_names_by_type.rds"))
# ------------------
person_vessel_df <- other_communications_df %>%
filter(
(sender_sub_type == "Person" & recipient_sub_type == "Vessel") |
(sender_sub_type == "Vessel" & recipient_sub_type == "Person") |
(sender_sub_type == "Person" & recipient_sub_type == "Person") |
(sender_sub_type == "Vessel" & recipient_sub_type == "Vessel")
)
saveRDS(person_vessel_df, file = file.path("rds_objects", "person_vessel_df.rds"))
# ------------------
#| code-fold: true
#| code-summary: "Show the code"
# --- FACTORING and DATETIME CLEANING ---
person_vessel_df_for_plot <- person_vessel_df %>%
mutate(
timestamp = as.POSIXct(timestamp),
comm_date = as.Date(timestamp),
comm_time_of_day = hms::as_hms(format(timestamp, "%H:%M:%S")),
sender_sub_type = factor(sender_sub_type, levels = c("Person", "Vessel")),
communicating_pair_sorted = paste(pmin(sender_name, recipient_name), pmax(sender_name, recipient_name), sep = " & ")
)
# --- WRAPPING CONTENT AND TOOLTIP ---
plot_data1 <- person_vessel_df_for_plot %>%
mutate(
timestamp = as.POSIXct(timestamp),
date = as.Date(timestamp),
time = format(timestamp, "%H:%M:%S"),
wrapped_content = str_wrap(content, width = 50),
tooltip_text = paste0(
"<b>Date:</b> ", date, "<br>",
"<b>Time:</b> ", time, "<br>",
"<b>From:</b> ", sender_name, "<br>",
"<b>To:</b> ", recipient_name, "<br>",
"<b>Event_id:</b> ", event_id, "<br><br>",
"<b>Content:</b><br>", wrapped_content
)
)
# Plot
p <-ggplot(plot_data1, aes(x = comm_date, y = comm_time_of_day)) +
geom_point(aes(
color = sender_id,
shape = sender_sub_type,
text = tooltip_text
),show.legend = c(color = TRUE, shape = FALSE),
size = 2, alpha = 0.7) +
scale_shape_manual(values = c("Person" = 16, "Vessel" = 17)) +
facet_wrap(~ sender_sub_type, ncol = 1, scales = "fixed") +
scale_y_time(
limits = hms::as_hms(c("08:00:00", "14:00:00")), # reversed to show time top-to-bottom
breaks = hms::as_hms(c("08:00:00", "09:00:00", "10:00:00", "11:00:00", "12:00:00", "13:00:00", "14:00:00")),
labels = c("08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00")
)+
scale_x_date(
date_breaks = "1 day",
date_labels = "%d %b"
)+
labs(
title = "Communication Events Over Time (Sender's Perspective)",
x = "Date",
y = "Time of Day",
color = "Sender (subtype, name)"
) +
theme_grey() +
theme(
axis.text.y = element_text(size = 6),
axis.title.y = element_text(size = 7),
axis.ticks.y = element_line(),
axis.text.x = element_text(size = 6, angle = 45, hjust = 1),
axis.title.x = element_text(margin = margin(t = 8), size = 7),
panel.spacing = unit(0.5, "lines"), # Applies to both x and y spacing
strip.text = element_text(size = 8, face = "bold"),
legend.position = "bottom",
legend.text = element_text(size = 6),
legend.title = element_blank()
)
# --- Convert to interactive plot ---
ggplotly(p, tooltip = "tooltip_text")
saveRDS(plot_data1, file = file.path("rds_objects", "plot_data1.rds"))
saveRDS(p, file = file.path("rds_objects", "p.rds"))
saveRDS(person_vessel_df_for_plot, file = file.path("rds_objects", "person_vessel_df_for_plot.rds"))