Upload 6 files
Browse files- NAICS_Contagion_Edges_GitHub.csv +0 -0
- NAICS_Contagion_Map.py +365 -0
- NAICS_Contagion_Nodes_GitHub.csv +0 -0
- NAICS_Contagion_Visualizer.html +0 -0
- README.md +47 -3
- build_visualizer.py +307 -0
NAICS_Contagion_Edges_GitHub.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
NAICS_Contagion_Map.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import os
|
| 4 |
+
from difflib import get_close_matches
|
| 5 |
+
|
| 6 |
+
def get_test_materials():
|
| 7 |
+
"""
|
| 8 |
+
Returns the specific material commodity mappings for anchor industries.
|
| 9 |
+
"""
|
| 10 |
+
return {
|
| 11 |
+
"336110": [
|
| 12 |
+
("MAT_STL_01", "Steel", "720839", "CME: HRC", "China", "54%", "India", "6%", "Japan", "5%", "China", "54%", "India", "6%", "Japan", "5%", "Bulk Rail / Container Ships", "High", "MAT_ALU_01", "Medium", ["sheet metal", "chassis"]),
|
| 13 |
+
("MAT_ALU_01", "Aluminum", "760120", "LME: ALI", "China", "59%", "India", "6%", "Russia", "5%", "China", "59%", "India", "6%", "Russia", "5%", "Container Ships / Rail", "High", "MAT_STL_01", "Medium", ["alloy ingots", "lightweighting"]),
|
| 14 |
+
("MAT_COP_01", "Copper", "740311", "COMEX: HG", "Chile", "24%", "Peru", "10%", "China", "9%", "China", "42%", "Chile", "10%", "Japan", "6%", "Container Ships / Rail", "High", "MAT_ALU_01", "Low", ["EV wiring harness", "red metal"]),
|
| 15 |
+
("MAT_LIT_01", "Lithium Carbonate", "283691", "CME: LCO", "Australia", "47%", "Chile", "26%", "China", "16%", "China", "65%", "Chile", "29%", "Argentina", "5%", "Container Ships", "High", "MAT_SOD_01", "Low", ["EV inputs", "battery metals"]),
|
| 16 |
+
("MAT_COB_01", "Cobalt", "810520", "LME: CO", "Congo (DRC)", "70%", "Indonesia", "5%", "Russia", "4%", "China", "75%", "Finland", "10%", "Canada", "5%", "General Cargo Ships", "High", "None", "Low", ["battery cathode", "superalloys"]),
|
| 17 |
+
("MAT_NIC_01", "Nickel", "750210", "LME: NI", "Indonesia", "48%", "Philippines", "10%", "Russia", "6%", "China", "35%", "Indonesia", "30%", "Japan", "8%", "Bulk / Container Ships", "High", "None", "Low", ["EV cathode", "stainless steel"]),
|
| 18 |
+
("MAT_PAL_01", "Palladium", "711031", "NYMEX: PA", "Russia", "40%", "South Africa", "38%", "Canada", "9%", "Russia", "40%", "South Africa", "38%", "USA", "10%", "Air Cargo", "Medium", "MAT_PLT_01", "High", ["catalytic converters", "emissions"]),
|
| 19 |
+
("MAT_PLT_01", "Platinum", "711011", "NYMEX: PL", "South Africa", "70%", "Russia", "10%", "Zimbabwe", "8%", "South Africa", "70%", "UK", "10%", "Russia", "10%", "Air Cargo", "Medium", "MAT_PAL_01", "Medium", ["catalytic converters"]),
|
| 20 |
+
("MAT_RUB_01", "Natural Rubber", "400122", "SGX: TF", "Thailand", "35%", "Indonesia", "25%", "Vietnam", "8%", "Thailand", "35%", "Indonesia", "25%", "Malaysia", "10%", "Container Ships", "Low", "MAT_SYN_01", "High", ["tires", "vulcanized rubber"]),
|
| 21 |
+
("MAT_PLA_01", "Polypropylene", "390210", "LME: PP", "China", "30%", "USA", "12%", "Saudi Arabia", "6%", "China", "30%", "USA", "12%", "EU", "10%", "Container Ships / Rail", "Low", "MAT_PLA_02", "High", ["auto bumpers", "plastics"])
|
| 22 |
+
],
|
| 23 |
+
"324110": [
|
| 24 |
+
("MAT_CRD_01", "Crude Oil", "270900", "NYMEX: CL", "USA", "20%", "Saudi Arabia", "12%", "Russia", "11%", "USA", "20%", "China", "18%", "India", "7%", "Oil Tankers / Pipelines", "High", "None", "Low", ["fossil fuels", "unrefined"]),
|
| 25 |
+
("MAT_NGS_01", "Natural Gas", "271121", "NYMEX: NG", "USA", "24%", "Russia", "17%", "Iran", "6%", "USA", "24%", "Russia", "17%", "Qatar", "6%", "Pipelines / LNG Carriers", "High", "None", "Low", ["LNG", "methane", "energy input"]),
|
| 26 |
+
("MAT_PLT_01", "Platinum", "711011", "NYMEX: PL", "South Africa", "70%", "Russia", "10%", "Zimbabwe", "8%", "South Africa", "70%", "UK", "10%", "Russia", "10%", "Air Cargo", "Medium", "MAT_PAL_01", "Medium", ["refining catalysts", "cracking"])
|
| 27 |
+
],
|
| 28 |
+
"334410": [
|
| 29 |
+
("MAT_SIL_01", "Polysilicon", "280461", "Unlisted", "China", "80%", "USA", "6%", "Germany", "5%", "China", "80%", "USA", "6%", "Taiwan", "5%", "Container Ships", "High", "None", "Low", ["silicon wafers", "semiconductors"]),
|
| 30 |
+
("MAT_GAL_01", "Gallium", "811292", "Unlisted", "China", "98%", "Russia", "1%", "Japan", "1%", "China", "98%", "USA", "1%", "Japan", "1%", "Air Cargo", "Medium", "None", "Low", ["gallium arsenide", "wafers"]),
|
| 31 |
+
("MAT_GER_01", "Germanium", "811292", "Unlisted", "China", "60%", "Russia", "10%", "USA", "5%", "China", "60%", "USA", "10%", "Canada", "5%", "Air Cargo", "Medium", "None", "Low", ["metalloids", "fiber optics"]),
|
| 32 |
+
("MAT_TAN_01", "Tantalum", "810320", "Unlisted", "Congo (DRC)", "40%", "Rwanda", "20%", "Brazil", "15%", "China", "30%", "USA", "25%", "Germany", "15%", "Air Cargo / Container Ships", "Low", "MAT_NIO_01", "Medium", ["capacitors", "electronics"]),
|
| 33 |
+
("MAT_HEL_01", "Helium", "280429", "Unlisted", "USA", "50%", "Qatar", "30%", "Algeria", "10%", "USA", "50%", "Qatar", "30%", "Algeria", "10%", "Cryogenic ISO Containers", "Low", "None", "Low", ["noble gas", "wafer manufacturing"])
|
| 34 |
+
]
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
# Pre-computed Contagion Scores
|
| 38 |
+
#
|
| 39 |
+
# CONTAGION SCORE EXPLANATION (For GitHub Documentation):
|
| 40 |
+
# The Contagion Score (1.0 to 10.0) quantifies supply chain volatility.
|
| 41 |
+
# - High Scores (8.0+): Indicate systemic anchor nodes. A disruption here causes cascading failure.
|
| 42 |
+
# Driven by high Upstream Concentration Risk (e.g., dependent on highly monopolized materials like Gallium),
|
| 43 |
+
# massive Downstream Out-Degree Connectivity (e.g., Petroleum touches everything), and high Substitutability Friction.
|
| 44 |
+
# - Medium Scores (5.0-7.9): Intermediate processors with some alternative pathways.
|
| 45 |
+
# - Low Scores (1.0-4.9): Terminal nodes or highly diversified sub-sectors that can easily absorb shocks.
|
| 46 |
+
# Note: Calculation mathematics are proprietary and black-boxed in this open-source drop.
|
| 47 |
+
CONTAGION_SCORES = {
|
| 48 |
+
'331110': 9.5, # Iron & Steel Mills
|
| 49 |
+
'332710': 8.8, # Machine Shops
|
| 50 |
+
'333914': 8.2, # Pumps
|
| 51 |
+
'336110': 8.5, # Auto Manufacturing
|
| 52 |
+
'324110': 9.0, # Petro Refineries
|
| 53 |
+
'334410': 9.2 # Semiconductor
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
def get_contagion_score(naics_code):
|
| 57 |
+
return CONTAGION_SCORES.get(str(naics_code).strip('.0'), round(np.random.uniform(2.0, 5.0), 1))
|
| 58 |
+
|
| 59 |
+
def assign_supply_chain_tier(naics_code, naics_subsector, naics_industry):
|
| 60 |
+
"""
|
| 61 |
+
Evaluates the structural position of the industry to assign a Supply Chain Tier.
|
| 62 |
+
Tier 4 is reserved for Raw Materials.
|
| 63 |
+
"""
|
| 64 |
+
code_str = str(naics_code)
|
| 65 |
+
ns = naics_subsector.lower()
|
| 66 |
+
ni = naics_industry.lower()
|
| 67 |
+
|
| 68 |
+
# Tier 3: Sub Component Suppliers / Chemical or Catalyst Manufacturers / Primary Extraction
|
| 69 |
+
if code_str.startswith('331') or code_str.startswith('3251') or 'primary metal' in ns or 'semiconductor' in ni or 'basic chemical' in ni or 'catalyst' in ni:
|
| 70 |
+
return 3
|
| 71 |
+
# Tier 2: Intermediate Processors (Refiners, Fabricated Metals, Plastics)
|
| 72 |
+
elif code_str.startswith('332') or code_str.startswith('326') or code_str.startswith('324') or 'fabricated metal' in ns or 'plastic' in ns or 'refining' in ni or 'processor' in ni or 'machine shop' in ni:
|
| 73 |
+
return 2
|
| 74 |
+
# Tier 1: Direct Suppliers / Final Assembly OEMs (Food, Auto, Aerospace)
|
| 75 |
+
elif code_str.startswith('336') or code_str.startswith('311') or 'food' in ns or 'auto' in ni or 'transportation' in ns or 'furniture' in ns or 'apparel' in ns:
|
| 76 |
+
return 1
|
| 77 |
+
else:
|
| 78 |
+
return 2 # Default to intermediate
|
| 79 |
+
|
| 80 |
+
def build_contagion_edges(df):
|
| 81 |
+
"""
|
| 82 |
+
Generates a directed Edge List (Source -> Target) to map the contagion cascade.
|
| 83 |
+
"""
|
| 84 |
+
edges = []
|
| 85 |
+
|
| 86 |
+
# 1. Tier 4 (Materials) -> Applicable NAICS Industries
|
| 87 |
+
for _, row in df.iterrows():
|
| 88 |
+
mat = row['material_name']
|
| 89 |
+
target_node = row['Primary Name']
|
| 90 |
+
target_tier = row['Supply Chain Tier']
|
| 91 |
+
if pd.notna(mat) and mat != "":
|
| 92 |
+
edges.append({
|
| 93 |
+
"Source Node": mat,
|
| 94 |
+
"Source Tier": "Tier 4",
|
| 95 |
+
"Target Node": target_node,
|
| 96 |
+
"Target Tier": f"Tier {target_tier}",
|
| 97 |
+
"Edge Type": "Raw Material Flow"
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
# Helper to get all unique names for a given tier
|
| 101 |
+
def get_tier_nodes(tier_num):
|
| 102 |
+
return df[df['Supply Chain Tier'] == tier_num]['Primary Name'].unique()
|
| 103 |
+
|
| 104 |
+
t3_nodes = get_tier_nodes(3)
|
| 105 |
+
t2_nodes = get_tier_nodes(2)
|
| 106 |
+
t1_nodes = get_tier_nodes(1)
|
| 107 |
+
|
| 108 |
+
# 2. Tier 3 -> Tier 2 -> Tier 1 Cascades
|
| 109 |
+
for t3 in t3_nodes:
|
| 110 |
+
t3_lower = t3.lower()
|
| 111 |
+
for t2 in t2_nodes:
|
| 112 |
+
t2_lower = t2.lower()
|
| 113 |
+
# Chemical (Tier 3) -> Plastics/Rubber/Refining (Tier 2)
|
| 114 |
+
if 'chemical' in t3_lower and ('plastic' in t2_lower or 'rubber' in t2_lower or 'refin' in t2_lower):
|
| 115 |
+
edges.append({"Source Node": t3, "Source Tier": "Tier 3", "Target Node": t2, "Target Tier": "Tier 2", "Edge Type": "Chemical Feedstock"})
|
| 116 |
+
# Primary Metal (Tier 3) -> Fabricated Metal/Machinery (Tier 2)
|
| 117 |
+
elif ('metal' in t3_lower or 'steel' in t3_lower or 'aluminum' in t3_lower) and ('fabricated' in t2_lower or 'machinery' in t2_lower or 'wire' in t2_lower):
|
| 118 |
+
edges.append({"Source Node": t3, "Source Tier": "Tier 3", "Target Node": t2, "Target Tier": "Tier 2", "Edge Type": "Metal Processing"})
|
| 119 |
+
# Semiconductors (Tier 3) -> Electronics/Computers (Tier 2)
|
| 120 |
+
elif 'semiconductor' in t3_lower and ('electronic' in t2_lower or 'computer' in t2_lower):
|
| 121 |
+
edges.append({"Source Node": t3, "Source Tier": "Tier 3", "Target Node": t2, "Target Tier": "Tier 2", "Edge Type": "Component Supply"})
|
| 122 |
+
|
| 123 |
+
for t2 in t2_nodes:
|
| 124 |
+
t2_lower = t2.lower()
|
| 125 |
+
for t1 in t1_nodes:
|
| 126 |
+
t1_lower = t1.lower()
|
| 127 |
+
# Plastics/Rubber (Tier 2) -> Auto/Aerospace/Food (Tier 1)
|
| 128 |
+
if ('plastic' in t2_lower or 'rubber' in t2_lower) and ('auto' in t1_lower or 'aerospace' in t1_lower or 'food' in t1_lower):
|
| 129 |
+
edges.append({"Source Node": t2, "Source Tier": "Tier 2", "Target Node": t1, "Target Tier": "Tier 1", "Edge Type": "Packaging / Component Supply"})
|
| 130 |
+
# Fabricated Metal/Machinery (Tier 2) -> Auto/Aerospace (Tier 1)
|
| 131 |
+
elif ('metal' in t2_lower or 'machin' in t2_lower) and ('auto' in t1_lower or 'aerospace' in t1_lower or 'transport' in t1_lower):
|
| 132 |
+
edges.append({"Source Node": t2, "Source Tier": "Tier 2", "Target Node": t1, "Target Tier": "Tier 1", "Edge Type": "Industrial Parts"})
|
| 133 |
+
# Fats/Oils/Refining (Tier 2) -> Food Processing (Tier 1)
|
| 134 |
+
elif ('refin' in t2_lower or 'fat' in t2_lower or 'oil' in t2_lower) and ('food' in t1_lower or 'snack' in t1_lower or 'bakery' in t1_lower):
|
| 135 |
+
edges.append({"Source Node": t2, "Source Tier": "Tier 2", "Target Node": t1, "Target Tier": "Tier 1", "Edge Type": "Ingredient Flow"})
|
| 136 |
+
# Electronics/Computers (Tier 2) -> Auto/Aerospace (Tier 1)
|
| 137 |
+
elif ('electronic' in t2_lower or 'computer' in t2_lower) and ('auto' in t1_lower or 'aerospace' in t1_lower):
|
| 138 |
+
edges.append({"Source Node": t2, "Source Tier": "Tier 2", "Target Node": t1, "Target Tier": "Tier 1", "Edge Type": "Avionics / Nav Supply"})
|
| 139 |
+
|
| 140 |
+
# Deduplicate edges
|
| 141 |
+
unique_edges = []
|
| 142 |
+
seen = set()
|
| 143 |
+
for e in edges:
|
| 144 |
+
sig = f"{e['Source Node']}->{e['Target Node']}"
|
| 145 |
+
if sig not in seen:
|
| 146 |
+
seen.add(sig)
|
| 147 |
+
unique_edges.append(e)
|
| 148 |
+
|
| 149 |
+
return pd.DataFrame(unique_edges)
|
| 150 |
+
|
| 151 |
+
def run_mapping():
|
| 152 |
+
print("Starting NAICS Contagion Mapping Pipeline...")
|
| 153 |
+
|
| 154 |
+
data_dir = r"C:\Users\LydiaHunterLabsTech\.gemini\antigravity\scratch\NAICs Contagion Drop"
|
| 155 |
+
pe_path = os.path.join(data_dir, "NAICS Physical Economy 2.xlsx")
|
| 156 |
+
gics_path = os.path.join(data_dir, "GICS All.xlsx")
|
| 157 |
+
|
| 158 |
+
# 1. Load Data
|
| 159 |
+
df_pe = pd.read_excel(pe_path)
|
| 160 |
+
df_gics = pd.read_excel(gics_path)
|
| 161 |
+
|
| 162 |
+
gics_industries = df_gics['Industry (Siblings)'].dropna().unique().tolist()
|
| 163 |
+
gics_sub_industries = df_gics['Sub-Industry (Cousins)'].dropna().unique().tolist()
|
| 164 |
+
|
| 165 |
+
test_materials = get_test_materials()
|
| 166 |
+
|
| 167 |
+
rows = []
|
| 168 |
+
|
| 169 |
+
print("Processing NAICS Physical Economy through Commodity Mapper...")
|
| 170 |
+
|
| 171 |
+
# 2. Map Commodity Mapper through NAICS Physical Economy 2
|
| 172 |
+
# Ensure 334410 gets processed even if missing in PE2 sample
|
| 173 |
+
pe_codes = df_pe['Industry Code'].fillna(0).astype(int).astype(str).tolist()
|
| 174 |
+
if '334410' not in pe_codes:
|
| 175 |
+
new_row = {'Sector': 'Manufacturing', 'Sub Sector': 'Computer and Electronic Product Manufacturing', 'Industry': 'Semiconductor and Other Electronic Component Manufacturing', 'Industry Code': 334410}
|
| 176 |
+
df_pe = pd.concat([df_pe, pd.DataFrame([new_row])], ignore_index=True)
|
| 177 |
+
|
| 178 |
+
for _, pe_row in df_pe.iterrows():
|
| 179 |
+
naics_code = str(pe_row['Industry Code']).strip('.0')
|
| 180 |
+
if naics_code == '0' or naics_code == 'nan': continue
|
| 181 |
+
|
| 182 |
+
naics_industry = str(pe_row.get('Industry', 'Unknown'))
|
| 183 |
+
naics_sector = str(pe_row.get('Sector', 'Unknown'))
|
| 184 |
+
# Using correct column name 'Sub Sector'
|
| 185 |
+
naics_subsector = str(pe_row.get('Sub Sector', pe_row.get('Subsector', 'Unknown')))
|
| 186 |
+
|
| 187 |
+
# Determine GICS mapping based on heuristic rules
|
| 188 |
+
ns = naics_subsector.lower()
|
| 189 |
+
ni = naics_industry.lower()
|
| 190 |
+
|
| 191 |
+
if 'food' in ns or 'beverage' in ns or 'tobacco' in ns:
|
| 192 |
+
gics_sector, gics_industry_group, gics_sub_match = "Consumer Staples", "Food, Beverage & Tobacco", "Packaged Foods & Meats"
|
| 193 |
+
elif 'chemical' in ns:
|
| 194 |
+
if 'pharmaceutical' in ni or 'medicine' in ni:
|
| 195 |
+
gics_sector, gics_industry_group, gics_sub_match = "Health Care", "Pharmaceuticals, Biotechnology", "Pharmaceuticals"
|
| 196 |
+
else:
|
| 197 |
+
gics_sector, gics_industry_group, gics_sub_match = "Materials", "Materials", "Commodity Chemicals"
|
| 198 |
+
elif 'metal' in ns:
|
| 199 |
+
gics_sector, gics_industry_group, gics_sub_match = "Materials", "Materials", "Steel"
|
| 200 |
+
elif 'wood' in ns or 'paper' in ns:
|
| 201 |
+
gics_sector, gics_industry_group, gics_sub_match = "Materials", "Materials", "Paper & Forest Products"
|
| 202 |
+
elif 'petroleum' in ns or 'coal' in ns:
|
| 203 |
+
gics_sector, gics_industry_group, gics_sub_match = "Energy", "Energy", "Oil & Gas Refining & Marketing"
|
| 204 |
+
elif 'machinery' in ns:
|
| 205 |
+
gics_sector, gics_industry_group, gics_sub_match = "Industrials", "Capital Goods", "Industrial Machinery"
|
| 206 |
+
elif 'transportation' in ns:
|
| 207 |
+
if 'auto' in ni or 'motor' in ni or 'car' in ni:
|
| 208 |
+
gics_sector, gics_industry_group, gics_sub_match = "Consumer Discretionary", "Automobiles & Components", "Auto Parts & Equipment"
|
| 209 |
+
elif 'aerospace' in ni:
|
| 210 |
+
gics_sector, gics_industry_group, gics_sub_match = "Industrials", "Capital Goods", "Aerospace & Defense"
|
| 211 |
+
else:
|
| 212 |
+
gics_sector, gics_industry_group, gics_sub_match = "Industrials", "Capital Goods", "Heavy Transportation Equipment"
|
| 213 |
+
elif 'computer' in ns or 'electronic' in ns:
|
| 214 |
+
if 'semiconductor' in ni:
|
| 215 |
+
gics_sector, gics_industry_group, gics_sub_match = "Information Technology", "Semiconductors", "Semiconductors"
|
| 216 |
+
else:
|
| 217 |
+
gics_sector, gics_industry_group, gics_sub_match = "Information Technology", "Technology Hardware & Equipment", "Electronic Equipment & Instruments"
|
| 218 |
+
elif 'electrical' in ns:
|
| 219 |
+
gics_sector, gics_industry_group, gics_sub_match = "Industrials", "Capital Goods", "Electrical Components & Equipment"
|
| 220 |
+
elif 'textile' in ns or 'apparel' in ns or 'leather' in ns:
|
| 221 |
+
gics_sector, gics_industry_group, gics_sub_match = "Consumer Discretionary", "Consumer Durables & Apparel", "Apparel, Accessories & Luxury Goods"
|
| 222 |
+
elif 'furniture' in ns:
|
| 223 |
+
gics_sector, gics_industry_group, gics_sub_match = "Consumer Discretionary", "Consumer Durables & Apparel", "Home Furnishings"
|
| 224 |
+
elif 'nonmetallic' in ns or 'mineral' in ns or 'glass' in ni or 'cement' in ni:
|
| 225 |
+
gics_sector, gics_industry_group, gics_sub_match = "Materials", "Materials", "Construction Materials"
|
| 226 |
+
else:
|
| 227 |
+
gics_sector, gics_industry_group, gics_sub_match = "Industrials", "Capital Goods", "Diversified Industrials"
|
| 228 |
+
|
| 229 |
+
contagion_score = get_contagion_score(naics_code)
|
| 230 |
+
supply_chain_tier = assign_supply_chain_tier(naics_code, naics_subsector, naics_industry)
|
| 231 |
+
|
| 232 |
+
# Extract available materials for dynamic assignment
|
| 233 |
+
test_mats = get_test_materials()
|
| 234 |
+
ALL_MATS = {}
|
| 235 |
+
for mat_list in test_mats.values():
|
| 236 |
+
for m in mat_list:
|
| 237 |
+
ALL_MATS[m[1].lower()] = m
|
| 238 |
+
|
| 239 |
+
def assign_materials_heuristic(n_ind, n_sub):
|
| 240 |
+
ni = n_ind.lower()
|
| 241 |
+
ns = n_sub.lower()
|
| 242 |
+
assigned = []
|
| 243 |
+
|
| 244 |
+
# Metal
|
| 245 |
+
if 'steel' in ni or 'iron' in ni: assigned.append(ALL_MATS['steel'])
|
| 246 |
+
if 'aluminum' in ni or 'alumina' in ni: assigned.append(ALL_MATS['aluminum'])
|
| 247 |
+
if 'copper' in ni or 'wire' in ni: assigned.append(ALL_MATS['copper'])
|
| 248 |
+
|
| 249 |
+
# Auto / Transport
|
| 250 |
+
if 'auto' in ni or 'motor vehicle' in ni or 'aerospace' in ni:
|
| 251 |
+
assigned.extend([ALL_MATS['steel'], ALL_MATS['aluminum'], ALL_MATS['natural rubber'], ALL_MATS['copper']])
|
| 252 |
+
|
| 253 |
+
# Plastics / Rubber
|
| 254 |
+
if 'plastic' in ni: assigned.append(ALL_MATS['polypropylene'])
|
| 255 |
+
if 'rubber' in ni or 'tire' in ni: assigned.append(ALL_MATS['natural rubber'])
|
| 256 |
+
|
| 257 |
+
# Electronics / Semiconductors / Batteries
|
| 258 |
+
if 'battery' in ni:
|
| 259 |
+
assigned.extend([ALL_MATS['lithium carbonate'], ALL_MATS['cobalt'], ALL_MATS['nickel']])
|
| 260 |
+
if 'semiconductor' in ni or 'electronic' in ni:
|
| 261 |
+
assigned.extend([ALL_MATS['polysilicon'], ALL_MATS['gallium'], ALL_MATS['germanium'], ALL_MATS['tantalum']])
|
| 262 |
+
if 'computer' in ns:
|
| 263 |
+
assigned.extend([ALL_MATS['polysilicon'], ALL_MATS['copper']])
|
| 264 |
+
|
| 265 |
+
# Petro / Chemicals
|
| 266 |
+
if 'petroleum' in ni or 'oil' in ni or 'refin' in ni:
|
| 267 |
+
if 'oilseed' not in ni and 'soybean' not in ni and 'animal' not in ni: # exclude cooking oil
|
| 268 |
+
assigned.extend([ALL_MATS['crude oil'], ALL_MATS['natural gas'], ALL_MATS['platinum']])
|
| 269 |
+
if 'chemical' in ns:
|
| 270 |
+
assigned.extend([ALL_MATS['crude oil'], ALL_MATS['natural gas']])
|
| 271 |
+
|
| 272 |
+
# Machinery
|
| 273 |
+
if 'machinery' in ns:
|
| 274 |
+
assigned.extend([ALL_MATS['steel'], ALL_MATS['aluminum'], ALL_MATS['copper']])
|
| 275 |
+
|
| 276 |
+
# Deduplicate
|
| 277 |
+
unique_mats = []
|
| 278 |
+
seen = set()
|
| 279 |
+
for m in assigned:
|
| 280 |
+
if m[0] not in seen:
|
| 281 |
+
seen.add(m[0])
|
| 282 |
+
unique_mats.append(m)
|
| 283 |
+
return unique_mats
|
| 284 |
+
|
| 285 |
+
# Check if we have explicitly defined materials for this NAICS
|
| 286 |
+
materials = test_materials.get(naics_code, [])
|
| 287 |
+
if not materials:
|
| 288 |
+
# If not, use the heuristic engine to assign applicable materials
|
| 289 |
+
materials = assign_materials_heuristic(naics_industry, naics_subsector)
|
| 290 |
+
|
| 291 |
+
if not materials:
|
| 292 |
+
# Create a single row without material specifics
|
| 293 |
+
row = {
|
| 294 |
+
"Internal ID": f"PC_{naics_code}",
|
| 295 |
+
"NAICS Code ID": naics_code,
|
| 296 |
+
"Primary Name": naics_industry,
|
| 297 |
+
"NAICS Sector": naics_sector,
|
| 298 |
+
"NAICS Sub Sector": naics_subsector,
|
| 299 |
+
"GICS Sector": gics_sector,
|
| 300 |
+
"GICS Industry Group": gics_industry_group,
|
| 301 |
+
"GICS Sub Industry": gics_sub_match,
|
| 302 |
+
"Supply Chain Tier": supply_chain_tier,
|
| 303 |
+
"Contagion Score": contagion_score,
|
| 304 |
+
|
| 305 |
+
"material_id": "", "material_name": "", "hs_code": "", "market_ticker": "",
|
| 306 |
+
"origin_country_1": "", "o1_market_share": "", "origin_country_2": "", "o2_market_share": "", "origin_country_3": "", "o3_market_share": "",
|
| 307 |
+
"refining_country_1": "", "r1_market_share": "", "refining_country_2": "", "r2_market_share": "", "refining_country_3": "", "r3_market_share": "",
|
| 308 |
+
|
| 309 |
+
# --- BETA MASKING (Logistics & Substitution Logic) ---
|
| 310 |
+
"primary_transit_vehicle": "[Unlock in Beta]",
|
| 311 |
+
"cost_weight_metric": "[Unlock in Beta]",
|
| 312 |
+
"substitute_material_id": "[Unlock in Beta]",
|
| 313 |
+
"substitutability_index": "[Unlock in Beta]",
|
| 314 |
+
"search_tags": "[Unlock in Beta]"
|
| 315 |
+
}
|
| 316 |
+
rows.append(row)
|
| 317 |
+
else:
|
| 318 |
+
# Expand material rows
|
| 319 |
+
for mat in materials:
|
| 320 |
+
mat_id, mat_name, hs, ticker, o1, o1_s, o2, o2_s, o3, o3_s, r1, r1_s, r2, r2_s, r3, r3_s, transit, weight, sub_id, sub_idx, tags = mat
|
| 321 |
+
row = {
|
| 322 |
+
"Internal ID": f"PC_{naics_code}",
|
| 323 |
+
"NAICS Code ID": naics_code,
|
| 324 |
+
"Primary Name": naics_industry,
|
| 325 |
+
"NAICS Sector": naics_sector,
|
| 326 |
+
"NAICS Sub Sector": naics_subsector,
|
| 327 |
+
"GICS Sector": gics_sector,
|
| 328 |
+
"GICS Industry Group": gics_industry_group,
|
| 329 |
+
"GICS Sub Industry": gics_sub_match,
|
| 330 |
+
"Supply Chain Tier": supply_chain_tier,
|
| 331 |
+
"Contagion Score": contagion_score,
|
| 332 |
+
|
| 333 |
+
"material_id": mat_id, "material_name": mat_name, "hs_code": hs, "market_ticker": ticker,
|
| 334 |
+
"origin_country_1": o1, "o1_market_share": o1_s, "origin_country_2": o2, "o2_market_share": o2_s, "origin_country_3": o3, "o3_market_share": o3_s,
|
| 335 |
+
"refining_country_1": r1, "r1_market_share": r1_s, "refining_country_2": r2, "r2_market_share": r2_s, "refining_country_3": r3, "r3_market_share": r3_s,
|
| 336 |
+
|
| 337 |
+
# --- BETA MASKING (Logistics & Substitution Logic) ---
|
| 338 |
+
"primary_transit_vehicle": "[Unlock in Beta]",
|
| 339 |
+
"cost_weight_metric": "[Unlock in Beta]",
|
| 340 |
+
"substitute_material_id": "[Unlock in Beta]",
|
| 341 |
+
"substitutability_index": "[Unlock in Beta]",
|
| 342 |
+
"search_tags": "[Unlock in Beta]"
|
| 343 |
+
}
|
| 344 |
+
rows.append(row)
|
| 345 |
+
|
| 346 |
+
final_df = pd.DataFrame(rows)
|
| 347 |
+
|
| 348 |
+
# Generate the Edge List for the Cascade
|
| 349 |
+
edges_df = build_contagion_edges(final_df)
|
| 350 |
+
|
| 351 |
+
out_csv = os.path.join(data_dir, "NAICS_Contagion_Nodes_GitHub.csv")
|
| 352 |
+
out_xlsx = os.path.join(data_dir, "NAICS_Contagion_Nodes_GitHub.xlsx")
|
| 353 |
+
edges_csv = os.path.join(data_dir, "NAICS_Contagion_Edges_GitHub.csv")
|
| 354 |
+
|
| 355 |
+
print(f"Saving mapped results to {out_csv} and {out_xlsx}...")
|
| 356 |
+
final_df.to_csv(out_csv, index=False)
|
| 357 |
+
final_df.to_excel(out_xlsx, index=False)
|
| 358 |
+
|
| 359 |
+
print(f"Saving Cascade Edge List to {edges_csv}...")
|
| 360 |
+
edges_df.to_csv(edges_csv, index=False)
|
| 361 |
+
|
| 362 |
+
print("Contagion Map & Cascades Complete!")
|
| 363 |
+
|
| 364 |
+
if __name__ == "__main__":
|
| 365 |
+
run_mapping()
|
NAICS_Contagion_Nodes_GitHub.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
NAICS_Contagion_Visualizer.html
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
README.md
CHANGED
|
@@ -1,3 +1,47 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🌐 NAICS Contagion Map: The Physical Economy Visualized
|
| 2 |
+
|
| 3 |
+
## [🚀 Join the June 2026 Beta](https://a7af2a54.sibforms.com/serve/MUIFAK4KiE6r-UBeNPKiGd_hFht_dPE_p8oCs2NOx53N8abu_SQe9HTVgRxIlg4HlA9cOsVmYs2pkeAZHGZ0XlDh2RBLa_bZZLLiaXPKpUTjgr72heyx-lYwgPb0B8dnkWsj7lw-M1jEOnzP7Oc8o12c0SG3UYsmQZRaWacaAWgweWru9S9fWYne4o43aByc7BqGSjRvnZcHXYcQ)
|
| 4 |
+
|
| 5 |
+
Welcome to the **NAICS Contagion Intelligence Map** — an open-source pipeline mapping the vulnerability cascades of the physical economy.
|
| 6 |
+
|
| 7 |
+
This repository bridges institutional supply chain taxonomies (NAICS) with financial market frameworks (GICS) to visualize how disruptions in upstream raw materials systematically ripple down to consumer goods.
|
| 8 |
+
|
| 9 |
+

|
| 10 |
+
|
| 11 |
+
## 📦 What's Included in the Drop?
|
| 12 |
+
|
| 13 |
+
1. **`NAICS_Contagion_Map.py`**
|
| 14 |
+
The core intelligence engine. It utilizes a deterministic heuristic algorithm to classify manufacturing nodes into Supply Chain Tiers (Tier 1 to Tier 4) and generate topological edge networks.
|
| 15 |
+
|
| 16 |
+
2. **`NAICS_Contagion_Nodes_GitHub.xlsx` / `.csv`**
|
| 17 |
+
The flat intelligence map. Contains 346 mapped NAICS industries, their corresponding GICS cousins, their structural Tier, and their **Contagion Score (1.0 - 10.0)**.
|
| 18 |
+
*Note: Sensitive logistics data and substitutability friction metrics are masked as `[Unlock in Beta]` to protect trade-secret competitive intelligence.*
|
| 19 |
+
|
| 20 |
+
3. **`NAICS_Contagion_Edges_GitHub.csv`**
|
| 21 |
+
The relational spiderweb. A generated list of 1,100+ topological edges showing the exact contagion cascade from Tier 4 (Commodity) -> Tier 3 (Primary Extractor) -> Tier 2 (Processor) -> Tier 1 (Final Assembler).
|
| 22 |
+
|
| 23 |
+
4. **`build_visualizer.py` & `NAICS_Contagion_Visualizer.html`**
|
| 24 |
+
A stunning, interactive Web application generated from the data. You can open the `.html` file directly in any browser (no server required) to explore the system cascades interactively via an embedded physics-driven network engine.
|
| 25 |
+
|
| 26 |
+
## 🧠 The Intelligence Framework
|
| 27 |
+
|
| 28 |
+
### The Supply Chain Tiers
|
| 29 |
+
We categorize the physical economy into four distinct levels of depth:
|
| 30 |
+
* **Tier 4 (Raw Materials):** Foundational commodities (e.g., Lithium, Crude Oil, Platinum).
|
| 31 |
+
* **Tier 3 (Primary Converters):** Heavy extractors and baseline chemical/metal converters (e.g., Basic Chemical Mfg, Primary Metal Mfg).
|
| 32 |
+
* **Tier 2 (Intermediate Processors):** Mid-stream molders and fabricators (e.g., Fabricated Metals, Plastics, Refiners).
|
| 33 |
+
* **Tier 1 (Direct Suppliers / OEMs):** Final assembly and direct-to-consumer manufacturing (e.g., Auto Manufacturing, Food Processing, Aerospace).
|
| 34 |
+
|
| 35 |
+
### The Contagion Score (1.0 - 10.0)
|
| 36 |
+
The Contagion Score quantifies systemic volatility.
|
| 37 |
+
- **High Scores (8.0+):** Indicate a systemic "anchor node". A bottleneck here causes catastrophic downstream starvation. Driven by high Upstream Concentration Risk and massive Downstream Connectivity.
|
| 38 |
+
- **Medium Scores (5.0-7.9):** Intermediate processors with some alternative pathways.
|
| 39 |
+
- **Low Scores (1.0-4.9):** Terminal nodes that can absorb localized shocks.
|
| 40 |
+
|
| 41 |
+
## 🚀 How to Use the Data
|
| 42 |
+
Import the `Edges` and `Nodes` CSVs directly into network visualization tools like Gephi, Neo4j, or Python's NetworkX to build an interactive, force-directed graph of macroeconomic risk.
|
| 43 |
+
|
| 44 |
+
---
|
| 45 |
+
|
| 46 |
+
**Contact for Enterprise Inquiry:**
|
| 47 |
+
Email Mark: `mark(at)plainr(dot)io`
|
build_visualizer.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
def generate_html():
|
| 6 |
+
print("Loading Contagion Data...")
|
| 7 |
+
|
| 8 |
+
# Load data from the current directory
|
| 9 |
+
df_nodes = pd.read_csv("NAICS_Contagion_Nodes_GitHub.csv")
|
| 10 |
+
df_edges = pd.read_csv("NAICS_Contagion_Edges_GitHub.csv")
|
| 11 |
+
|
| 12 |
+
# Build Vis.js Nodes
|
| 13 |
+
nodes = []
|
| 14 |
+
seen_nodes = set()
|
| 15 |
+
|
| 16 |
+
# Map colors to Tiers
|
| 17 |
+
color_map = {
|
| 18 |
+
'Tier 4': '#ff9f43', # Orange for Raw Materials
|
| 19 |
+
'Tier 3': '#ee5253', # Red for Primary
|
| 20 |
+
'Tier 2': '#9b59b6', # Purple for Intermediate
|
| 21 |
+
'Tier 1': '#3498db' # Blue for Final
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# Process edges to get all nodes
|
| 25 |
+
for _, e in df_edges.iterrows():
|
| 26 |
+
src = e['Source Node']
|
| 27 |
+
src_tier = e['Source Tier']
|
| 28 |
+
tgt = e['Target Node']
|
| 29 |
+
tgt_tier = e['Target Tier']
|
| 30 |
+
|
| 31 |
+
if src not in seen_nodes:
|
| 32 |
+
seen_nodes.add(src)
|
| 33 |
+
nodes.append({
|
| 34 |
+
"id": src,
|
| 35 |
+
"label": src,
|
| 36 |
+
"group": src_tier,
|
| 37 |
+
"color": color_map.get(src_tier, '#bdc3c7'),
|
| 38 |
+
"value": 20 if src_tier == 'Tier 4' else 10,
|
| 39 |
+
"title": f"<b>{src}</b><br>{src_tier}"
|
| 40 |
+
})
|
| 41 |
+
|
| 42 |
+
if tgt not in seen_nodes:
|
| 43 |
+
seen_nodes.add(tgt)
|
| 44 |
+
# Find contagion score for target
|
| 45 |
+
node_data = df_nodes[df_nodes['Primary Name'] == tgt]
|
| 46 |
+
score = 5.0
|
| 47 |
+
if not node_data.empty:
|
| 48 |
+
score = float(node_data.iloc[0]['Contagion Score'])
|
| 49 |
+
|
| 50 |
+
nodes.append({
|
| 51 |
+
"id": tgt,
|
| 52 |
+
"label": tgt,
|
| 53 |
+
"group": tgt_tier,
|
| 54 |
+
"color": color_map.get(tgt_tier, '#bdc3c7'),
|
| 55 |
+
"value": score * 3, # Scale for visualization
|
| 56 |
+
"title": f"<b>{tgt}</b><br>{tgt_tier}<br>Contagion Score: {score}"
|
| 57 |
+
})
|
| 58 |
+
|
| 59 |
+
# Build Vis.js Edges
|
| 60 |
+
edges = []
|
| 61 |
+
for _, e in df_edges.iterrows():
|
| 62 |
+
edges.append({
|
| 63 |
+
"from": e['Source Node'],
|
| 64 |
+
"to": e['Target Node'],
|
| 65 |
+
"title": e['Edge Type'],
|
| 66 |
+
"arrows": "to",
|
| 67 |
+
"color": {"color": "rgba(255,255,255,0.2)", "highlight": "rgba(255,255,255,0.8)"}
|
| 68 |
+
})
|
| 69 |
+
|
| 70 |
+
nodes_json = json.dumps(nodes)
|
| 71 |
+
edges_json = json.dumps(edges)
|
| 72 |
+
|
| 73 |
+
# --- STUNNING HTML TEMPLATE (Dark Mode, Glassmorphism) ---
|
| 74 |
+
html_content = f"""
|
| 75 |
+
<!DOCTYPE html>
|
| 76 |
+
<html lang="en">
|
| 77 |
+
<head>
|
| 78 |
+
<meta charset="UTF-8">
|
| 79 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 80 |
+
<title>NAICS Contagion Intelligence Map</title>
|
| 81 |
+
<script type="text/javascript" src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
|
| 82 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;800&display=swap" rel="stylesheet">
|
| 83 |
+
<style>
|
| 84 |
+
body {{
|
| 85 |
+
margin: 0;
|
| 86 |
+
padding: 0;
|
| 87 |
+
background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%);
|
| 88 |
+
color: #f8fafc;
|
| 89 |
+
font-family: 'Inter', sans-serif;
|
| 90 |
+
overflow: hidden;
|
| 91 |
+
display: flex;
|
| 92 |
+
height: 100vh;
|
| 93 |
+
}}
|
| 94 |
+
|
| 95 |
+
#mynetwork {{
|
| 96 |
+
flex-grow: 1;
|
| 97 |
+
height: 100%;
|
| 98 |
+
outline: none;
|
| 99 |
+
}}
|
| 100 |
+
|
| 101 |
+
/* Glassmorphism Sidebar */
|
| 102 |
+
.sidebar {{
|
| 103 |
+
width: 380px;
|
| 104 |
+
height: 100%;
|
| 105 |
+
background: rgba(15, 23, 42, 0.6);
|
| 106 |
+
backdrop-filter: blur(16px);
|
| 107 |
+
-webkit-backdrop-filter: blur(16px);
|
| 108 |
+
border-left: 1px solid rgba(255, 255, 255, 0.1);
|
| 109 |
+
padding: 40px 30px;
|
| 110 |
+
box-sizing: border-box;
|
| 111 |
+
display: flex;
|
| 112 |
+
flex-direction: column;
|
| 113 |
+
z-index: 10;
|
| 114 |
+
box-shadow: -10px 0 30px rgba(0,0,0,0.5);
|
| 115 |
+
}}
|
| 116 |
+
|
| 117 |
+
.header h1 {{
|
| 118 |
+
font-size: 24px;
|
| 119 |
+
font-weight: 800;
|
| 120 |
+
margin: 0 0 10px 0;
|
| 121 |
+
background: -webkit-linear-gradient(45deg, #38bdf8, #818cf8);
|
| 122 |
+
-webkit-background-clip: text;
|
| 123 |
+
-webkit-text-fill-color: transparent;
|
| 124 |
+
letter-spacing: -0.5px;
|
| 125 |
+
}}
|
| 126 |
+
|
| 127 |
+
.header p {{
|
| 128 |
+
font-size: 13px;
|
| 129 |
+
color: #94a3b8;
|
| 130 |
+
line-height: 1.6;
|
| 131 |
+
margin-bottom: 30px;
|
| 132 |
+
}}
|
| 133 |
+
|
| 134 |
+
.legend {{
|
| 135 |
+
background: rgba(255,255,255,0.03);
|
| 136 |
+
border-radius: 12px;
|
| 137 |
+
padding: 20px;
|
| 138 |
+
border: 1px solid rgba(255,255,255,0.05);
|
| 139 |
+
margin-bottom: 30px;
|
| 140 |
+
}}
|
| 141 |
+
|
| 142 |
+
.legend-title {{
|
| 143 |
+
font-size: 11px;
|
| 144 |
+
text-transform: uppercase;
|
| 145 |
+
letter-spacing: 1px;
|
| 146 |
+
color: #64748b;
|
| 147 |
+
margin-bottom: 15px;
|
| 148 |
+
font-weight: 600;
|
| 149 |
+
}}
|
| 150 |
+
|
| 151 |
+
.legend-item {{
|
| 152 |
+
display: flex;
|
| 153 |
+
align-items: center;
|
| 154 |
+
margin-bottom: 12px;
|
| 155 |
+
font-size: 14px;
|
| 156 |
+
}}
|
| 157 |
+
|
| 158 |
+
.color-dot {{
|
| 159 |
+
width: 12px;
|
| 160 |
+
height: 12px;
|
| 161 |
+
border-radius: 50%;
|
| 162 |
+
margin-right: 12px;
|
| 163 |
+
box-shadow: 0 0 10px currentColor;
|
| 164 |
+
}}
|
| 165 |
+
|
| 166 |
+
.node-info {{
|
| 167 |
+
margin-top: auto;
|
| 168 |
+
background: rgba(0,0,0,0.3);
|
| 169 |
+
border-radius: 12px;
|
| 170 |
+
padding: 20px;
|
| 171 |
+
border: 1px solid rgba(255,255,255,0.05);
|
| 172 |
+
display: none;
|
| 173 |
+
}}
|
| 174 |
+
|
| 175 |
+
.node-info h3 {{ margin: 0 0 10px 0; font-size: 16px; color: #fff; }}
|
| 176 |
+
.node-info p {{ margin: 5px 0; font-size: 13px; color: #cbd5e1; }}
|
| 177 |
+
.badge {{
|
| 178 |
+
display: inline-block;
|
| 179 |
+
padding: 4px 8px;
|
| 180 |
+
border-radius: 4px;
|
| 181 |
+
font-size: 11px;
|
| 182 |
+
font-weight: 600;
|
| 183 |
+
background: rgba(255,255,255,0.1);
|
| 184 |
+
margin-top: 10px;
|
| 185 |
+
}}
|
| 186 |
+
|
| 187 |
+
/* Floating branding */
|
| 188 |
+
.brand {{
|
| 189 |
+
position: absolute;
|
| 190 |
+
bottom: 30px;
|
| 191 |
+
left: 30px;
|
| 192 |
+
font-size: 12px;
|
| 193 |
+
color: rgba(255,255,255,0.3);
|
| 194 |
+
pointer-events: none;
|
| 195 |
+
letter-spacing: 2px;
|
| 196 |
+
font-weight: 600;
|
| 197 |
+
}}
|
| 198 |
+
</style>
|
| 199 |
+
</head>
|
| 200 |
+
<body>
|
| 201 |
+
|
| 202 |
+
<div id="mynetwork"></div>
|
| 203 |
+
<div class="brand">NAICS CONTAGION INTELLIGENCE</div>
|
| 204 |
+
|
| 205 |
+
<div class="sidebar">
|
| 206 |
+
<div class="header">
|
| 207 |
+
<h1>Contagion Cascade</h1>
|
| 208 |
+
<p>Interactive mapping of systemic vulnerability across the NAICS physical economy. Nodes are sized by Contagion Score.</p>
|
| 209 |
+
</div>
|
| 210 |
+
|
| 211 |
+
<div class="legend">
|
| 212 |
+
<div class="legend-title">Supply Chain Hierarchy</div>
|
| 213 |
+
<div class="legend-item"><div class="color-dot" style="color: #ff9f43; background: #ff9f43;"></div> Tier 4: Raw Commodity</div>
|
| 214 |
+
<div class="legend-item"><div class="color-dot" style="color: #ee5253; background: #ee5253;"></div> Tier 3: Primary Extractor</div>
|
| 215 |
+
<div class="legend-item"><div class="color-dot" style="color: #9b59b6; background: #9b59b6;"></div> Tier 2: Intermediate Processor</div>
|
| 216 |
+
<div class="legend-item"><div class="color-dot" style="color: #3498db; background: #3498db;"></div> Tier 1: Final Assembly</div>
|
| 217 |
+
</div>
|
| 218 |
+
|
| 219 |
+
<div class="node-info" id="nodeInfo">
|
| 220 |
+
<h3 id="ni-title">Node Name</h3>
|
| 221 |
+
<p id="ni-tier">Tier: --</p>
|
| 222 |
+
<p id="ni-score">Contagion Score: --</p>
|
| 223 |
+
<div class="badge" id="ni-badge">Systemic Node</div>
|
| 224 |
+
</div>
|
| 225 |
+
</div>
|
| 226 |
+
|
| 227 |
+
<script type="text/javascript">
|
| 228 |
+
// Inject Data
|
| 229 |
+
var nodes = new vis.DataSet({nodes_json});
|
| 230 |
+
var edges = new vis.DataSet({edges_json});
|
| 231 |
+
|
| 232 |
+
var container = document.getElementById('mynetwork');
|
| 233 |
+
var data = {{
|
| 234 |
+
nodes: nodes,
|
| 235 |
+
edges: edges
|
| 236 |
+
}};
|
| 237 |
+
|
| 238 |
+
var options = {{
|
| 239 |
+
nodes: {{
|
| 240 |
+
shape: 'dot',
|
| 241 |
+
font: {{ color: '#ffffff', size: 12, face: 'Inter', strokeWidth: 2, strokeColor: '#0f172a' }},
|
| 242 |
+
borderWidth: 2,
|
| 243 |
+
shadow: true
|
| 244 |
+
}},
|
| 245 |
+
edges: {{
|
| 246 |
+
smooth: {{ type: 'continuous' }}
|
| 247 |
+
}},
|
| 248 |
+
physics: {{
|
| 249 |
+
forceAtlas2Based: {{
|
| 250 |
+
gravitationalConstant: -80,
|
| 251 |
+
centralGravity: 0.005,
|
| 252 |
+
springLength: 200,
|
| 253 |
+
springConstant: 0.04,
|
| 254 |
+
damping: 0.65
|
| 255 |
+
}},
|
| 256 |
+
maxVelocity: 8,
|
| 257 |
+
solver: 'forceAtlas2Based',
|
| 258 |
+
timestep: 0.15,
|
| 259 |
+
stabilization: {{ iterations: 150 }}
|
| 260 |
+
}},
|
| 261 |
+
interaction: {{
|
| 262 |
+
hover: true,
|
| 263 |
+
tooltipDelay: 200
|
| 264 |
+
}}
|
| 265 |
+
}};
|
| 266 |
+
|
| 267 |
+
var network = new vis.Network(container, data, options);
|
| 268 |
+
|
| 269 |
+
// Interaction Events for the sidebar
|
| 270 |
+
network.on("selectNode", function (params) {{
|
| 271 |
+
if (params.nodes.length == 1) {{
|
| 272 |
+
var nodeId = params.nodes[0];
|
| 273 |
+
var node = nodes.get(nodeId);
|
| 274 |
+
|
| 275 |
+
document.getElementById('nodeInfo').style.display = 'block';
|
| 276 |
+
document.getElementById('ni-title').innerText = node.label;
|
| 277 |
+
document.getElementById('ni-tier').innerText = node.group;
|
| 278 |
+
|
| 279 |
+
// Extract score from title or set to NA
|
| 280 |
+
var score = "N/A";
|
| 281 |
+
if(node.title.includes("Contagion Score")) {{
|
| 282 |
+
score = node.title.split("Contagion Score: ")[1];
|
| 283 |
+
document.getElementById('ni-badge').style.display = parseFloat(score) > 8.0 ? 'inline-block' : 'none';
|
| 284 |
+
if(parseFloat(score) > 8.0) document.getElementById('ni-badge').innerText = 'Critical Anchor Node';
|
| 285 |
+
}} else {{
|
| 286 |
+
document.getElementById('ni-badge').style.display = 'none';
|
| 287 |
+
}}
|
| 288 |
+
document.getElementById('ni-score').innerText = "Contagion Score: " + score;
|
| 289 |
+
}}
|
| 290 |
+
}});
|
| 291 |
+
|
| 292 |
+
network.on("deselectNode", function (params) {{
|
| 293 |
+
document.getElementById('nodeInfo').style.display = 'none';
|
| 294 |
+
}});
|
| 295 |
+
</script>
|
| 296 |
+
</body>
|
| 297 |
+
</html>
|
| 298 |
+
"""
|
| 299 |
+
|
| 300 |
+
out_path = "NAICS_Contagion_Visualizer.html"
|
| 301 |
+
with open(out_path, "w", encoding="utf-8") as f:
|
| 302 |
+
f.write(html_content)
|
| 303 |
+
|
| 304 |
+
print(f"Visualization generated successfully at: {out_path}")
|
| 305 |
+
|
| 306 |
+
if __name__ == "__main__":
|
| 307 |
+
generate_html()
|