# install.packages(c("dodgr", "igraph", "ggraph", "ggplot2")) # run once if needed library(dodgr) library(igraph) library(ggraph) library(ggplot2) ## 1. Define the tree as a directed graph (X upstream of A) # X # | # A # / \ # B C # / \ / \ # D E F G graph <- data.frame( edge_id = 1:7, from = c("X", "A","A", "B","B", "C","C"), to = c("A", "B","C", "D","E", "F","G"), weight = rep(1, 7), # used by dodgr for routing distance = rep(1, 7) # distance-like metric ) ## 2. Define OD flows at the leaf nodes (demands at D, E, F, G) from <- "X" # origin (root) to <- c("D", "E", "F", "G") # leaves flows <- matrix(c(5, 5, 10, 10), # X->D, X->E, X->F, X->G nrow = length(from)) ## 3. Use dodgr to aggregate flows on each edge agg <- dodgr_flows_aggregate( graph = graph, from = from, to = to, flows = flows, contract = FALSE, norm_sums = FALSE # keep raw flow sums (not normalised) ) ## 4. Compute pressure drop per edge from the flows # Simple model: ΔP_e = R_e * Q_e^2 # Here we just set R_e = 1 Pa / (flow_unit^2) for all edges # (You’d normally use real R values from duct calcs) agg$R_coeff <- 1 agg$dp_edge_Pa <- agg$R_coeff * agg$flow^2 # Quick check in console print(agg[, c("edge_id", "from", "to", "flow", "dp_edge_Pa")]) ## 5. Build an igraph object with attributes for plotting g <- graph_from_data_frame( d = agg[, c("from", "to", "flow", "dp_edge_Pa")], directed = TRUE ) ## 6. Plot the tree with edge labels (flow + ΔP) and save as PDF # Create the plot object p <- ggraph(g, layout = "tree") + # edges with labels: show flow and ΔP on each edge geom_edge_link(aes( label = paste0("Q=", flow, "\nΔP=", round(dp_edge_Pa, 2), " Pa") ), angle_calc = "along", label_dodge = unit(2, "mm"), label_size = 3 ) + geom_node_point(size = 4) + geom_node_text(aes(label = name), vjust = -1, size = 4) + theme_void() + ggtitle("Tree with Flows and Pressure Drops") # Save to PDF in your working directory ggsave("tree_flows.pdf", p, width = 6, height = 8) # After running this script, check your working directory for "tree_flows.pdf"