Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-27 09:45:45

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2024, EICrecon contributors
0003 
0004 #include "JEventProcessorCallGraph.h"
0005 
0006 #include <JANA/JApplication.h>
0007 #include <JANA/JApplicationFwd.h>
0008 #include <JANA/JEvent.h>
0009 #include <JANA/JFactory.h>
0010 #include <JANA/JFactorySet.h>
0011 #include <JANA/Services/JParameterManager.h>
0012 #include <JANA/Utils/JCallGraphRecorder.h>
0013 #include <fmt/format.h>
0014 #include <algorithm>
0015 #include <chrono>
0016 #include <cmath>
0017 #include <cstddef>
0018 #include <format>
0019 #include <fstream>
0020 #include <initializer_list>
0021 #include <iomanip>
0022 #include <memory>
0023 #include <ratio>
0024 #include <sstream>
0025 #include <utility>
0026 
0027 #include "services/log/Log_service.h"
0028 
0029 void JEventProcessorCallGraph::Init() {
0030   m_log = GetApplication()->GetService<Log_service>()->logger("callgraph");
0031 
0032   // Get parameter manager
0033   auto params = GetApplication()->GetJParameterManager();
0034 
0035   // Set default parameter values and register them
0036   output_filename = "callgraph.dot";
0037   params->SetDefaultParameter("callgraph:output_file", output_filename, "Output DOT filename");
0038 
0039   enable_splitting = true;
0040   params->SetDefaultParameter("callgraph:enable_splitting", enable_splitting,
0041                               "Enable splitting graphs into multiple files by plugin");
0042 
0043   // Check for callgraph:group parameters (command line group definitions)
0044   // These override the default plugin-based group assignment
0045   std::map<std::string, std::string> parameter_keys;
0046   params->FilterParameters(parameter_keys, "callgraph:group:");
0047   for (const auto& [group_name, group_definition] : parameter_keys) {
0048     // Parse command line group definition similar to file format
0049     std::vector<std::string> factories;
0050     std::string color = "lightblue"; // default color
0051 
0052     std::stringstream ss(group_definition);
0053     std::string item;
0054     while (std::getline(ss, item, ',')) {
0055       // Trim surrounding whitespace, e.g. "Type:Tag1, Type:Tag2, color_blue"
0056       std::size_t first = item.find_first_not_of(" \t");
0057       if (first == std::string::npos) {
0058         continue; // all whitespace
0059       }
0060       std::size_t last = item.find_last_not_of(" \t");
0061       item             = item.substr(first, last - first + 1);
0062 
0063       if (item.find("color_") == 0) {
0064         color = item.substr(6); // remove "color_" prefix
0065       } else if (!item.empty()) {
0066         factories.push_back(item);
0067       }
0068     }
0069 
0070     user_group_colors[group_name] = color;
0071 
0072     // Build nametag to group mapping (overrides plugin-based assignment).
0073     // Each factory spec is "Tag" or "Type:Tag" (the type itself may contain "::",
0074     // so split on the last ':'). This map is later looked up by the nametags that
0075     // MakeNametag() makes from the call graph: "tag (type)" for factories with an
0076     // object name (JFactoryT-based ones), but just "tag" for the others, which
0077     // include every JOmniFactory, so register both forms.
0078     for (const auto& factory : factories) {
0079       auto colon_pos        = factory.rfind(':');
0080       std::string type_part = (colon_pos == std::string::npos) ? "" : factory.substr(0, colon_pos);
0081       std::string tag_part =
0082           (colon_pos == std::string::npos) ? factory : factory.substr(colon_pos + 1);
0083       std::string nametag        = MakeNametag(type_part, tag_part);
0084       nametag_to_group[nametag]  = group_name;
0085       nametag_to_group[tag_part] = group_name;
0086       user_group_entries.push_back({group_name, factory, {nametag, tag_part}});
0087     }
0088   }
0089 
0090   // Add default group assignments for special factories
0091   // podio::Frame is a PODIO framework factory that has no plugin name
0092   nametag_to_group["podio::Frame"] = "processors";
0093 }
0094 
0095 void JEventProcessorCallGraph::Process(const std::shared_ptr<const JEvent>& event) {
0096   // Get the call stack for this event and add the results to our stats
0097   auto stack = event->GetJCallGraphRecorder()->GetCallGraph();
0098 
0099   // Lock mutex in case we are running with multiple threads
0100   std::lock_guard<std::mutex> lck(mutex);
0101   ++event_count; // reported in the legend
0102 
0103   // Build mapping of nametags to plugin names (only do this once per instance)
0104   if (!factory_mapping_built) {
0105     auto factories = event->GetFactorySet()->GetAllFactories();
0106 
0107     for (auto* factory : factories) {
0108       std::string nametag     = MakeNametag(factory->GetObjectName(), factory->GetTag());
0109       std::string plugin_name = factory->GetPluginName();
0110 
0111       // If plugin name is empty, use "core" as default
0112       if (plugin_name.empty()) {
0113         plugin_name = "core";
0114       }
0115 
0116       nametag_to_plugin[nametag] = plugin_name;
0117     }
0118 
0119     // Group tags by finding sets of tags that share a common prefix
0120     // where the common prefix exactly matches one of the tags in the set
0121     std::map<std::string, std::vector<std::string>> prefix_to_tags;
0122     std::vector<std::string> all_helper_tags;
0123     std::set<std::string> processed_tags;
0124 
0125     for (auto* factory : factories) {
0126       std::string factory_name = factory->GetFactoryName();
0127       std::string factory_tag  = factory->GetTag();
0128 
0129       // Helper factories can legitimately have an empty tag. An empty string
0130       // is a "prefix" of every other string (find("") == 0), so including it
0131       // here would collapse every helper tag into a single bogus group.
0132       if (factory_name.find("::Helper<") != std::string::npos && !factory_tag.empty()) {
0133         all_helper_tags.push_back(factory_tag);
0134       }
0135     }
0136 
0137     // Sort tags by length (shortest first) to ensure prefixes come before their extensions,
0138     // with a lexical tie-breaker so equal-length tags sort deterministically across runs.
0139     std::sort(all_helper_tags.begin(), all_helper_tags.end(),
0140               [](const std::string& a, const std::string& b) {
0141                 if (a.length() != b.length())
0142                   return a.length() < b.length();
0143                 return a < b;
0144               });
0145 
0146     // Group tags by finding their longest common prefix
0147     // For each pair/group of tags that share a common prefix, group them together
0148     for (std::size_t i = 0; i < all_helper_tags.size(); ++i) {
0149       if (processed_tags.count(all_helper_tags[i]))
0150         continue;
0151 
0152       std::vector<std::string> group;
0153       group.push_back(all_helper_tags[i]);
0154 
0155       // Find all tags that differ from all_helper_tags[i] only in a suffix
0156       for (std::size_t j = i + 1; j < all_helper_tags.size(); ++j) {
0157         if (processed_tags.count(all_helper_tags[j]))
0158           continue;
0159 
0160         // Check if one tag is a prefix of the other, OR they share all but the last word
0161         // Strategy: one should start with the other, OR they should be identical except for a suffix
0162         bool should_group = false;
0163 
0164         // Case 1: tag j starts with tag i (tag i is a prefix)
0165         if (all_helper_tags[j].find(all_helper_tags[i]) == 0) {
0166           should_group = true;
0167         }
0168         // Case 2: they share a common prefix and differ only at the end
0169         else {
0170           // Find common prefix
0171           std::size_t k = 0;
0172           while (k < all_helper_tags[i].length() && k < all_helper_tags[j].length() &&
0173                  all_helper_tags[i][k] == all_helper_tags[j][k]) {
0174             ++k;
0175           }
0176 
0177           // They should share at least 90% of the shorter tag's length
0178           std::size_t min_len = std::min(all_helper_tags[i].length(), all_helper_tags[j].length());
0179           if (k >= min_len * 0.9 && k >= 15) {
0180             should_group = true;
0181           }
0182         }
0183 
0184         if (should_group) {
0185           group.push_back(all_helper_tags[j]);
0186           processed_tags.insert(all_helper_tags[j]);
0187         }
0188       }
0189 
0190       if (group.size() > 1) {
0191         // Use the first tag (shortest) as the factory_id
0192         prefix_to_tags[all_helper_tags[i]] = group;
0193         processed_tags.insert(all_helper_tags[i]);
0194       }
0195     }
0196 
0197     // Build tag_to_factory_id mapping
0198     std::map<std::string, std::string> tag_to_factory_id;
0199     for (const auto& [prefix, tags] : prefix_to_tags) {
0200       for (const auto& tag : tags) {
0201         tag_to_factory_id[tag] = prefix;
0202       }
0203     }
0204 
0205     // Map each nametag to its factory_id
0206     for (auto* factory : factories) {
0207       std::string nametag     = MakeNametag(factory->GetObjectName(), factory->GetTag());
0208       std::string factory_tag = factory->GetTag();
0209       // Default to tag, but an empty tag is valid (MakeNametag falls back to
0210       // the object name); use the nametag then so distinct such factories
0211       // don't collapse into a single "" factory_id.
0212       std::string factory_id = factory_tag.empty() ? nametag : factory_tag;
0213 
0214       // Check if this tag has a factory_id mapping (from prefix grouping)
0215       auto it = tag_to_factory_id.find(factory_tag);
0216       if (it != tag_to_factory_id.end()) {
0217         factory_id = it->second;
0218       }
0219 
0220       // Track all output tags for this factory_id. An empty tag is valid (see
0221       // above), but storing "" here would later render as a blank line in the
0222       // "Outputs:" list, so fall back to factory_id for the stored value too.
0223       std::string output_tag = factory_tag.empty() ? factory_id : factory_tag;
0224       if (factory_outputs.find(factory_id) == factory_outputs.end()) {
0225         factory_outputs[factory_id] = {output_tag};
0226       } else {
0227         auto& tags = factory_outputs[factory_id];
0228         if (std::find(tags.begin(), tags.end(), output_tag) == tags.end()) {
0229           tags.push_back(output_tag);
0230         }
0231       }
0232 
0233       // Map this nametag to the factory_id for grouping
0234       nametag_to_factory_id[nametag] = factory_id;
0235     }
0236 
0237     // GetAllFactories() iteration order isn't guaranteed stable, so sort each
0238     // factory's output tags to keep the generated DOT/SVG output deterministic.
0239     for (auto& [factory_id, tags] : factory_outputs) {
0240       std::sort(tags.begin(), tags.end());
0241     }
0242 
0243     factory_mapping_built = true;
0244   }
0245 
0246   // Loop over the call stack elements and add in the values
0247   for (std::size_t i = 0; i < stack.size(); ++i) {
0248 
0249     // Keep track of total time each factory spent waiting and being waited on
0250     std::string nametag1 = MakeNametag(stack[i].caller_name, stack[i].caller_tag);
0251     std::string nametag2 = MakeNametag(stack[i].callee_name, stack[i].callee_tag);
0252 
0253     FactoryCallStats& fcallstats1 = factory_stats[nametag1];
0254     FactoryCallStats& fcallstats2 = factory_stats[nametag2];
0255 
0256     // Determine node types
0257     fcallstats1.type = GetNodeType(stack[i].caller_name, stack[i].caller_tag);
0258     fcallstats2.type = GetNodeType(stack[i].callee_name, stack[i].callee_tag);
0259 
0260     // Use a floating-point duration so calls shorter than 1ms still contribute
0261     // their actual time instead of being truncated to 0.
0262     auto delta_t_ms =
0263         std::chrono::duration<double, std::milli>(stack[i].end_time - stack[i].start_time).count();
0264     fcallstats1.time_waiting += delta_t_ms;
0265     fcallstats2.time_waited_on += delta_t_ms;
0266 
0267     // Get pointer to CallStats object representing this calling pair
0268     CallLink link;
0269     link.caller_name = stack[i].caller_name;
0270     link.caller_tag  = stack[i].caller_tag;
0271     link.callee_name = stack[i].callee_name;
0272     link.callee_tag  = stack[i].callee_tag;
0273     CallStats& stats =
0274         call_links[link]; // get pointer to stats object or create if it doesn't exist
0275 
0276     switch (stack[i].data_source) {
0277     case JCallGraphRecorder::DATA_NOT_AVAILABLE:
0278       stats.Ndata_not_available++;
0279       stats.data_not_available_ms += delta_t_ms;
0280       break;
0281     case JCallGraphRecorder::DATA_FROM_CACHE:
0282       fcallstats2.Nfrom_cache++;
0283       stats.Nfrom_cache++;
0284       stats.from_cache_ms += delta_t_ms;
0285       break;
0286     case JCallGraphRecorder::DATA_FROM_SOURCE:
0287       fcallstats2.Nfrom_source++;
0288       stats.Nfrom_source++;
0289       stats.from_source_ms += delta_t_ms;
0290       break;
0291     case JCallGraphRecorder::DATA_FROM_FACTORY:
0292       fcallstats2.Nfrom_factory++;
0293       stats.Nfrom_factory++;
0294       stats.from_factory_ms += delta_t_ms;
0295       break;
0296     }
0297   }
0298 }
0299 
0300 void JEventProcessorCallGraph::Finish() { WriteDotFile(); }
0301 
0302 void JEventProcessorCallGraph::WriteGraphLabel(std::ostream& ofs, const std::string& title,
0303                                                graph_type type) {
0304   // The graph label holds the title and a legend defining the quantities in the
0305   // node and edge labels. Unlike a legend node, it takes no part in the layout.
0306   // Each legend row is a term and the lines of its definition.
0307   std::vector<std::pair<std::string, std::vector<std::string>>> rows;
0308   if (type == kOverviewGraph) {
0309     rows.push_back({"node",
0310                     {
0311                         user_group_colors.empty()
0312                             ? "one box per plugin"
0313                             : "one box per plugin or user-defined group (colored border)",
0314                         "label: name, number of factories, plugin time (% of T)",
0315                         "click it to open its graph",
0316                     }});
0317     rows.push_back({"A -&gt; B",
0318                     {
0319                         "factories in A requested data from factories in B",
0320                         "label: calls, edge time (% of T), summed over these requests",
0321                     }});
0322     rows.push_back({"plugin time",
0323                     {
0324                         "sum of the self times of its factories",
0325                         "= sum of incoming edge times - sum of outgoing edge times",
0326                         "(requests between factories in the same plugin cancel out)",
0327                     }});
0328   } else {
0329     rows.push_back(
0330         {"node",
0331          {
0332              "label: name, Outputs (if several), Inputs (in this graph), self time (% of T)",
0333              "box: factory, ellipse: event processor or other,",
0334              "diamond: cache, trapezium: event source",
0335          }});
0336     rows.push_back({"A -&gt; B",
0337                     {
0338                         "A requested data from B",
0339                         "label: calls, edge time (% of T)",
0340                     }});
0341   }
0342   rows.push_back({"self time",
0343                   {
0344                       "time spent in a node's own code, not waiting for its inputs",
0345                       "= sum of incoming edge times - sum of outgoing edge times.",
0346                       "Not measured for event processors (shown as 0);",
0347                       "the edges leaving them add up to T.",
0348                   }});
0349   rows.push_back({"edge time",
0350                   {
0351                       "time the caller waited for the requested data, summed over all calls.",
0352                       "A factory runs once per event, for the first request; that request's time",
0353                       "includes the factory's self time and all of its outgoing edges, while",
0354                       "later requests are served from cache and add almost nothing.",
0355                   }});
0356   rows.push_back({"calls", {"number of requests, including those served from cache"}});
0357   rows.push_back({"T = 100%",
0358                   {
0359                       std::format("{}, the self time of all nodes in all plugins,",
0360                                   MakeTimeString(GetTotalSelfTime())),
0361                       std::format("summed over {} events (on all threads)", event_count),
0362                   }});
0363   if (type == kPluginGraph) {
0364     rows.push_back({"not drawn",
0365                     {
0366                         "requests to or from other plugins (see the overview graph);",
0367                         "they still count in the sums above",
0368                     }});
0369   }
0370   // Node fill colors, drawn with the same mapping the nodes use
0371   std::string swatches = "<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\"><TR>";
0372   for (int percent : {0, 25, 50, 75, 100}) {
0373     swatches +=
0374         std::format("<TD BGCOLOR=\"{}\">{}%</TD>", GetNodeColorFromPercent(percent), percent);
0375   }
0376   swatches += "</TR></TABLE>";
0377   rows.push_back({"node fill", {swatches}});
0378   rows.push_back({"edge width", {"from 1 (0%) to 8 (100%)"}});
0379 
0380   ofs << "  fontname=\"Arial\";" << '\n';
0381   ofs << "  fontsize=10;" << '\n';
0382   ofs << "  labelloc=\"t\";" << '\n';
0383   ofs << "  labeljust=\"l\";" << '\n';
0384   ofs << "  label=<<TABLE BORDER=\"0\" CELLSPACING=\"4\">" << '\n';
0385   ofs << "    <TR><TD ALIGN=\"LEFT\"><FONT POINT-SIZE=\"16\">" << EscapeForHtml(title)
0386       << "</FONT></TD></TR>" << '\n';
0387   ofs << "    <TR><TD ALIGN=\"LEFT\"><TABLE BORDER=\"1\" CELLBORDER=\"0\" CELLSPACING=\"0\" "
0388          "CELLPADDING=\"3\" COLOR=\"gray50\">"
0389       << '\n';
0390   ofs << "      <TR><TD COLSPAN=\"2\" ALIGN=\"LEFT\"><B>Legend</B></TD></TR>" << '\n';
0391   for (const auto& [term, lines] : rows) {
0392     ofs << "      <TR><TD ALIGN=\"LEFT\" VALIGN=\"TOP\"><B>" << term
0393         << "</B></TD><TD ALIGN=\"LEFT\" BALIGN=\"LEFT\">";
0394     for (std::size_t i = 0; i < lines.size(); ++i) {
0395       ofs << (i > 0 ? "<BR/>" : "") << lines[i];
0396     }
0397     ofs << "</TD></TR>" << '\n';
0398   }
0399   ofs << "    </TABLE></TD></TR>" << '\n';
0400   ofs << "  </TABLE>>;" << '\n';
0401 }
0402 
0403 void JEventProcessorCallGraph::WriteDotFile() {
0404   if (enable_splitting) {
0405     WriteSplitDotFiles();
0406   } else {
0407     WriteSingleDotFile(output_filename);
0408     m_log->info("Call graph written to {}; to make a PDF from it, run: dot -Tpdf {} -o {}.pdf",
0409                 output_filename, output_filename, GetBaseFilename());
0410   }
0411 }
0412 
0413 void JEventProcessorCallGraph::WriteSingleDotFile(const std::string& filename) {
0414   std::ofstream ofs(filename);
0415   if (!ofs.is_open()) {
0416     m_log->error("Unable to open file {} for writing", filename);
0417     return;
0418   }
0419 
0420   // Percentages are relative to the total self time of all nodes (see GetTotalSelfTime)
0421   double total_ms = GetTotalSelfTime();
0422   if (total_ms == 0.0)
0423     total_ms = 1.0;
0424 
0425   // Write DOT file header
0426   ofs << "digraph G {" << '\n';
0427   ofs << "  rankdir=TB;" << '\n';
0428   ofs << "  node [fontname=\"Arial\", fontsize=10];" << '\n';
0429   ofs << "  edge [fontname=\"Arial\", fontsize=8];" << '\n';
0430   WriteGraphLabel(ofs, "EICrecon Call Graph", kSingleGraph);
0431   ofs << '\n';
0432 
0433   // Aggregate factory stats by factory ID (groups multi-output factories together)
0434   std::map<std::string, double> factory_times;
0435   std::map<std::string, std::vector<std::string>> factory_output_tags;
0436   std::map<std::string, node_type> factory_types;
0437 
0438   for (auto& [nametag, fstats] : factory_stats) {
0439     std::string factory_id = GetFactoryNodeName(nametag);
0440     double time_in_factory = GetSelfTime(fstats);
0441 
0442     factory_times[factory_id] += time_in_factory;
0443     factory_types[factory_id] = fstats.type;
0444   }
0445 
0446   // Populate output tags for each factory ID using the factory_outputs map
0447   for (auto& [factory_id, output_tags] : factory_outputs) {
0448     factory_output_tags[factory_id] = output_tags;
0449   }
0450 
0451   // Build input tags for each factory ID by examining call links
0452   std::map<std::string, std::set<std::string>> factory_input_tags;
0453   for (auto& [link, stats] : call_links) {
0454     std::string caller_nametag = MakeNametag(link.caller_name, link.caller_tag);
0455     std::string callee_nametag = MakeNametag(link.callee_name, link.callee_tag);
0456     std::string caller_id      = GetFactoryNodeName(caller_nametag);
0457     std::string callee_id      = GetFactoryNodeName(callee_nametag);
0458 
0459     // The caller depends on the callee, so callee is an input to caller.
0460     // Multiple nametags can collapse into the same factory_id, so skip
0461     // self-dependencies - a node listing itself as its own input is just noise.
0462     if (caller_id != callee_id) {
0463       factory_input_tags[caller_id].insert(callee_id);
0464     }
0465   }
0466 
0467   // Write nodes (one per factory, listing all outputs and inputs)
0468   for (auto& [factory_id, time_in_factory] : factory_times) {
0469     double percent = 100.0 * time_in_factory / total_ms;
0470 
0471     std::string color = GetNodeColorFromPercent(percent);
0472     std::string shape = GetNodeShape(factory_types[factory_id]);
0473 
0474     ofs << "  \"" << EscapeForDot(factory_id) << "\" [";
0475     ofs << "fillcolor=\"" << color << "\", ";
0476     ofs << "style=filled, ";
0477     ofs << "shape=" << shape << ", ";
0478     ofs << "labeljust=l, ";
0479     ofs << "label=\"" << EscapeForDot(factory_id);
0480 
0481     // List output collections
0482     auto& output_tags = factory_output_tags[factory_id];
0483     if (!output_tags.empty() && (output_tags.size() > 1 || output_tags[0] != factory_id)) {
0484       ofs << "\\nOutputs:";
0485       for (const auto& tag : output_tags) {
0486         ofs << "\\n  " << EscapeForDot(tag);
0487       }
0488     }
0489 
0490     // List input collections
0491     auto it = factory_input_tags.find(factory_id);
0492     if (it != factory_input_tags.end() && !it->second.empty()) {
0493       ofs << "\\nInputs:";
0494       for (const auto& tag : it->second) {
0495         ofs << "\\n  " << EscapeForDot(tag);
0496       }
0497     }
0498 
0499     ofs << "\\n"
0500         << MakeTimeString(time_in_factory) << " (" << std::fixed << std::setprecision(1) << percent
0501         << "%)\"";
0502     ofs << "];" << '\n';
0503   }
0504 
0505   ofs << '\n';
0506 
0507   // Write edges (grouped by factory names)
0508   std::map<std::pair<std::string, std::string>, std::pair<unsigned int, double>> aggregated_links;
0509 
0510   for (auto& [link, stats] : call_links) {
0511     std::string caller_nametag = MakeNametag(link.caller_name, link.caller_tag);
0512     std::string callee_nametag = MakeNametag(link.callee_name, link.callee_tag);
0513     std::string caller         = GetFactoryNodeName(caller_nametag);
0514     std::string callee         = GetFactoryNodeName(callee_nametag);
0515 
0516     unsigned int total_calls =
0517         stats.Nfrom_cache + stats.Nfrom_source + stats.Nfrom_factory + stats.Ndata_not_available;
0518     double total_time = stats.from_cache_ms + stats.from_source_ms + stats.from_factory_ms +
0519                         stats.data_not_available_ms;
0520 
0521     auto key = std::make_pair(caller, callee);
0522     aggregated_links[key].first += total_calls;
0523     aggregated_links[key].second += total_time;
0524   }
0525 
0526   for (auto& [link_pair, call_data] : aggregated_links) {
0527     unsigned int total_calls = call_data.first;
0528     double total_time        = call_data.second;
0529     double percent           = ClampPercent(100.0 * total_time / total_ms);
0530 
0531     ofs << "  \"" << EscapeForDot(link_pair.first) << "\" -> \"" << EscapeForDot(link_pair.second)
0532         << "\" [";
0533     ofs << "label=\"" << total_calls << " calls\\n";
0534     ofs << MakeTimeString(total_time) << " (" << std::fixed << std::setprecision(1) << percent
0535         << "%)\", ";
0536     // Scale penwidth linearly from 1 (0%) to 8 (100%)
0537     double penwidth = 1.0 + (percent / 100.0) * 7.0;
0538     ofs << "penwidth=" << std::fixed << std::setprecision(1) << penwidth;
0539     ofs << "];" << '\n';
0540   }
0541 
0542   ofs << "}" << '\n';
0543   ofs.close();
0544 }
0545 
0546 void JEventProcessorCallGraph::WriteSplitDotFiles() {
0547   // Always use plugin-based splitting with optional user group overrides
0548   std::map<std::string, std::set<std::string>> groups = SplitGraphByPlugin();
0549 
0550   // A group entry that matches nothing, e.g. a misspelled tag or a factory output other
0551   // than the first one (which the factory is named after), would otherwise be ignored silently
0552   for (const auto& [group_name, entry, nametags] : user_group_entries) {
0553     if (std::ranges::none_of(nametags, [this](const std::string& nametag) {
0554           return factory_stats.contains(nametag);
0555         })) {
0556       m_log->warn("callgraph:group:{} entry \"{}\" matches nothing in the call graph and is "
0557                   "ignored; use the name on a factory's box in the graphs (for a factory with "
0558                   "several outputs, the first one)",
0559                   group_name, entry);
0560     }
0561   }
0562 
0563   WritePluginGraphs(groups);
0564   WriteOverallDotFile(groups);
0565 }
0566 
0567 std::string JEventProcessorCallGraph::MakeTimeString(double time_in_ms) {
0568   double order = log10(std::abs(time_in_ms) + 1e-9); // avoid log(0)
0569   std::stringstream ss;
0570   ss << std::fixed << std::setprecision(2);
0571   if (order < 0) {
0572     ss << time_in_ms * 1000.0 << " us";
0573   } else if (order <= 2.0) {
0574     ss << time_in_ms << " ms";
0575   } else {
0576     ss << time_in_ms / 1000.0 << " s";
0577   }
0578   return ss.str();
0579 }
0580 
0581 std::string JEventProcessorCallGraph::MakeNametag(const std::string& name, const std::string& tag) {
0582   std::string nametag = tag;
0583   if (tag.size() > 0 && name.size() > 0) {
0584     nametag += " (" + name + ")";
0585   } else if (name.size() > 0) {
0586     nametag = name;
0587   }
0588   return nametag;
0589 }
0590 
0591 std::string JEventProcessorCallGraph::GetBaseFilename() {
0592   // Strip the extension from output_filename so per-plugin files and their
0593   // cross-referenced URLs are named consistently, even when output_filename
0594   // isn't the default "callgraph.dot".
0595   std::string base_filename = output_filename;
0596   std::size_t dot_pos       = base_filename.find_last_of('.');
0597   if (dot_pos != std::string::npos) {
0598     base_filename = base_filename.substr(0, dot_pos);
0599   }
0600   return base_filename;
0601 }
0602 
0603 std::string JEventProcessorCallGraph::SanitizeForFilename(const std::string& name) {
0604   // Plugin/group names can come from user-supplied -Pcallgraph:group:<name>=...
0605   // parameters. Replace path separators so they can't escape the working
0606   // directory via the generated filename, and so the URL we embed in the
0607   // overview graph (built from the same sanitized name) always matches it.
0608   std::string sanitized = name;
0609   std::replace(sanitized.begin(), sanitized.end(), '/', '_');
0610   std::replace(sanitized.begin(), sanitized.end(), '\\', '_');
0611   return sanitized;
0612 }
0613 
0614 std::string JEventProcessorCallGraph::EscapeForDot(const std::string& s) {
0615   // color_<...> comes from user-supplied -Pcallgraph:group:*=... parameters and
0616   // is written into a quoted DOT attribute. Escape '"' and '\' so it can't
0617   // terminate the string early and inject additional attributes.
0618   std::string escaped;
0619   escaped.reserve(s.size());
0620   for (char c : s) {
0621     if (c == '"' || c == '\\') {
0622       escaped += '\\';
0623     }
0624     escaped += c;
0625   }
0626   return escaped;
0627 }
0628 
0629 std::string JEventProcessorCallGraph::EscapeForHtml(const std::string& s) {
0630   // The graph title includes plugin/group names, which can come from user-supplied
0631   // -Pcallgraph:group:<name>=... parameters, and goes into an HTML-like label (see
0632   // WriteGraphLabel). Escape the characters that would be parsed as markup there.
0633   std::string escaped;
0634   escaped.reserve(s.size());
0635   for (char c : s) {
0636     if (c == '&') {
0637       escaped += "&amp;";
0638     } else if (c == '<') {
0639       escaped += "&lt;";
0640     } else if (c == '>') {
0641       escaped += "&gt;";
0642     } else if (c == '"') {
0643       escaped += "&quot;";
0644     } else {
0645       escaped += c;
0646     }
0647   }
0648   return escaped;
0649 }
0650 
0651 double JEventProcessorCallGraph::ClampPercent(double percent) {
0652   return std::clamp(percent, 0.0, 100.0);
0653 }
0654 
0655 double JEventProcessorCallGraph::GetSelfTime(const FactoryCallStats& fstats) {
0656   // Time spent in the node's own code: the time its callers waited on it (the sum
0657   // of its incoming edges) minus the time it waited on its inputs (the sum of its
0658   // outgoing edges). A pure top-level caller (e.g. an event processor requesting
0659   // its outputs at end-of-event) is never waited on, so its own time isn't
0660   // measured and this is 0 for it. Its waiting time isn't a substitute: that's
0661   // the self time of the factories it requested, which would be counted twice.
0662   return std::max(0.0, fstats.time_waited_on - fstats.time_waiting);
0663 }
0664 
0665 double JEventProcessorCallGraph::GetTotalSelfTime() {
0666   // The 100% reference for the percentages in every graph: the self time of all
0667   // nodes, i.e. the time spent in all factories. Using the same total in each
0668   // plugin graph as in the overview keeps their percentages comparable, and keeps
0669   // edge times, which include callees in other plugins, within 100%.
0670   double total_ms = 0.0;
0671   for (auto& [nametag, fstats] : factory_stats) {
0672     total_ms += GetSelfTime(fstats);
0673   }
0674   return total_ms;
0675 }
0676 
0677 std::string JEventProcessorCallGraph::GetFactoryNodeName(const std::string& nametag) {
0678   // Return the factory ID for this nametag, which groups multi-output factories
0679   auto it = nametag_to_factory_id.find(nametag);
0680   if (it != nametag_to_factory_id.end()) {
0681     return it->second;
0682   }
0683   // Fallback to nametag if not found
0684   return nametag;
0685 }
0686 
0687 JEventProcessorCallGraph::node_type JEventProcessorCallGraph::GetNodeType(const std::string& name,
0688                                                                           const std::string& tag) {
0689   // Simple heuristics to determine node type based on name patterns
0690   if (name.find("Processor") != std::string::npos || name.find("PROCESSOR") != std::string::npos) {
0691     return kProcessor;
0692   } else if (name.find("Source") != std::string::npos || name.find("SOURCE") != std::string::npos) {
0693     return kSource;
0694   } else if (name.find("Cache") != std::string::npos || name.find("CACHE") != std::string::npos) {
0695     return kCache;
0696   } else if (!tag.empty() || name.find("Factory") != std::string::npos ||
0697              name.find("edm4") != std::string::npos) {
0698     return kFactory;
0699   }
0700   return kDefault;
0701 }
0702 
0703 std::string JEventProcessorCallGraph::GetNodeColorFromPercent(double percent) {
0704   // Clamp percent to [0, 100]
0705   if (percent < 0.0)
0706     percent = 0.0;
0707   if (percent > 100.0)
0708     percent = 100.0;
0709 
0710   // Convert to [0, 1] range
0711   double t = percent / 100.0;
0712 
0713   // White (low/optimal) to Red (high) gradient
0714   // White: RGB(255, 255, 255) -> #FFFFFF at 0%
0715   // Red:   RGB(255, 0, 0) -> #FF0000 at 100%
0716 
0717   int r = 255;
0718   int g = static_cast<int>((1.0 - t) * 255);
0719   int b = static_cast<int>((1.0 - t) * 255);
0720 
0721   return std::format("#{:02X}{:02X}{:02X}", r, g, b);
0722 }
0723 
0724 std::string JEventProcessorCallGraph::GetNodeShape(node_type type) {
0725   switch (type) {
0726   case kProcessor:
0727     return "ellipse";
0728   case kFactory:
0729     return "box";
0730   case kCache:
0731     return "diamond";
0732   case kSource:
0733     return "trapezium";
0734   default:
0735     return "ellipse";
0736   }
0737 }
0738 
0739 void JEventProcessorCallGraph::WritePluginGraphs(
0740     const std::map<std::string, std::set<std::string>>& plugin_groups) {
0741   // Write individual plugin dot files
0742   for (auto& [plugin_name, nodes] : plugin_groups) {
0743     WritePluginDotFile(plugin_name, nodes);
0744   }
0745 
0746   m_log->info("Call graph written to {} per-plugin files {}.<plugin>.dot and the overview {}, "
0747               "which shows the connections between plugins",
0748               plugin_groups.size(), GetBaseFilename(), output_filename);
0749 }
0750 
0751 void JEventProcessorCallGraph::WritePluginDotFile(const std::string& plugin_name,
0752                                                   const std::set<std::string>& nodes) {
0753   // Create filename using period-separated plugin name
0754   std::string filename = GetBaseFilename() + "." + SanitizeForFilename(plugin_name) + ".dot";
0755 
0756   std::ofstream ofs(filename);
0757   if (!ofs.is_open()) {
0758     m_log->error("Unable to open file {} for writing", filename);
0759     return;
0760   }
0761 
0762   // Percentages are relative to the total self time of all plugins, not just this
0763   // one (see GetTotalSelfTime)
0764   double total_ms = GetTotalSelfTime();
0765   if (total_ms == 0.0)
0766     total_ms = 1.0;
0767 
0768   // Write DOT file header
0769   ofs << "digraph G {" << '\n';
0770   ofs << "  rankdir=TB;" << '\n';
0771   ofs << "  node [fontname=\"Arial\", fontsize=10];" << '\n';
0772   ofs << "  edge [fontname=\"Arial\", fontsize=8];" << '\n';
0773   WriteGraphLabel(ofs, "EICrecon Call Graph - " + plugin_name + " Plugin", kPluginGraph);
0774   ofs << '\n';
0775 
0776   // Aggregate factory stats by factory ID for nodes in this plugin
0777   std::map<std::string, double> factory_times;
0778   std::map<std::string, std::vector<std::string>> factory_output_tags;
0779   std::map<std::string, node_type> factory_types;
0780   std::set<std::string> factory_nodes; // Set of factory IDs in this plugin
0781 
0782   for (const std::string& nametag : nodes) {
0783     auto fstats_it = factory_stats.find(nametag);
0784     if (fstats_it == factory_stats.end())
0785       continue;
0786 
0787     const FactoryCallStats& fstats = fstats_it->second;
0788     std::string factory_id         = GetFactoryNodeName(nametag);
0789     double time_in_factory         = GetSelfTime(fstats);
0790 
0791     factory_times[factory_id] += time_in_factory;
0792     factory_types[factory_id] = fstats.type;
0793     factory_nodes.insert(factory_id);
0794   }
0795 
0796   // Populate output tags for each factory ID in this plugin
0797   for (const auto& factory_id : factory_nodes) {
0798     auto it = factory_outputs.find(factory_id);
0799     if (it != factory_outputs.end()) {
0800       factory_output_tags[factory_id] = it->second;
0801     }
0802   }
0803 
0804   // Build input tags for each factory ID in this plugin
0805   std::map<std::string, std::set<std::string>> factory_input_tags;
0806   for (auto& [link, stats] : call_links) {
0807     std::string caller_nametag = MakeNametag(link.caller_name, link.caller_tag);
0808     std::string callee_nametag = MakeNametag(link.callee_name, link.callee_tag);
0809 
0810     // Only consider links where both the caller and callee are in this
0811     // plugin: this subgraph doesn't draw nodes/edges for external factories,
0812     // so an "Inputs:" list referencing one would point at nothing in the file.
0813     if (nodes.find(caller_nametag) != nodes.end() && nodes.find(callee_nametag) != nodes.end()) {
0814       std::string caller_id = GetFactoryNodeName(caller_nametag);
0815       std::string callee_id = GetFactoryNodeName(callee_nametag);
0816       // Multiple nametags can collapse into the same factory_id; skip
0817       // self-dependencies rather than listing a node as its own input.
0818       if (caller_id != callee_id) {
0819         factory_input_tags[caller_id].insert(callee_id);
0820       }
0821     }
0822   }
0823 
0824   // Write nodes (one per factory in this plugin, listing all outputs and inputs)
0825   for (auto& [factory_id, time_in_factory] : factory_times) {
0826     double percent = 100.0 * time_in_factory / total_ms;
0827 
0828     std::string color = GetNodeColorFromPercent(percent);
0829     std::string shape = GetNodeShape(factory_types[factory_id]);
0830 
0831     ofs << "  \"" << EscapeForDot(factory_id) << "\" [";
0832     ofs << "fillcolor=\"" << color << "\", ";
0833     ofs << "style=filled, ";
0834     ofs << "shape=" << shape << ", ";
0835     ofs << "labeljust=l, ";
0836     ofs << "label=\"" << EscapeForDot(factory_id);
0837 
0838     // List output collections
0839     auto& output_tags = factory_output_tags[factory_id];
0840     if (!output_tags.empty() && (output_tags.size() > 1 || output_tags[0] != factory_id)) {
0841       ofs << "\\nOutputs:";
0842       for (const auto& tag : output_tags) {
0843         ofs << "\\n  " << EscapeForDot(tag);
0844       }
0845     }
0846 
0847     // List input collections
0848     auto input_it = factory_input_tags.find(factory_id);
0849     if (input_it != factory_input_tags.end() && !input_it->second.empty()) {
0850       ofs << "\\nInputs:";
0851       for (const auto& tag : input_it->second) {
0852         ofs << "\\n  " << EscapeForDot(tag);
0853       }
0854     }
0855 
0856     ofs << "\\n"
0857         << MakeTimeString(time_in_factory) << " (" << std::fixed << std::setprecision(1) << percent
0858         << "%)\"";
0859     ofs << "];" << '\n';
0860   }
0861 
0862   ofs << '\n';
0863 
0864   // Write edges (aggregated by factory names, only within this plugin)
0865   std::map<std::pair<std::string, std::string>, std::pair<unsigned int, double>> aggregated_links;
0866 
0867   for (auto& [link, stats] : call_links) {
0868     std::string caller_nametag = MakeNametag(link.caller_name, link.caller_tag);
0869     std::string callee_nametag = MakeNametag(link.callee_name, link.callee_tag);
0870 
0871     // Only include edges where both nodes are in this plugin
0872     if (nodes.find(caller_nametag) == nodes.end() || nodes.find(callee_nametag) == nodes.end()) {
0873       continue;
0874     }
0875 
0876     std::string caller = GetFactoryNodeName(caller_nametag);
0877     std::string callee = GetFactoryNodeName(callee_nametag);
0878 
0879     unsigned int total_calls =
0880         stats.Nfrom_cache + stats.Nfrom_source + stats.Nfrom_factory + stats.Ndata_not_available;
0881     double total_time = stats.from_cache_ms + stats.from_source_ms + stats.from_factory_ms +
0882                         stats.data_not_available_ms;
0883 
0884     auto key = std::make_pair(caller, callee);
0885     aggregated_links[key].first += total_calls;
0886     aggregated_links[key].second += total_time;
0887   }
0888 
0889   for (auto& [link_pair, call_data] : aggregated_links) {
0890     unsigned int total_calls = call_data.first;
0891     double total_time        = call_data.second;
0892     double percent           = ClampPercent(100.0 * total_time / total_ms);
0893 
0894     ofs << "  \"" << EscapeForDot(link_pair.first) << "\" -> \"" << EscapeForDot(link_pair.second)
0895         << "\" [";
0896     ofs << "label=\"" << total_calls << " calls\\n";
0897     ofs << MakeTimeString(total_time) << " (" << std::fixed << std::setprecision(1) << percent
0898         << "%)\", ";
0899     // Scale penwidth linearly from 1 (0%) to 8 (100%)
0900     double penwidth = 1.0 + (percent / 100.0) * 7.0;
0901     ofs << "penwidth=" << std::fixed << std::setprecision(1) << penwidth;
0902     ofs << "];" << '\n';
0903   }
0904 
0905   ofs << "}" << '\n';
0906   ofs.close();
0907 }
0908 
0909 void JEventProcessorCallGraph::WriteOverallDotFile(
0910     const std::map<std::string, std::set<std::string>>& plugin_groups) {
0911   std::ofstream ofs(output_filename);
0912   if (!ofs.is_open()) {
0913     m_log->error("Unable to open file {} for writing", output_filename);
0914     return;
0915   }
0916 
0917   std::string base_filename = GetBaseFilename();
0918 
0919   // Percentages are relative to the total self time of all nodes (see GetTotalSelfTime)
0920   double total_ms = GetTotalSelfTime();
0921   if (total_ms == 0.0)
0922     total_ms = 1.0;
0923 
0924   // Write DOT file header
0925   ofs << "digraph G {" << '\n';
0926   ofs << "  rankdir=TB;" << '\n';
0927   ofs << "  node [fontname=\"Arial\", fontsize=12];" << '\n';
0928   ofs << "  edge [fontname=\"Arial\", fontsize=10];" << '\n';
0929   WriteGraphLabel(ofs, "EICrecon Overall Call Graph - Inter-Plugin Connections", kOverviewGraph);
0930   ofs << '\n';
0931 
0932   // Create plugin nodes (aggregate statistics per plugin)
0933   std::map<std::string, double> plugin_times;
0934   std::map<std::string, int> plugin_node_counts;
0935 
0936   for (auto& [plugin_name, nodes] : plugin_groups) {
0937     double plugin_time = 0.0;
0938     // Count unique factory node IDs, not nametags: multi-output factories
0939     // collapse multiple nametags into one node via GetFactoryNodeName(), so
0940     // counting nametags would inflate the displayed "N factories".
0941     std::set<std::string> unique_nodes;
0942 
0943     for (const std::string& nametag : nodes) {
0944       auto fstats_it = factory_stats.find(nametag);
0945       if (fstats_it != factory_stats.end()) {
0946         const FactoryCallStats& fstats = fstats_it->second;
0947         plugin_time += GetSelfTime(fstats);
0948         unique_nodes.insert(GetFactoryNodeName(nametag));
0949       }
0950     }
0951     int node_count = static_cast<int>(unique_nodes.size());
0952 
0953     plugin_times[plugin_name]       = plugin_time;
0954     plugin_node_counts[plugin_name] = node_count;
0955 
0956     double percent = 100.0 * plugin_time / total_ms;
0957 
0958     std::string color = GetNodeColorFromPercent(percent);
0959 
0960     ofs << "  \"" << EscapeForDot(plugin_name) << "\" [";
0961     ofs << "fillcolor=\"" << color << "\", ";
0962     ofs << "style=filled, ";
0963     // User-defined groups (via -Pcallgraph:group:) get their requested color as the
0964     // node border, so they're visually distinguishable from auto-detected plugins
0965     // while still using the time-percentage gradient for the fill.
0966     auto group_color_it = user_group_colors.find(plugin_name);
0967     if (group_color_it != user_group_colors.end()) {
0968       ofs << "color=\"" << EscapeForDot(group_color_it->second) << "\", penwidth=2, ";
0969     }
0970     ofs << "shape=box, ";
0971     ofs << "URL=\"" << EscapeForDot(base_filename) << "."
0972         << EscapeForDot(SanitizeForFilename(plugin_name)) << ".svg\", ";
0973     ofs << "label=\"" << EscapeForDot(plugin_name) << "\\n";
0974     ofs << node_count << " factories\\n";
0975     ofs << MakeTimeString(plugin_time) << " (" << std::fixed << std::setprecision(1) << percent
0976         << "%)\"";
0977     ofs << "];" << '\n';
0978   }
0979 
0980   ofs << '\n';
0981 
0982   // Create edges between plugins (when there are calls between different plugins)
0983   std::map<std::pair<std::string, std::string>, std::pair<int, double>> inter_plugin_calls;
0984 
0985   for (auto& [link, stats] : call_links) {
0986     std::string caller = MakeNametag(link.caller_name, link.caller_tag);
0987     std::string callee = MakeNametag(link.callee_name, link.callee_tag);
0988 
0989     // Resolve group names the same way SplitGraphByPlugin() does (user group
0990     // overrides first, then plugin, then the "processors" fallback), so a
0991     // factory reassigned via -Pcallgraph:group:* contributes edges to its new
0992     // group instead of its original plugin.
0993     std::string caller_plugin = ResolveGroupName(caller);
0994     std::string callee_plugin = ResolveGroupName(callee);
0995 
0996     // Only show inter-plugin connections
0997     if (caller_plugin != callee_plugin && !caller_plugin.empty() && !callee_plugin.empty()) {
0998       auto key = std::make_pair(caller_plugin, callee_plugin);
0999 
1000       unsigned int total_calls =
1001           stats.Nfrom_cache + stats.Nfrom_source + stats.Nfrom_factory + stats.Ndata_not_available;
1002       double total_time = stats.from_cache_ms + stats.from_source_ms + stats.from_factory_ms +
1003                           stats.data_not_available_ms;
1004 
1005       inter_plugin_calls[key].first += total_calls;
1006       inter_plugin_calls[key].second += total_time;
1007     }
1008   }
1009 
1010   // Write inter-plugin edges
1011   for (auto& [plugins, call_data] : inter_plugin_calls) {
1012     int total_calls   = call_data.first;
1013     double total_time = call_data.second;
1014     double percent    = ClampPercent(100.0 * total_time / total_ms);
1015 
1016     ofs << "  \"" << EscapeForDot(plugins.first) << "\" -> \"" << EscapeForDot(plugins.second)
1017         << "\" [";
1018     ofs << "label=\"" << total_calls << " calls\\n";
1019     ofs << MakeTimeString(total_time) << " (" << std::fixed << std::setprecision(1) << percent
1020         << "%)\", ";
1021     // Scale penwidth linearly from 1 (0%) to 8 (100%)
1022     double penwidth = 1.0 + (percent / 100.0) * 7.0;
1023     ofs << "penwidth=" << std::fixed << std::setprecision(1) << penwidth;
1024     ofs << "];" << '\n';
1025   }
1026 
1027   ofs << "}" << '\n';
1028   ofs.close();
1029 }
1030 
1031 std::string JEventProcessorCallGraph::ResolveGroupName(const std::string& nametag) {
1032   // Check if this factory has a user-defined group override
1033   auto override_it = nametag_to_group.find(nametag);
1034   if (override_it != nametag_to_group.end()) {
1035     return override_it->second;
1036   }
1037   // Use plugin name from factory
1038   auto it = nametag_to_plugin.find(nametag);
1039   if (it != nametag_to_plugin.end()) {
1040     return it->second;
1041   }
1042   // Call-graph nodes aren't limited to registered factories - event
1043   // processors (e.g. JEventProcessorPODIO requesting its outputs at
1044   // end-of-event) show up here too but have no GetAllFactories() entry.
1045   // Group them with other non-factory framework nodes rather than an
1046   // "unknown" bucket that would mix them with genuinely unmapped ones.
1047   return "processors";
1048 }
1049 
1050 std::map<std::string, std::set<std::string>> JEventProcessorCallGraph::SplitGraphByPlugin() {
1051   std::map<std::string, std::set<std::string>> plugin_groups;
1052 
1053   // Group nodes by their actual plugin (from factory information)
1054   // with optional user group overrides
1055   for (auto& [nametag, fstats] : factory_stats) {
1056     std::string group_name = ResolveGroupName(nametag);
1057     plugin_groups[group_name].insert(nametag);
1058   }
1059 
1060   return plugin_groups;
1061 }