library(igraph) library(DiagrammeR) library(DiagrammeRsvg) library(rsvg) # 1) Read data edges <- read.csv("edges.csv", stringsAsFactors = FALSE) nodes <- read.csv("nodes.csv", stringsAsFactors = FALSE) # 2) Build graph (root -> leaves) g <- graph_from_data_frame(edges, directed = TRUE, vertices = nodes) # 3) Put demand on vertices (0 for non-terminals) V(g)$demand_lps <- ifelse(is.na(V(g)$demand_lps), 0, V(g)$demand_lps) # 4) Topological order (works for a tree/DAG) ord <- topo_sort(g, mode = "out") # root first, leaves last # 5) Accumulate from leaves back to root V(g)$acc_lps <- V(g)$demand_lps for (v in rev(ord)) { kids <- neighbors(g, v, mode = "out") # downstream nodes if (length(kids) > 0) { V(g)$acc_lps[v] <- V(g)$acc_lps[v] + sum(V(g)$acc_lps[kids]) } } # 6) Edge flow = accumulated flow at the downstream end ("to" node) E(g)$acc_lps <- V(g)$acc_lps[ head_of(g, E(g)) ] # head_of = edge "to" in a directed graph # 7) Write results (optional) out_edges <- as_data_frame(g, what = "edges") out_edges$acc_lps <- E(g)$acc_lps write.csv(out_edges, "edges_with_accumulated_flow.csv", row.names = FALSE) # 8) Plot to PDF with accumulated flow labels (optional) pdf("graph_accumulated2.pdf", width = 10, height = 8) plot( g, layout = layout_as_tree(g)*10, vertex.size = 5, vertex.label = V(g)$name, edge.arrow.size = 0.6, edge.label = paste0(round(E(g)$acc_lps, 1), " l/s"), edge.label.cex = 0.8 ) dev.off() cat("Wrote edges_with_accumulated_flow.csv and graph_accumulated.pdf\n") # 2) Write DOT file write_graph(g, file = "network.dot", format = "dot") #dot_file <- tempfile(fileext = ".dot") #write_graph(g, file = dot_file, format = "dot") # 3) Read DOT text and create DiagrammeR graph object #dot_text <- paste(readLines("network.dot"), collapse = "\n") #gr <- grViz(dot_text) # 4) Export to PDF #svg_txt <- export_svg(gr) #rsvg_pdf(charToRaw(svg_txt), file = "tree_output.pdf")