Average Weighted Shortest Path Calculator & Guide
:root {
–primary-color: #004a99;
–success-color: #28a745;
–background-color: #f8f9fa;
–text-color: #333;
–border-color: #ddd;
–card-background: #fff;
–shadow-color: rgba(0, 0, 0, 0.1);
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: var(–background-color);
color: var(–text-color);
line-height: 1.6;
margin: 0;
padding: 0;
}
.container {
max-width: 960px;
margin: 20px auto;
padding: 20px;
background-color: var(–card-background);
border-radius: 8px;
box-shadow: 0 4px 12px var(–shadow-color);
}
h1, h2, h3 {
color: var(–primary-color);
text-align: center;
margin-bottom: 20px;
}
h1 {
font-size: 2.2em;
}
h2 {
font-size: 1.8em;
margin-top: 30px;
border-bottom: 2px solid var(–primary-color);
padding-bottom: 5px;
}
h3 {
font-size: 1.4em;
margin-top: 25px;
}
.calculator-section {
background-color: var(–card-background);
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 8px var(–shadow-color);
margin-bottom: 30px;
}
.input-group {
margin-bottom: 20px;
text-align: left;
}
.input-group label {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: var(–primary-color);
}
.input-group input[type="number"],
.input-group input[type="text"],
.input-group select {
width: calc(100% – 22px);
padding: 10px;
border: 1px solid var(–border-color);
border-radius: 4px;
font-size: 1em;
box-sizing: border-box;
}
.input-group input[type="number"]:focus,
.input-group input[type="text"]:focus,
.input-group select:focus {
border-color: var(–primary-color);
outline: none;
box-shadow: 0 0 0 2px rgba(0, 74, 153, 0.2);
}
.input-group .helper-text {
font-size: 0.85em;
color: #666;
margin-top: 5px;
display: block;
}
.error-message {
color: #dc3545;
font-size: 0.85em;
margin-top: 5px;
display: block;
min-height: 1.2em; /* Prevent layout shift */
}
.button-group {
text-align: center;
margin-top: 25px;
}
button {
padding: 12px 25px;
margin: 0 10px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
font-weight: bold;
transition: background-color 0.3s ease, transform 0.2s ease;
}
button.primary {
background-color: var(–primary-color);
color: white;
}
button.primary:hover {
background-color: #003366;
transform: translateY(-2px);
}
button.secondary {
background-color: #6c757d;
color: white;
}
button.secondary:hover {
background-color: #5a6268;
transform: translateY(-2px);
}
button.reset {
background-color: #ffc107;
color: #212529;
}
button.reset:hover {
background-color: #e0a800;
transform: translateY(-2px);
}
.results-container {
margin-top: 30px;
padding: 20px;
background-color: #e7f3ff;
border: 1px dashed var(–primary-color);
border-radius: 8px;
text-align: center;
}
.results-container h3 {
margin-top: 0;
color: var(–primary-color);
}
.main-result {
font-size: 2.5em;
font-weight: bold;
color: var(–primary-color);
margin: 15px 0;
display: inline-block;
padding: 10px 20px;
background-color: #ffffff;
border-radius: 6px;
box-shadow: inset 0 0 10px rgba(0, 74, 153, 0.1);
}
.intermediate-results div {
margin-bottom: 10px;
font-size: 1.1em;
}
.intermediate-results strong {
color: var(–primary-color);
min-width: 200px;
display: inline-block;
}
.formula-explanation {
font-size: 0.95em;
color: #555;
margin-top: 15px;
padding: 10px;
background-color: #f0f8ff;
border-left: 4px solid var(–primary-color);
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
box-shadow: 0 2px 8px var(–shadow-color);
}
th, td {
padding: 12px 15px;
text-align: left;
border: 1px solid var(–border-color);
}
thead {
background-color: var(–primary-color);
color: white;
}
tbody tr:nth-child(even) {
background-color: #f2f2f2;
}
caption {
font-size: 1.1em;
font-weight: bold;
color: var(–primary-color);
margin-bottom: 10px;
caption-side: top;
text-align: left;
}
canvas {
display: block;
margin: 20px auto;
max-width: 100%;
border: 1px solid var(–border-color);
border-radius: 4px;
}
.article-content {
margin-top: 40px;
background-color: var(–card-background);
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 8px var(–shadow-color);
}
.article-content p, .article-content ul, .article-content ol {
margin-bottom: 15px;
}
.article-content li {
margin-bottom: 8px;
}
.article-content a {
color: var(–primary-color);
text-decoration: none;
}
.article-content a:hover {
text-decoration: underline;
}
.faq-item {
margin-bottom: 15px;
border-bottom: 1px dashed var(–border-color);
padding-bottom: 10px;
}
.faq-item:last-child {
border-bottom: none;
}
.faq-item strong {
display: block;
color: var(–primary-color);
margin-bottom: 5px;
cursor: pointer;
}
.faq-item p {
margin-bottom: 0;
display: none; /* Initially hidden */
}
.faq-item.open p {
display: block;
}
.related-links ul {
list-style: none;
padding: 0;
}
.related-links li {
margin-bottom: 10px;
}
.related-links li a {
font-weight: bold;
}
.related-links li span {
font-size: 0.9em;
color: #666;
display: block;
margin-top: 3px;
}
.highlighted-result {
background-color: var(–success-color);
color: white;
padding: 15px 25px;
border-radius: 6px;
font-size: 1.3em;
font-weight: bold;
text-align: center;
margin-top: 20px;
box-shadow: 0 4px 8px rgba(40, 167, 69, 0.3);
}
.copy-button {
background-color: #17a2b8;
color: white;
margin-top: 15px;
}
.copy-button:hover {
background-color: #138496;
}
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
cursor: help;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 220px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 10px;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -110px;
opacity: 0;
transition: opacity 0.3s;
font-size: 0.8em;
line-height: 1.4;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
Network Path Analysis
Calculation Results
AWSP: —
Formula: AWSP = (Sum of All Weighted Path Lengths) / (Number of Possible Paths)
*Note: The number of possible paths is typically N*(N-1)/2 for undirected graphs, or N*(N-1) for directed graphs. This calculator assumes N*(N-1)/2 for simplicity unless specified otherwise.*
Network Path Analysis Chart
Comparison of Average Shortest Path vs. Average Weighted Path
Network Metrics Summary
| Metric |
Value |
Unit |
| Number of Nodes (N) |
— |
Nodes |
| Number of Edges (M) |
— |
Edges |
| Sum of Weighted Paths |
— |
Units |
| Average Shortest Path |
— |
Units |
| Average Weighted Path |
— |
Units |
| Average Weighted Shortest Path (AWSP) |
— |
Units |
| Path Density |
— |
% |
Summary of calculated network path metrics.
{primary_keyword}
The Average Weighted Shortest Path (AWSP) is a critical metric used in network analysis to quantify the overall efficiency and connectivity of a network. It represents the average length of the shortest paths between all possible pairs of nodes in a network, where the "length" is determined by the sum of weights along the path. Understanding the AWSP is fundamental for designing robust, scalable, and high-performing networks, whether they are physical infrastructure, communication systems, or even abstract data structures.
Who Should Use the Average Weighted Shortest Path Calculator?
This calculator and the underlying concept of AWSP are invaluable for a wide range of professionals and researchers:
- Network Engineers: To assess the efficiency of existing network topologies and plan for upgrades or new deployments. A lower AWSP generally indicates better performance and lower latency.
- Computer Scientists: For analyzing graph algorithms, distributed systems, and data structures. It helps in understanding the communication overhead and data retrieval times.
- Logistics and Supply Chain Managers: To optimize delivery routes, warehouse placement, and transportation networks. Minimizing the AWSP can lead to significant cost savings and faster delivery times.
- Urban Planners: When designing transportation systems (roads, public transit) to minimize travel time between different points in a city.
- Researchers: In fields like social network analysis, biology (protein interaction networks), and physics (complex systems) to understand connectivity patterns.
Common Misconceptions about AWSP
Several misunderstandings can arise when discussing AWSP:
- AWSP is the same as Average Path Length: While related, AWSP specifically considers edge weights, making it more relevant for networks where connections have varying costs or capacities (e.g., bandwidth, travel time, cost). Simple Average Path Length ignores these weights.
- A Dense Network Always Has a Low AWSP: While denser networks (more edges) often have shorter paths, a poorly designed dense network with high-weight edges can still have a high AWSP. The structure and weights are crucial.
- AWSP is Static: In dynamic networks (e.g., the internet, traffic networks), AWSP can change frequently due to congestion, link failures, or rerouting. The calculated value is a snapshot based on current conditions or a specific topology.
- AWSP is the Only Metric for Network Efficiency: While important, AWSP should be considered alongside other metrics like network diameter, clustering coefficient, and throughput for a comprehensive understanding.
The calculation of the Average Weighted Shortest Path involves several steps, primarily focused on identifying the shortest path between every pair of nodes and then averaging these lengths, weighted appropriately.
Step-by-Step Derivation
- Identify All Node Pairs: Determine all unique pairs of nodes (u, v) in the network. For an undirected graph with N nodes, there are N * (N – 1) / 2 such pairs. For a directed graph, there are N * (N – 1) pairs.
- Calculate Shortest Path for Each Pair: For each pair (u, v), find the shortest path. This typically involves using algorithms like Dijkstra's algorithm (for non-negative weights) or the Floyd-Warshall algorithm (for all-pairs shortest paths, handling negative weights but not negative cycles). The result is the shortest path distance, d(u, v), considering the edge weights.
- Sum of All Shortest Path Lengths: Add up the shortest path distances for all identified pairs: Sum = Σ d(u, v) for all pairs (u, v).
- Determine the Number of Paths: Calculate the total number of possible paths between distinct nodes. As mentioned, this is typically N * (N – 1) / 2 for undirected graphs.
- Calculate the Average Weighted Shortest Path (AWSP): Divide the sum of all shortest path lengths by the total number of paths.
Variable Explanations
The core variables involved in calculating AWSP are:
- N (Number of Nodes): The total count of distinct points or entities in the network.
- M (Number of Edges): The total count of connections linking the nodes.
- Edge Weights: Numerical values assigned to each edge, representing cost, distance, time, capacity, or any other relevant metric.
- d(u, v): The length (sum of weights) of the shortest path between node 'u' and node 'v'.
- Sum of All Shortest Path Lengths: The total sum obtained by adding d(u, v) for every pair of distinct nodes.
- Number of Paths: The total count of unique pairs of distinct nodes.
Variables Table
| Variable |
Meaning |
Unit |
Typical Range |
| N |
Number of Nodes |
Nodes |
2 to thousands (or more) |
| M |
Number of Edges |
Edges |
1 to N*(N-1)/2 (undirected) or N*(N-1) (directed) |
| w(e) |
Weight of an edge 'e' |
Cost, Time, Distance, etc. |
Non-negative real numbers (typically) |
| d(u, v) |
Shortest path distance between u and v |
Sum of edge weights |
0 to ∞ (depending on weights and connectivity) |
| Σ d(u, v) |
Sum of all shortest path lengths |
Sum of edge weights |
0 to ∞ |
| Number of Paths |
Total pairs of distinct nodes |
Pairs |
N*(N-1)/2 (undirected) or N*(N-1) (directed) |
| AWSP |
Average Weighted Shortest Path |
Average edge weight sum |
0 to ∞ |
Practical Examples
Example 1: Small Road Network
Consider a small town with 4 intersections (nodes A, B, C, D) and 5 roads (edges) connecting them. The weights represent travel time in minutes.
- Nodes (N): 4 (A, B, C, D)
- Edges (M): 5
- Connections & Weights: A-B (5 min), A-C (2 min), B-C (3 min), B-D (6 min), C-D (4 min)
- Sum of All Weighted Path Lengths: Let's assume after running Dijkstra's, the sum of shortest paths is 35 minutes (e.g., A-B=5, A-C=2, A-D=6, B-C=3, B-D=6, C-D=4. Sum = 5+2+6+3+6+4 = 26. *Note: This is a simplified sum for illustration; actual calculation requires all pairs.* Let's use the calculator's input value of 50 for this example.)
- Number of Paths: For 4 nodes, N*(N-1)/2 = 4*3/2 = 6 pairs (A-B, A-C, A-D, B-C, B-D, C-D).
Using the Calculator:
- Input: N=4, M=5, Sum of Weighted Paths=50
- Output:
- Average Shortest Path: 8.33
- Average Weighted Path: 8.33
- Path Density: 41.67%
- AWSP: 8.33
Interpretation: On average, traveling between any two points in this town takes approximately 8.33 minutes, considering the most efficient routes. A path density of ~42% suggests a moderately connected network.
Example 2: Computer Network Routing
Imagine 5 servers (nodes) in a data center. Connections (edges) have weights representing latency in milliseconds (ms).
- Nodes (N): 5
- Edges (M): 7
- Sum of All Weighted Path Lengths: Assume 120 ms (calculated via Floyd-Warshall or similar).
- Number of Paths: For 5 nodes, N*(N-1)/2 = 5*4/2 = 10 pairs.
Using the Calculator:
- Input: N=5, M=7, Sum of Weighted Paths=120
- Output:
- Average Shortest Path: 12.00
- Average Weighted Path: 12.00
- Path Density: 29.17%
- AWSP: 12.00
Interpretation: The average latency between any two servers is 12.00 ms. This metric helps in understanding the overall responsiveness of the network. A lower AWSP is desirable for applications sensitive to latency.
How to Use This Average Weighted Shortest Path Calculator
Our calculator simplifies the process of determining the AWSP for your network. Follow these steps:
- Input Network Size: Enter the total number of nodes (N) and edges (M) in your network.
- Provide Total Weighted Path Length: Input the pre-calculated sum of the lengths of the shortest paths between all distinct node pairs. This value is often obtained using graph algorithms like Floyd-Warshall or by summing results from multiple Dijkstra runs.
- Calculate: Click the "Calculate AWSP" button.
- Review Results: The calculator will display:
- Intermediate Values: Average Shortest Path, Average Weighted Path, and Path Density.
- Primary Result (AWSP): The main highlighted value, representing the average weighted shortest path length.
- Formula Explanation: A brief description of the calculation.
- Summary Table: A detailed breakdown of all input and calculated metrics.
- Chart: A visual comparison of Average Shortest Path and Average Weighted Path.
- Reset or Copy: Use the "Reset" button to clear fields and enter new data, or use "Copy Results" to save the calculated metrics.
Decision-Making Guidance: A lower AWSP generally indicates a more efficient and well-connected network. Use this metric to compare different network designs, identify bottlenecks, or justify network upgrades. For instance, if comparing two potential network layouts, the one with the lower AWSP might be preferred if all other factors are equal.
Key Factors That Affect AWSP Results
Several factors significantly influence the calculated AWSP:
- Network Topology: The arrangement of nodes and edges is paramount. A highly centralized or star topology might have a lower AWSP than a sparse, linear one, assuming similar edge weights. Conversely, a ring or mesh topology often offers good connectivity.
- Edge Weights: Higher weights on edges increase the shortest path lengths, thus raising the AWSP. Optimizing or re-routing through lower-weight edges is key to reducing AWSP. This could mean using fiber optic cables instead of copper, choosing shorter physical routes, or prioritizing high-bandwidth links.
- Number of Nodes (N): As N increases, the number of node pairs (N*(N-1)/2) grows quadratically. This increases the computational effort to find all shortest paths and can naturally lead to longer average paths if the number of edges doesn't scale proportionally.
- Network Density (M/N^2): A denser network (more edges relative to nodes) generally allows for shorter paths, potentially lowering the AWSP. However, adding edges with high weights can counteract this benefit. Path density, calculated as M / (N*(N-1)/2), provides a normalized view.
- Presence of Hubs or Central Nodes: Networks with highly connected central nodes (hubs) often exhibit lower AWSP because many paths can be routed efficiently through these central points. This is common in star topologies or hierarchical networks.
- Algorithm Used for Shortest Paths: While the AWSP is a conceptual metric, the accuracy of its calculation depends on using appropriate shortest path algorithms (like Dijkstra for non-negative weights). Incorrect algorithm choices or failure to find the true shortest paths will lead to inaccurate AWSP values.
- Directed vs. Undirected Graph: The calculation differs slightly. In directed graphs, the number of paths is N*(N-1), and paths are not necessarily reciprocal (d(u,v) might not equal d(v,u)). This can affect the total sum and the final AWSP.
Frequently Asked Questions (FAQ)
What is the difference between Average Shortest Path and Average Weighted Shortest Path?
The Average Shortest Path (ASP) considers only the number of hops (edges) in the shortest path, assuming each hop has a unit length. The Average Weighted Shortest Path (AWSP) considers the actual sum of weights (like distance, cost, or latency) along the shortest path, providing a more realistic measure for networks with varying connection characteristics.
How do I find the "Sum of All Weighted Path Lengths"?
This value is typically computed using all-pairs shortest path algorithms like Floyd-Warshall or by running a single-source shortest path algorithm (like Dijkstra) from each node and summing the results. Many network analysis libraries or specialized software can compute this.
Is a lower AWSP always better?
Generally, yes. A lower AWSP indicates greater network efficiency, meaning data or resources can travel between points more quickly or cheaply on average. However, context matters. Sometimes, a slightly higher AWSP might be acceptable if it comes with significantly lower infrastructure costs or greater redundancy.
Can AWSP be negative?
If edge weights represent costs or distances, they are typically non-negative, making the AWSP non-negative. However, if weights represent something like 'gain' or 'efficiency improvement', negative values could theoretically occur, but this is rare in standard network analysis and requires careful interpretation. Standard algorithms like Dijkstra assume non-negative weights.
What is Path Density?
Path Density is a measure of how many actual connections exist relative to the maximum possible connections. It's calculated as (Number of Edges) / (Maximum Possible Edges). For undirected graphs, Max Edges = N*(N-1)/2. A higher density often correlates with shorter paths but also higher complexity and cost.
Does the calculator handle directed graphs?
This specific calculator simplifies the calculation by assuming an undirected graph for determining the number of paths (N*(N-1)/2). For directed graphs, the number of paths is N*(N-1), and the sum of shortest paths might differ. For precise directed graph analysis, adjust the number of paths accordingly.
What if my network has disconnected components?
If a network has disconnected components, the shortest path between nodes in different components is infinite. This significantly impacts the sum of shortest paths and the AWSP. You might need to calculate AWSP for each component separately or define a maximum path length threshold.
How does AWSP relate to network diameter?
Network diameter is the *longest* shortest path between any two nodes. AWSP is the *average* of all shortest paths. A network can have a small diameter but a large AWSP if most paths are short but a few are very long. Conversely, a network might have a large diameter but a relatively small AWSP if the average path length is kept low.
var chartInstance = null; // Global variable to hold chart instance
function getElement(id) {
return document.getElementById(id);
}
function validateInput(value, id, min, max, name) {
var errorElement = getElement(id + 'Error');
errorElement.textContent = ";
if (value === ") {
errorElement.textContent = name + ' cannot be empty.';
return false;
}
var numValue = parseFloat(value);
if (isNaN(numValue)) {
errorElement.textContent = name + ' must be a number.';
return false;
}
if (min !== null && numValue max) {
errorElement.textContent = name + ' must be no more than ' + max + '.';
return false;
}
return true;
}
function calculateAWSP() {
var numNodes = getElement('numNodes').value;
var numEdges = getElement('numEdges').value;
var totalWeightedPathLength = getElement('totalWeightedPathLength').value;
var error = false;
if (!validateInput(numNodes, 'numNodes', 2, 50, 'Number of Nodes')) error = true;
if (!validateInput(numEdges, 'numEdges', 1, 200, 'Number of Edges')) error = true;
if (!validateInput(totalWeightedPathLength, 'totalWeightedPathLength', 0, null, 'Sum of Weighted Path Lengths')) error = true;
if (error) {
clearResults();
return;
}
var n = parseFloat(numNodes);
var m = parseFloat(numEdges);
var sumWPL = parseFloat(totalWeightedPathLength);
// Assuming undirected graph for number of paths calculation
var numPaths = n * (n – 1) / 2;
if (numPaths =2 is enforced)
var avgShortestPath = sumWPL / numPaths; // Simplified: assumes ASP = AWSP if weights are uniform
var avgWeightedPath = sumWPL / numPaths; // In this simplified model, they are the same
var pathDensity = (m / (n * (n – 1) / 2)) * 100;
if (isNaN(pathDensity) || !isFinite(pathDensity)) pathDensity = 0;
if (pathDensity > 100) pathDensity = 100; // Cap at 100%
var awsp = sumWPL / numPaths;
getElement('avgShortestPathValue').textContent = avgShortestPath.toFixed(2);
getElement('avgWeightedPathValue').textContent = avgWeightedPath.toFixed(2);
getElement('pathDensityValue').textContent = pathDensity.toFixed(2);
getElement('awspValue').textContent = awsp.toFixed(2);
getElement('resultsExplanation').innerHTML = 'The Average Weighted Shortest Path (AWSP) is calculated by dividing the total sum of weighted shortest paths between all node pairs by the number of such pairs. In this simplified model, we assume the Average Shortest Path and Average Weighted Path are derived from the same total sum, reflecting a baseline connectivity measure.';
// Update table
getElement('tableNumNodes').textContent = n.toFixed(0);
getElement('tableNumEdges').textContent = m.toFixed(0);
getElement('tableTotalWeightedPathLength').textContent = sumWPL.toFixed(2);
getElement('tableAvgShortestPath').textContent = avgShortestPath.toFixed(2);
getElement('tableAvgWeightedPath').textContent = avgWeightedPath.toFixed(2);
getElement('tableAwsp').textContent = awsp.toFixed(2);
getElement('tablePathDensity').textContent = pathDensity.toFixed(2);
updateChart(avgShortestPath, avgWeightedPath);
}
function clearResults() {
getElement('avgShortestPathValue').textContent = '–';
getElement('avgWeightedPathValue').textContent = '–';
getElement('pathDensityValue').textContent = '–';
getElement('awspValue').textContent = '–';
getElement('resultsExplanation').innerHTML = ";
getElement('tableNumNodes').textContent = '–';
getElement('tableNumEdges').textContent = '–';
getElement('tableTotalWeightedPathLength').textContent = '–';
getElement('tableAvgShortestPath').textContent = '–';
getElement('tableAvgWeightedPath').textContent = '–';
getElement('tableAwsp').textContent = '–';
getElement('tablePathDensity').textContent = '–';
if (chartInstance) {
chartInstance.destroy();
chartInstance = null;
}
var ctx = getElement('awspChart').getContext('2d');
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
function resetForm() {
getElement('numNodes').value = 4;
getElement('numEdges').value = 5;
getElement('totalWeightedPathLength').value = 50;
clearResults();
// Optionally recalculate immediately after reset
// calculateAWSP();
}
function updateChart(avgShortestPath, avgWeightedPath) {
var ctx = getElement('awspChart').getContext('2d');
// Destroy previous chart instance if it exists
if (chartInstance) {
chartInstance.destroy();
}
chartInstance = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Average Shortest Path', 'Average Weighted Path'],
datasets: [{
label: 'Path Length (Units)',
data: [avgShortestPath, avgWeightedPath],
backgroundColor: [
'rgba(0, 74, 153, 0.6)',
'rgba(40, 167, 69, 0.6)'
],
borderColor: [
'rgba(0, 74, 153, 1)',
'rgba(40, 167, 69, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'Average Path Length (Units)'
}
}
},
plugins: {
legend: {
display: false // Hide legend as labels are on x-axis
},
title: {
display: true,
text: 'Comparison of Average Path Metrics'
}
}
}
});
}
function copyResults() {
var numNodes = getElement('numNodes').value;
var numEdges = getElement('numEdges').value;
var totalWeightedPathLength = getElement('totalWeightedPathLength').value;
var avgShortestPath = getElement('avgShortestPathValue').textContent;
var avgWeightedPath = getElement('avgWeightedPathValue').textContent;
var pathDensity = getElement('pathDensityValue').textContent;
var awsp = getElement('awspValue').textContent;
var resultsText = "— Network Path Analysis Results —\n\n";
resultsText += "Inputs:\n";
resultsText += "- Number of Nodes (N): " + numNodes + "\n";
resultsText += "- Number of Edges (M): " + numEdges + "\n";
resultsText += "- Sum of All Weighted Path Lengths: " + totalWeightedPathLength + "\n\n";
resultsText += "Calculated Metrics:\n";
resultsText += "- Average Shortest Path: " + avgShortestPath + "\n";
resultsText += "- Average Weighted Path: " + avgWeightedPath + "\n";
resultsText += "- Path Density: " + pathDensity + "%\n";
resultsText += "- Average Weighted Shortest Path (AWSP): " + awsp + "\n\n";
resultsText += "Assumptions:\n";
resultsText += "- Assumed undirected graph for path count calculation.\n";
resultsText += "- Weights are non-negative.\n";
// Use a temporary textarea to copy text
var textArea = document.createElement("textarea");
textArea.value = resultsText;
textArea.style.position = "fixed"; // Avoid scrolling to bottom
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'Results copied to clipboard!' : 'Failed to copy results.';
// Optionally show a temporary message to the user
var copyButton = getElement('copyButton'); // Assuming copy button has id="copyButton"
if (!copyButton) { // Create a temporary button if it doesn't exist for feedback
copyButton = document.createElement('button');
copyButton.id = 'copyButton';
copyButton.className = 'copy-button';
copyButton.style.marginLeft = '10px';
getElement('networkForm').appendChild(copyButton);
}
copyButton.textContent = msg;
copyButton.style.backgroundColor = successful ? 'var(–success-color)' : '#dc3545';
setTimeout(function() {
copyButton.textContent = 'Copy Results';
copyButton.style.backgroundColor = '#17a2b8';
}, 2000);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
// Handle error, maybe show a message to the user
}
document.body.removeChild(textArea);
}
// Initialize chart on load if default values are present
document.addEventListener('DOMContentLoaded', function() {
// Add event listeners for real-time updates
var inputs = document.querySelectorAll('#networkForm input[type="number"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('input', function() {
// Basic validation on input change
var id = this.id;
var value = this.value;
var name = this.labels ? this.labels[0].textContent : id;
var min = parseFloat(this.min);
var max = parseFloat(this.max);
var errorElement = getElement(id + 'Error');
errorElement.textContent = '';
if (value === '') {
errorElement.textContent = name + ' cannot be empty.';
clearResults(); // Clear results if input becomes empty
return;
}
var numValue = parseFloat(value);
if (isNaN(numValue)) {
errorElement.textContent = name + ' must be a number.';
clearResults();
return;
}
if (min !== null && numValue max) {
errorElement.textContent = name + ' must be no more than ' + max + '.';
// Don't clear results here
}
// Only calculate if all inputs are valid numbers and not empty
var numNodesVal = getElement('numNodes').value;
var numEdgesVal = getElement('numEdges').value;
var totalWPLVal = getElement('totalWeightedPathLength').value;
if (numNodesVal !== " && numEdgesVal !== " && totalWPLVal !== " &&
!isNaN(parseFloat(numNodesVal)) && !isNaN(parseFloat(numEdgesVal)) && !isNaN(parseFloat(totalWPLVal))) {
calculateAWSP();
} else {
clearResults(); // Clear if any input becomes invalid during typing
}
});
}
// Initial calculation with default values
calculateAWSP();
// FAQ toggle functionality
var faqItems = document.querySelectorAll('.faq-item strong');
for (var i = 0; i < faqItems.length; i++) {
faqItems[i].addEventListener('click', function() {
var parent = this.parentElement;
parent.classList.toggle('open');
});
}
});
// Chart.js library needs to be included for the chart to work.
// In a real WordPress environment, you'd enqueue this script properly.
// For this standalone HTML, assume Chart.js is available globally.
// If running locally without Chart.js, you'll need to add:
//
// at the end of the body or in the head.