Humanitarian Aid Supply Chain Network
Use graph reasoning to analyze a humanitarian aid supply chain network with PageRank and Weighted Degree Centrality to optimize resource distribution strategies.
What this template is for
During humanitarian crises—natural disasters, conflicts, or disease outbreaks—emergency response teams must rapidly deploy aid through complex supply chain networks. This template demonstrates how to use PageRank and Weighted Degree Centrality — two complementary graph algorithms that reveal different dimensions of network importance — to optimize aid distribution strategies.
By analyzing a network of distribution points (airports, warehouses, border crossings, relief camps) and supply routes, this template helps you:
- Identify influential hubs where aid naturally concentrates (PageRank)
- Find critical coordination nodes that serve as highly connected network hubs (Weighted Degree Centrality)
- Prioritize resource deployment by combining both metrics for strategic decision-making
PageRank simulates how aid flows through the network using iterative random walks, while Weighted Degree Centrality identifies the most connected nodes that serve as coordination points. Together, they provide a comprehensive view of network structure and strategic priorities.
Who this is for
- Intermediate users ready to learn multi-metric graph analysis with iterative algorithms
- Data scientists working with supply chain optimization and network resilience
- Emergency response coordinators planning humanitarian aid distribution strategies
- Supply chain analysts identifying vulnerabilities in complex distribution networks
What you’ll build
- Load a humanitarian aid network with 18 distribution points and 28 directed supply routes from CSV files
- Use RelationalAI’s Graph API to model a weighted, directed supply chain network
- Calculate PageRank to identify where aid flows naturally concentrate (influence)
- Calculate Weighted Degree Centrality to find highly connected coordination nodes (network hubs)
- Analyze strategic categories: critical coordination hubs, influential endpoints, and network connectors
- Generate actionable recommendations for resource deployment and network resilience
- Compare multiple graph metrics to make informed strategic decisions
This template uses RelationalAI’s advanced graph algorithms including PageRank (an iterative algorithm requiring multiple passes over the network) and Weighted Degree Centrality (analyzing network connectivity patterns).
What’s included
- Shared model setup:
model_setup.py- Common model configuration and graph creation (used by both scripts) - Command-line script:
humanitarian_aid_supply_chain.py- CLI analysis script with detailed output - Interactive app:
app.py- Streamlit web application with visualizations and interactive analysis - Data:
data/distribution_points.csvanddata/supply_routes.csv
Prerequisites
- Python >= 3.10
- A Snowflake account that has the RAI Native App installed.
- A Snowflake user with permissions to access the RAI Native App.
Quickstart
Follow these steps to run the template with the included sample data. You can customize the data and model as needed after you have it running end-to-end.
-
Download the ZIP file for this template and extract it:
Terminal window curl -O https://docs.relational.ai/templates/zips/v1/humanitarian-aid-supply-chain.zipunzip humanitarian_aid_supply_chain.zipcd humanitarian_aid_supply_chain -
Create and activate a virtual environment
Terminal window python -m venv .venvsource .venv/bin/activatepython -m pip install -U pip -
Install dependencies
The SupplyRoute concept represents directed supply routes between distribution points with weighted attributes.
| Property | Type | Notes |
|---|---|---|
from_point | DistributionPoint | Source point in the supply route |
to_point | DistributionPoint | Destination point in the supply route |
route_capacity | Integer | Maximum throughput (units/day) |
reliability_score | Float | Route reliability (0-1 scale) |
distance_km | Integer | Physical distance for routing calculations |
Flow Weight Property
The flow weight property represents expected aid throughput considering capacity, reliability, and distance and is calculated using the following formula:
flow_weight = (route_capacity * reliability_score) / distance_kmGraph Metrics
The template calculates these advanced metrics using RelationalAI’s Graph API:
| Metric | Type | Description |
|---|---|---|
pagerank | Float | Influence score (0-1) based on iterative random walk simulation. Higher = more aid naturally flows here |
degree_centrality | Float | Sum of flow weights for all connected routes. Higher = more influential hub |
incoming_routes | Integer | Indegree: number of supply routes delivering TO this point |
outgoing_routes | Integer | Outdegree: number of supply routes originating FROM this point |
How it works
The template follows this flow:
CSV files → model_setup.create_model() → Calculate PageRank → Calculate Degree Centrality → Analyze strategic categories → Display results1. Shared Model Setup
Both the CLI script and Streamlit app use the same model setup from model_setup.py:
from model_setup import create_model
# Create the model, concepts, relationships, and graph (all in one call)model, graph, DistributionPoint, SupplyRoute = create_model()The create_model() function handles:
- Creating the RelationalAI model container
- Defining the
DistributionPointconcept with all properties - Loading distribution points from CSV
- Defining the
SupplyRouteconcept with weighted properties - Loading supply routes from CSV
- Creating the weighted, directed graph
- Returning all components for use in analysis
2. Calculate PageRank (Iterative Algorithm)
PageRank simulates random walks through the network to identify influential nodes:
# Calculate PageRank with damping factor 0.85# Damping factor models probability of continuing along routes vs. teleportingpagerank = graph.pagerank(damping_factor=0.85, tolerance=1e-6, max_iter=100)How PageRank works:
- Start with equal probability at all nodes
- Iteratively propagate probability along edges
- Apply damping factor: 85% chance of following an edge, 15% chance of “teleporting” to random node
- Converge when probabilities stabilize (tolerance threshold)
- Higher PageRank = more “important” in the network flow
3. Calculate Weighted Degree Centrality
Degree Centrality identifies highly connected network hubs:
# Calculate Degree Centralitydegree_centrality = graph.degree_centrality()
# Also calculate degree metrics for contextindegree = graph.indegree() # Incoming routesoutdegree = graph.outdegree() # Outgoing routesHow Weighted Degree Centrality works:
- Sum the flow weights for all connected routes (capacity × reliability) for each node
- Higher weighted degree = more influential hub with greater aid throughput capacity
- Accounts for both connectivity AND the strength/importance of those connections
- Identifies nodes that serve as critical coordination hubs with substantial flow capacity
4. Query and analyze strategic categories
Query both metrics and assign a strategic category to each distribution point.
from relationalai.semantics import where, select
# Create variable referencespoint = graph.Node.ref("point")pr_score = Float.ref("pr_score")dc_score = Float.ref("dc_score")in_routes = Integer.ref("in_routes")out_routes = Integer.ref("out_routes")
# Query all metrics togetherresults = where( pagerank(point, pr_score), degree_centrality(point, dc_score), indegree(point, in_routes), outdegree(point, out_routes)).select( point.id, point.name, point.type, point.region, point.capacity, point.population_served, pr_score.alias("pagerank"), dc_score.alias("degree_centrality"), in_routes.alias("incoming_routes"), out_routes.alias("outgoing_routes")).to_df()
# Assign a strategic category based on both metricspr_threshold = results['pagerank'].quantile(0.70)dc_threshold = results['degree_centrality'].quantile(0.70)
# Critical Coordination Hubs: High PageRank + High Degree Centralitycritical_hubs = results[ (results['pagerank'] >= pr_threshold) & (results['degree_centrality'] >= dc_threshold)]
# Influential Endpoints: High PageRank + Lower Degree Centralityinfluential_endpoints = results[ (results['pagerank'] >= pr_threshold) & (results['degree_centrality'] < dc_threshold)]
# Network Connectors: Lower PageRank + High Degree Centralityconnectors = results[ (results['pagerank'] < pr_threshold) & (results['degree_centrality'] >= dc_threshold)]5. Display strategic analysis and recommendations
CLI script (humanitarian_aid_supply_chain.py) prints:
- Ranked table of all distribution points with both metrics
- Strategic category analysis (Critical Coordination Hubs, Influential Endpoints, Network Connectors)
- Network-wide and regional statistics
- Actionable recommendations for emergency response teams
Streamlit app (app.py) provides:
- Interactive overview with top-5 rankings
- Network visualization with color-coded nodes by strategic category
- Detailed filterable rankings with CSV export
- Strategic analysis with expandable details for each category
- Regional distribution statistics
Customize this template
Use your own data:
- Replace the CSV files in the
data/directory with your own supply chain network, keeping the same column names (or update the logic inmodel_setup.py). - Ensure that supply routes only reference valid distribution point IDs.
- You can add additional properties to distribution points (organization, contact info, GPS coordinates) by adding columns to the CSV and corresponding properties to the model in
model_setup.py.
Extend the model:
-
Adjust PageRank parameters: Experiment with different damping factors:
- Higher damping (0.90-0.95): More emphasis on network structure, less on random teleportation
- Lower damping (0.70-0.80): More emphasis on direct connections, less on global influence
-
Add different edge weights: Change the graph edge weight formula in
model_setup.pyto optimize for different factors. Remember: for PageRank, use direct multipliers—higher weights indicate stronger connections that PageRank will favor.Current formula:
(route_capacity * reliability_score) / distance_km— good for balanced optimizationAlternative formulas (all using direct multipliers):
- Capacity-focused:
route_capacity(maximize throughput) - Reliability-focused:
reliability_score(emphasize route stability) - Simple combined:
route_capacity * reliability_score(ignore distance)
- Capacity-focused:
-
Try additional algorithms:
graph.louvain()- Community detection to identify regional aid distribution clustersgraph.is_reachable(point1, point2)- Verify connectivity between specific locationsgraph.distance(point1, point2)- Calculate shortest path length between pointsgraph.weakly_connected_components()- Identify disconnected network regions
Add temporal analysis: Include route availability schedules or seasonal variations to model time-dependent supply chains.
Incorporate risk factors: Add node properties for conflict zones, disease prevalence, or natural disaster risk to prioritize safe routes.
Troubleshooting
Why does authentication/configuration fail?
- Run
rai initto create/updateraiconfig.toml. - If you have multiple profiles, set
RAI_PROFILEor switch profiles in your config.
Why does the script fail to connect to the RAI Native App?
- Verify the Snowflake account/role/warehouse and
rai_app_nameare correct inraiconfig.toml. - Ensure the RAI Native App is installed and you have access.
Why does PageRank not converge?
- Your network might have disconnected components or unusual structure.
- Try increasing
max_iter(default 100) or adjustingtolerance(default 1e-6). - Check that your graph has valid edges and nodes.
How do I decide between PageRank and Degree Centrality?
- Use PageRank to identify where resources naturally accumulate (influence, importance)
- Use Degree Centrality to identify highly connected coordination hubs (network structure)
- Use both together (like this template) for comprehensive strategic analysis
- They measure different things: PageRank = “influence/flow”, Degree Centrality = “connectivity/hub importance”
Can I use this for other types of supply chains?
- Yes! This template works for any directed supply chain:
- Manufacturing supply chains (factories → warehouses → retailers)
- Food distribution networks (farms → processing → distribution → stores)
- Pharmaceutical supply chains (manufacturers → distributors → pharmacies)
- Just update the CSV data and entity names to match your domain.