network-visualization 1.0.4
Tools for visualizing and analyzing electrical grid network topology
License: MIT
Requires Python: >=3.8
Keywords: network, visualization, graph, energy, electrical-grid

# Network Visualization

[![PyPI](https://img.shields.io/badge/PyPI-v1.0.4-blue)](https://pypi.org/project/network-visualization/)
[![Python](https://img.shields.io/badge/Python-3.8%2B-brightgreen)](https://www.python.org/)
[![License](https://img.shields.io/badge/License-MIT-orange)](LICENSE)

Interactive visualization and analysis tools for Calliope energy system models. Extract and visualize network topology with a single line of code.

## ✨ Features

- **Universal Data Extraction**: Handles ANY Calliope naming structure and format
- **World Map Visualization**: Global projection with natural earth map (NEW v1.0.3)
- **Multi-File Import Support**: Resolves Calliope `import:` directives across files (NEW v1.0.3)
- **Scenarios & Overrides**: Full support for Calliope scenarios and runtime overrides (NEW v1.0.3)
- **One-Line Visualization**: Create interactive HTML visualizations instantly  
- **Connectivity Analysis**: Identify isolated nodes and network components
- **Flexible Format Support**: Works with any coordinate system (lat/lon, x/y, custom)
- **Smart Type Detection**: Automatically classifies generation, demand, and transmission nodes

## 🚀 Quick Start

### Installation

```bash
pip install network-visualization
```

That's it! No configuration needed.

### Usage in Your Script

**Option 1: Single import, one line**
```python
import network_visualization as nv

# Visualize (creates interactive HTML file)
nv.plot_network("path/to/your/calliope/model")
```

**Option 2: Complete analysis**
```python
import network_visualization as nv

# Analyze your model
results = nv.analyze_network("path/to/your/calliope/model")

# Check results
print(f"Network has {results['num_components']} components")
print(f"Isolated nodes: {results['isolated_nodes']}")
```

**Option 3: Copy-paste ready example**
```python
# Save this as visualize.py and run: python visualize.py
import network_visualization as nv

# Replace with your model path
MODEL_PATH = "C:/path/to/your/calliope/model"

# Create visualization
nv.plot_network(
    model_path=MODEL_PATH,
    output_file="my_network.html",
    title="My Energy Network"
)

print("✓ Visualization saved as my_network.html")
```

### Real Example with Your Model

```python
import network_visualization as nv

# Your model path (where locations.yaml is located)
model_path = "C:/Users/YourName/my_calliope_model"

# Option A: Quick visualization
nv.quick_viz(model_path)  # Opens in browser automatically

# Option B: Detailed analysis
analysis = nv.analyze_network(model_path)
print(f"Total locations: {analysis['total_nodes']}")
print(f"Total connections: {analysis['total_edges']}")
print(f"Network components: {analysis['num_components']}")
print(f"Isolated nodes: {analysis['isolated_nodes']}")
```

## 📖 Complete API Reference

### All Functions

```python
import network_visualization as nv

# Main functions (most commonly used)
nv.plot_network(model_path, ...)        # Create visualization
nv.analyze_network(model_path, ...)     # Analyze connectivity
nv.quick_viz(model_path)                # Fast visualization
nv.find_isolated_nodes(model_path)      # Find isolated nodes
nv.suggest_connections(model_path, ...) # Get connection suggestions
```

---

### `plot_network()` - Create Visualization

**Simple usage:**
```python
nv.plot_network("path/to/model")  # Creates network_visualization.html
```

**Advanced usage:**
```python
nv.plot_network(
    model_path="C:/my_models/chile",    # Required: your model path
    output_file="my_network.html",       # Optional: output filename
    auto_open=True,                      # Optional: open in browser
    title="Chile Energy Network"         # Optional: custom title
)
```

**Returns:** String with path to created HTML file

---

### `analyze_network()` - Analyze Connectivity

**Simple usage:**
```python
results = nv.analyze_network("path/to/model")
print(results['num_components'])   # How many disconnected parts
print(results['isolated_nodes'])   # List of isolated nodes
```

**Advanced usage:**
```python
results = nv.analyze_network(
    model_path="C:/my_models/chile",
    save_report=True,                  # Save report to file
    output_dir="my_reports"            # Where to save report
)

**Returns:** Dictionary with analysis results:
```python
{
    'num_components': int,         # Number of connected components
    'isolated_nodes': list,        # List of isolated node names
    'demand_isolated': set,        # Demand substations that are isolated
    'is_fully_connected': bool,    # Whether network is fully connected
    'total_nodes': int,            # Total nodes in graph
    'total_edges': int,            # Total edges in graph
    'components': list             # List of component sets
}
```

---

### `find_isolated_nodes(model_path)`

Find all isolated nodes in the network.

**Returns:** Dictionary with isolated node lists:
```python
{
    'all_isolated': list,          # All isolated nodes
    'isolated_with_demand': list   # Isolated nodes with demand
}
```

---

### `suggest_connections(model_path, max_distance_km, top_n)`

Get smart connection suggestions based on proximity.

**Parameters:**
- `model_path` (str): Path to Calliope model directory
- `max_distance_km` (float, optional): Maximum connection distance. Default: `100`
- `top_n` (int, optional): Number of suggestions to return. Default: `10`

**Returns:** List of suggested connections with distances

---

### `quick_viz(model_path)`

Fastest way to visualize - one function call with all defaults.

---

## 🌍 Advanced Features (v1.0.3)

### Multi-File Imports

The package now automatically resolves Calliope `import:` directives across multiple files:

```yaml
# model.yaml
import:
  - locations.yaml
  - techs.yaml

# locations.yaml
locations:
  region1:
    coordinates: {lat: 40, lon: -2}
```

**Usage:** Just point to your model - imports are handled automatically!

```python
nv.plot_network("path/to/model")  # Imports resolved automatically
```

### Scenarios

Apply Calliope scenarios to visualize different configurations:

```python
# Visualize with a specific scenario
nv.plot_network(
    model_path="path/to/model",
    scenario="high_cost",           # Apply 'high_cost' scenario
    title="High Cost Scenario"
)

# Analyze with scenario
results = nv.analyze_network(
    model_path="path/to/model",
    scenario="high_cost"
)
```

### Runtime Overrides

Apply custom overrides without modifying your model files:

```python
# Define overrides
overrides = {
    "locations.region1.coordinates.lat": 41.5,
    "locations.region1.coordinates.lon": -3.2,
    "links.region1,region2.distance": 150
}

# Visualize with overrides
nv.plot_network(
    model_path="path/to/model",
    override_dict=overrides,
    title="Modified Network"
)

# Combine scenario and overrides
nv.plot_network(
    model_path="path/to/model",
    scenario="high_cost",
    override_dict=overrides
)
```

### World Map Projection

All visualizations now use a world map with natural earth projection, perfect for global or multi-regional models.

---

## 🎯 Calliope Format Support

This package handles **any Calliope model structure**:

### Standard Format
```yaml
locations:
  region1:
    coordinates: {lat: 40, lon: -2}
    techs: {ccgt:, demand_power:}
```

### Split Coordinates
```yaml
locations:
  region1-1.coordinates:  # or region1:coords, region1_position, etc.
    lat: 41
    lon: -2
```

### Shared Technologies
```yaml
locations:
  "region1-1, region1-2, region1-3":  # or region1-1|region1-2|region1-3
    techs: {csp:}
```

### Any Coordinate System
- **Geographic**: `lat/lon`, `latitude/longitude`  
- **Cartesian**: `x/y`
- **Custom**: Any numeric coordinate pairs

### Flexible Naming
No restrictions on naming patterns:
- **Delimiters**: `.`, `:`, `_`, `-`, `|`, `,`
- **Suffixes**: `coordinates`, `coords`, `position`, `latlon`, etc.
- **Patterns**: Any naming convention (regions, nodes, stations, areas, etc.)

The parser automatically detects and handles all patterns!

## 📊 Example Output

### Visualization
Interactive HTML with:
- Color-coded nodes (generation, demand, transmission)
- Hover info showing technologies
- Zoom and pan navigation
- Network statistics overlay

### Analysis Report
```
================================================================================
NETWORK ANALYSIS REPORT
================================================================================

1. NETWORK SUMMARY
   Total Locations: 9
     - Power Plants: 5
     - Substations with Demand: 0
     - Transmission Nodes: 1

   Total Connections: 9
     - Power Links: 2
     - Transmission Links: 7

2. CONNECTIVITY ANALYSIS
   Connected Components: 1
   [OK] Network is fully connected
   [OK] No isolated nodes

3. DEMAND SUBSTATIONS STATUS
   [OK] All demand substations are connected
================================================================================
```

## 📁 Project Structure

```
network_visualization/
├── network_visualization.py    # Main API module
├── setup.py                    # Package configuration
├── requirements.txt            # Dependencies
├── README.md                   # This file
│
├── utils/                      # Core utilities
│   ├── load_data.py           # Universal data loader
│   ├── graph_builder.py       # Network graph construction
│   ├── geo_utils.py           # Geographic calculations
│   └── report_generator.py    # Report generation
│
├── scripts/                    # Command-line tools
│   ├── visualize_network.py
│   ├── analyze_isolated.py
│   └── suggest_connections.py
│
└── examples/                   # Usage examples
    └── basic_visualization.py
```

## 🛠️ Requirements

- Python 3.8+
- All dependencies install automatically with `pip install network-visualization`

## ❓ Troubleshooting

### "Module not found"
```bash
# Make sure it's installed in your current environment
pip install network-visualization

# Check installation
pip show network-visualization
```

### "Can't find my model"
Make sure you point to the **model directory** (the folder containing `model_config/`):
```python
# ✓ Correct - points to model directory
nv.plot_network("C:/my_models/national_scale")

# ✗ Wrong - points to locations.yaml file
nv.plot_network("C:/my_models/national_scale/model_config/locations.yaml")
```

### Model structure requirements
Your Calliope model should have this structure:
```
your_model/
└── model_config/
    └── locations.yaml    # Required
```

### Import error in script
If you get import errors, use the full import:
```python
import network_visualization as nv
# Not: from network_visualization import plot_network
```

### Still having issues?
1. Check Python version: `python --version` (needs 3.8+)
2. Reinstall: `pip uninstall network-visualization && pip install network-visualization`
3. Try the simple example from `examples/simple_example.py`

## 📝 Development

```bash
# Clone repository
git clone https://mygit.th-deg.de/thd-spatial-ai/example_models/calliope_plots.git
cd calliope_plots

# Install in development mode
pip install -e .

# Run tests
python -m pytest tests/
```

## 🤝 Contributing

Contributions welcome! Please:
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/improvement`)
3. Commit changes (`git commit -m 'Add improvement'`)
4. Push to branch (`git push origin feature/improvement`)
5. Open a Pull Request

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🔗 Links

- **PyPI**: https://pypi.org/project/network-visualization/
- **GitLab**: https://mygit.th-deg.de/thd-spatial-ai/example_models/calliope_plots
- **Calliope**: https://calliope.readthedocs.io/

## 🙏 Acknowledgments

Built for Calliope energy system modeling framework. Supports any Calliope model structure with universal data extraction.

---

**Version**: 1.0.3 | **Updated**: December 2025