rm(list=ls())
library("data.table")
library("DiagrammeR")
library("ggplot2")
agent_dt <- fread("~/Coding/khanna-research/cadre/python/output/agent_log_1.csv")
network_dt <- fread("~/Coding/khanna-research/cadre/python/output/network_log_1.csv")
last_tick <- max(network_dt$tick)
last_tick_network_dt <- network_dt[tick==last_tick,]
last_tick_agent_dt <- agent_dt[tick == last_tick,]
# get the ids of agents released in the last year
ever_incarcerated_agents <- last_tick_agent_dt$id[last_tick_agent_dt$last_incarceration_tick != -1]
length(ever_incarcerated_agents)
## [1] 555
# Get the network data for the recently released agents
network_ever_incarcerated <- last_tick_network_dt[(last_tick_network_dt$p1 %in% ever_incarcerated_agents) |
(last_tick_network_dt$p2 %in% ever_incarcerated_agents),]
nrow(network_ever_incarcerated) # number of connections of recently released
## [1] 2152
# get ids of all first degree neighbors
first_degree_neighbors <- unique(c(network_ever_incarcerated$p1, network_ever_incarcerated$p2))
# agent data for first degree neighbors
neighbors_agent_data <- last_tick_agent_dt[last_tick_agent_dt$id %in% first_degree_neighbors,]
# create data frame to hold edges from network data
edge_df <- data.frame(from = network_ever_incarcerated$p1, to = network_ever_incarcerated$p2)
# create data frame to hold nodes
node_df <- data.frame(id = neighbors_agent_data$id,
incarceration_status = neighbors_agent_data$current_incarceration_status,
ever_incarcerated = ifelse(neighbors_agent_data$id %in% ever_incarcerated_agents, "yes", "no")
)
# create graph
graph <- create_graph(nodes_df = node_df,
edges_df = edge_df,
directed = FALSE)
graph <- set_node_attrs(graph, "fillcolor", ifelse(node_df$incarceration_status == 1, "purple", ifelse(node_df$ever_incarcerated == "yes", "black", "white")))
graph <- set_node_attrs(graph, "shape", ifelse(node_df$ever_incarcerated == "yes", "square", "circle"))
graph <- set_node_attrs(graph, "label", "")
graph <- set_node_attrs(graph, "color", "black")
graph <- set_edge_attrs(graph, "color", "black")
graph <- set_edge_attrs(graph, "style", "solid")
graph <- set_edge_attrs(graph, "penwidth", 2)
# Render the graph
render_graph(graph, width = 800, height = 800)
legend <- rbind(data.frame(group = "Ever Incarcerated", shape = "square", color = "black"),
data.frame(group = "Currently Incarcerated", shape = "square", color = "purple"))
p <- ggplot() +
geom_point(data = legend,
aes(x = 1, y = group, color = color, fill = color, shape = shape),
size = 5) +
geom_text(data = legend,
aes(x = 1.1, y = group, label = group),
hjust = 0) +
scale_color_identity() +
scale_fill_identity() +
scale_shape_manual(values=c("square"=22, "circle"=21)) +
theme_void() +
theme(legend.position = "none") +
coord_cartesian(xlim = c(1, 2))
p
