tranpy-ai 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tranpy/__init__.py +28 -0
- tranpy/data/__init__.py +14 -0
- tranpy/data/cache.py +183 -0
- tranpy/data/datasets/registry.json +52 -0
- tranpy/data/download.py +150 -0
- tranpy/data/models/registry.json +844 -0
- tranpy/datasets/__init__.py +23 -0
- tranpy/datasets/base.py +65 -0
- tranpy/datasets/loaders.py +268 -0
- tranpy/explainers/__init__.py +34 -0
- tranpy/explainers/base.py +65 -0
- tranpy/explainers/dalex.py +247 -0
- tranpy/explainers/lime.py +269 -0
- tranpy/explainers/shap.py +316 -0
- tranpy/models/__init__.py +92 -0
- tranpy/models/base.py +160 -0
- tranpy/models/classical.py +960 -0
- tranpy/models/ensemble.py +195 -0
- tranpy/models/neural.py +293 -0
- tranpy/models/pretrained.py +255 -0
- tranpy/simulation/__init__.py +119 -0
- tranpy/simulation/config.py +340 -0
- tranpy/simulation/dataset_generator.py +320 -0
- tranpy/simulation/events.py +371 -0
- tranpy/simulation/mock_engine.py +364 -0
- tranpy/simulation/model.py +358 -0
- tranpy/simulation/powerfactory_config.py +236 -0
- tranpy/simulation/results.py +287 -0
- tranpy/simulation/simulator.py +501 -0
- tranpy/utils/__init__.py +11 -0
- tranpy/utils/config.py +70 -0
- tranpy/utils/io.py +64 -0
- tranpy/utils/logging.py +144 -0
- tranpy_ai-0.1.0.dist-info/METADATA +115 -0
- tranpy_ai-0.1.0.dist-info/RECORD +37 -0
- tranpy_ai-0.1.0.dist-info/WHEEL +5 -0
- tranpy_ai-0.1.0.dist-info/top_level.txt +1 -0
tranpy/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TranPy: Power System Transient Stability Analysis
|
|
3
|
+
|
|
4
|
+
A modern Python library for power system stability prediction and explainability.
|
|
5
|
+
|
|
6
|
+
Example usage:
|
|
7
|
+
>>> from tranpy.datasets import load_newengland
|
|
8
|
+
>>> from tranpy.models import SVMClassifier
|
|
9
|
+
>>>
|
|
10
|
+
>>> # Load data
|
|
11
|
+
>>> X_train, X_test, y_train, y_test = load_newengland(test_size=0.2)
|
|
12
|
+
>>>
|
|
13
|
+
>>> # Train model
|
|
14
|
+
>>> model = SVMClassifier()
|
|
15
|
+
>>> model.fit(X_train, y_train)
|
|
16
|
+
>>>
|
|
17
|
+
>>> # Evaluate
|
|
18
|
+
>>> accuracy = model.score(X_test, y_test)
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
__version__ = "0.1.0"
|
|
22
|
+
|
|
23
|
+
# Import main modules
|
|
24
|
+
from . import datasets
|
|
25
|
+
from . import models
|
|
26
|
+
from . import explainers
|
|
27
|
+
|
|
28
|
+
__all__ = ['datasets', 'models', 'explainers', '__version__']
|
tranpy/data/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TranPy Data Management Module
|
|
3
|
+
|
|
4
|
+
Handles data and model storage, caching, and downloading.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .download import download_from_google_drive
|
|
8
|
+
from .cache import get_cache_dir, clear_cache
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
'download_from_google_drive',
|
|
12
|
+
'get_cache_dir',
|
|
13
|
+
'clear_cache'
|
|
14
|
+
]
|
tranpy/data/cache.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Cache management for TranPy."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import shutil
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Optional, Dict
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
|
|
9
|
+
from ..utils.logging import get_logger
|
|
10
|
+
|
|
11
|
+
logger = get_logger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_cache_dir() -> Path:
|
|
15
|
+
"""
|
|
16
|
+
Get TranPy cache directory.
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
Path to ~/.tranpy/ cache directory
|
|
20
|
+
|
|
21
|
+
Examples:
|
|
22
|
+
>>> from tranpy.data import get_cache_dir
|
|
23
|
+
>>> cache_dir = get_cache_dir()
|
|
24
|
+
>>> print(cache_dir)
|
|
25
|
+
/Users/username/.tranpy
|
|
26
|
+
"""
|
|
27
|
+
cache_dir = Path.home() / '.tranpy'
|
|
28
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
29
|
+
return cache_dir
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get_models_cache_dir() -> Path:
|
|
33
|
+
"""Get directory for cached pretrained models."""
|
|
34
|
+
models_dir = get_cache_dir() / 'models'
|
|
35
|
+
models_dir.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
return models_dir
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_datasets_cache_dir() -> Path:
|
|
40
|
+
"""Get directory for cached datasets."""
|
|
41
|
+
datasets_dir = get_cache_dir() / 'datasets'
|
|
42
|
+
datasets_dir.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
return datasets_dir
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def get_cache_info() -> Dict:
|
|
47
|
+
"""
|
|
48
|
+
Get information about cached files.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
Dictionary with cache statistics
|
|
52
|
+
|
|
53
|
+
Examples:
|
|
54
|
+
>>> from tranpy.data import get_cache_info
|
|
55
|
+
>>> info = get_cache_info()
|
|
56
|
+
>>> print(f"Cache size: {info['total_size_mb']:.1f} MB")
|
|
57
|
+
"""
|
|
58
|
+
cache_dir = get_cache_dir()
|
|
59
|
+
|
|
60
|
+
if not cache_dir.exists():
|
|
61
|
+
return {
|
|
62
|
+
'cache_dir': str(cache_dir),
|
|
63
|
+
'exists': False,
|
|
64
|
+
'total_size_mb': 0,
|
|
65
|
+
'num_models': 0,
|
|
66
|
+
'num_datasets': 0
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
# Calculate total size
|
|
70
|
+
total_size = sum(
|
|
71
|
+
f.stat().st_size for f in cache_dir.rglob('*') if f.is_file()
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
# Count cached items
|
|
75
|
+
models_dir = cache_dir / 'models'
|
|
76
|
+
datasets_dir = cache_dir / 'datasets'
|
|
77
|
+
|
|
78
|
+
num_models = len(list(models_dir.glob('*.pkl'))) if models_dir.exists() else 0
|
|
79
|
+
num_datasets = len(list(datasets_dir.glob('*.pickle'))) if datasets_dir.exists() else 0
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
'cache_dir': str(cache_dir),
|
|
83
|
+
'exists': True,
|
|
84
|
+
'total_size_mb': total_size / (1024 * 1024),
|
|
85
|
+
'num_models': num_models,
|
|
86
|
+
'num_datasets': num_datasets,
|
|
87
|
+
'models_dir': str(models_dir) if models_dir.exists() else None,
|
|
88
|
+
'datasets_dir': str(datasets_dir) if datasets_dir.exists() else None
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def clear_cache(confirm: bool = True) -> None:
|
|
93
|
+
"""
|
|
94
|
+
Clear TranPy cache directory.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
confirm: If True, ask for confirmation before clearing
|
|
98
|
+
|
|
99
|
+
Examples:
|
|
100
|
+
>>> from tranpy.data import clear_cache
|
|
101
|
+
>>> clear_cache() # Will ask for confirmation
|
|
102
|
+
>>> clear_cache(confirm=False) # Clear without asking
|
|
103
|
+
"""
|
|
104
|
+
cache_dir = get_cache_dir()
|
|
105
|
+
|
|
106
|
+
if not cache_dir.exists():
|
|
107
|
+
logger.info(f"Cache directory does not exist: {cache_dir}")
|
|
108
|
+
return
|
|
109
|
+
|
|
110
|
+
# Get info before clearing
|
|
111
|
+
info = get_cache_info()
|
|
112
|
+
|
|
113
|
+
if confirm:
|
|
114
|
+
response = input(
|
|
115
|
+
f"Are you sure you want to clear the cache?\n"
|
|
116
|
+
f" Location: {cache_dir}\n"
|
|
117
|
+
f" Size: {info['total_size_mb']:.1f} MB\n"
|
|
118
|
+
f" Models: {info['num_models']}\n"
|
|
119
|
+
f" Datasets: {info['num_datasets']}\n"
|
|
120
|
+
f"Type 'yes' to confirm: "
|
|
121
|
+
)
|
|
122
|
+
if response.lower() != 'yes':
|
|
123
|
+
logger.info("Cache clear cancelled.")
|
|
124
|
+
return
|
|
125
|
+
|
|
126
|
+
# Clear cache
|
|
127
|
+
shutil.rmtree(cache_dir)
|
|
128
|
+
logger.info(f"Cache cleared: {cache_dir}")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def save_cache_metadata(model_id: str, metadata: Dict) -> None:
|
|
132
|
+
"""
|
|
133
|
+
Save metadata for a cached model.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
model_id: Model identifier
|
|
137
|
+
metadata: Metadata dictionary
|
|
138
|
+
"""
|
|
139
|
+
cache_dir = get_cache_dir()
|
|
140
|
+
metadata_file = cache_dir / 'cache_metadata.json'
|
|
141
|
+
|
|
142
|
+
# Load existing metadata
|
|
143
|
+
if metadata_file.exists():
|
|
144
|
+
with open(metadata_file, 'r') as f:
|
|
145
|
+
all_metadata = json.load(f)
|
|
146
|
+
else:
|
|
147
|
+
all_metadata = {}
|
|
148
|
+
|
|
149
|
+
# Add new metadata
|
|
150
|
+
all_metadata[model_id] = {
|
|
151
|
+
**metadata,
|
|
152
|
+
'cached_at': datetime.now().isoformat()
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
# Save
|
|
156
|
+
with open(metadata_file, 'w') as f:
|
|
157
|
+
json.dump(all_metadata, f, indent=2)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def get_cache_metadata(model_id: Optional[str] = None) -> Dict:
|
|
161
|
+
"""
|
|
162
|
+
Get metadata for cached models.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
model_id: If provided, get metadata for specific model.
|
|
166
|
+
Otherwise, get all metadata.
|
|
167
|
+
|
|
168
|
+
Returns:
|
|
169
|
+
Metadata dictionary
|
|
170
|
+
"""
|
|
171
|
+
cache_dir = get_cache_dir()
|
|
172
|
+
metadata_file = cache_dir / 'cache_metadata.json'
|
|
173
|
+
|
|
174
|
+
if not metadata_file.exists():
|
|
175
|
+
return {} if model_id is None else None
|
|
176
|
+
|
|
177
|
+
with open(metadata_file, 'r') as f:
|
|
178
|
+
all_metadata = json.load(f)
|
|
179
|
+
|
|
180
|
+
if model_id:
|
|
181
|
+
return all_metadata.get(model_id)
|
|
182
|
+
else:
|
|
183
|
+
return all_metadata
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": "0.1.0",
|
|
3
|
+
"description": "TranPy Dataset Registry - Power System Stability Datasets",
|
|
4
|
+
"datasets": {
|
|
5
|
+
"NewEngland": {
|
|
6
|
+
"name": "New England 39-Bus System",
|
|
7
|
+
"description": "IEEE New England 39-bus test system for transient stability analysis. Contains voltage magnitudes and phase angles post-fault for stability prediction.",
|
|
8
|
+
"grid_type": "NewEngland",
|
|
9
|
+
"n_buses": 39,
|
|
10
|
+
"n_features": 78,
|
|
11
|
+
"feature_description": "39 voltage magnitudes (bus_X:u) + 39 phase angles (bus_X:phi)",
|
|
12
|
+
"size_mb": 8.9,
|
|
13
|
+
"format": "pickle",
|
|
14
|
+
"google_drive": {
|
|
15
|
+
"file_id": "1eXtw44VXhYM0jQyJGGY5Eevdrg8yui0w",
|
|
16
|
+
"direct_link": "https://drive.google.com/uc?export=download&id=1eXtw44VXhYM0jQyJGGY5Eevdrg8yui0w",
|
|
17
|
+
"view_link": "https://drive.google.com/file/d/1eXtw44VXhYM0jQyJGGY5Eevdrg8yui0w/view?usp=drive_link"
|
|
18
|
+
},
|
|
19
|
+
"filename": "NewEngland.pickle",
|
|
20
|
+
"bundled": true,
|
|
21
|
+
"local_path": "datasets/NewEngland.pickle",
|
|
22
|
+
"metadata": {
|
|
23
|
+
"system_type": "Transmission System",
|
|
24
|
+
"voltage_level": "High Voltage",
|
|
25
|
+
"typical_use": "Transient stability analysis, ML benchmarking"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"NineBusSystem": {
|
|
29
|
+
"name": "IEEE 9-Bus System",
|
|
30
|
+
"description": "IEEE 9-bus test system (also known as WSCC 9-bus system) for transient stability analysis. Standard benchmark for power system studies.",
|
|
31
|
+
"grid_type": "NineBusSystem",
|
|
32
|
+
"n_buses": 9,
|
|
33
|
+
"n_features": 18,
|
|
34
|
+
"feature_description": "9 voltage magnitudes (bus_X:u) + 9 phase angles (bus_X:phi)",
|
|
35
|
+
"size_mb": 2.1,
|
|
36
|
+
"format": "pickle",
|
|
37
|
+
"google_drive": {
|
|
38
|
+
"file_id": "1-4LrEqmDP6-EcLpL0-6tvzsNSSJOLzG1",
|
|
39
|
+
"direct_link": "https://drive.google.com/uc?export=download&id=1-4LrEqmDP6-EcLpL0-6tvzsNSSJOLzG1",
|
|
40
|
+
"view_link": "https://drive.google.com/file/d/1-4LrEqmDP6-EcLpL0-6tvzsNSSJOLzG1/view?usp=drive_link"
|
|
41
|
+
},
|
|
42
|
+
"filename": "NineBusSystem.pickle",
|
|
43
|
+
"bundled": true,
|
|
44
|
+
"local_path": "datasets/NineBusSystem.pickle",
|
|
45
|
+
"metadata": {
|
|
46
|
+
"system_type": "Distribution System",
|
|
47
|
+
"voltage_level": "Medium Voltage",
|
|
48
|
+
"typical_use": "Educational purposes, algorithm testing"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
tranpy/data/download.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Google Drive download utilities for TranPy."""
|
|
2
|
+
|
|
3
|
+
import requests
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Optional
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from ..utils.logging import get_logger
|
|
9
|
+
|
|
10
|
+
logger = get_logger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def download_from_google_drive(
|
|
14
|
+
file_id: str,
|
|
15
|
+
destination: Path,
|
|
16
|
+
filename: str,
|
|
17
|
+
show_progress: bool = True
|
|
18
|
+
) -> Path:
|
|
19
|
+
"""
|
|
20
|
+
Download file from Google Drive.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
file_id: Google Drive file ID
|
|
24
|
+
destination: Local destination path
|
|
25
|
+
filename: Original filename (for display)
|
|
26
|
+
show_progress: Show download progress
|
|
27
|
+
|
|
28
|
+
Returns:
|
|
29
|
+
Path to downloaded file
|
|
30
|
+
|
|
31
|
+
Raises:
|
|
32
|
+
requests.RequestException: If download fails
|
|
33
|
+
|
|
34
|
+
Examples:
|
|
35
|
+
>>> from tranpy.data import download_from_google_drive
|
|
36
|
+
>>> path = download_from_google_drive(
|
|
37
|
+
... file_id='1eXtw44VXhYM0jQyJGGY5Eevdrg8yui0w',
|
|
38
|
+
... destination=Path('~/.tranpy/datasets/NewEngland.pickle'),
|
|
39
|
+
... filename='NewEngland.pickle'
|
|
40
|
+
... )
|
|
41
|
+
"""
|
|
42
|
+
destination = Path(destination).expanduser()
|
|
43
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
|
|
45
|
+
# Google Drive direct download URL
|
|
46
|
+
URL = "https://drive.google.com/uc?export=download"
|
|
47
|
+
|
|
48
|
+
logger.info(f"Downloading {filename} from Google Drive...")
|
|
49
|
+
|
|
50
|
+
session = requests.Session()
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
# Initial request
|
|
54
|
+
response = session.get(URL, params={'id': file_id}, stream=True)
|
|
55
|
+
response.raise_for_status()
|
|
56
|
+
|
|
57
|
+
# Handle large files (confirmation required)
|
|
58
|
+
token = None
|
|
59
|
+
for key, value in response.cookies.items():
|
|
60
|
+
if key.startswith('download_warning'):
|
|
61
|
+
token = value
|
|
62
|
+
break
|
|
63
|
+
|
|
64
|
+
if token:
|
|
65
|
+
params = {'id': file_id, 'confirm': token}
|
|
66
|
+
response = session.get(URL, params=params, stream=True)
|
|
67
|
+
response.raise_for_status()
|
|
68
|
+
|
|
69
|
+
# Get file size if available
|
|
70
|
+
total_size = int(response.headers.get('content-length', 0))
|
|
71
|
+
|
|
72
|
+
# Download file
|
|
73
|
+
downloaded = 0
|
|
74
|
+
chunk_size = 8192
|
|
75
|
+
|
|
76
|
+
with open(destination, 'wb') as f:
|
|
77
|
+
for chunk in response.iter_content(chunk_size=chunk_size):
|
|
78
|
+
if chunk:
|
|
79
|
+
f.write(chunk)
|
|
80
|
+
downloaded += len(chunk)
|
|
81
|
+
|
|
82
|
+
if show_progress and total_size > 0:
|
|
83
|
+
# Simple progress indicator
|
|
84
|
+
progress = (downloaded / total_size) * 100
|
|
85
|
+
sys.stdout.write(
|
|
86
|
+
f"\rProgress: {progress:.1f}% "
|
|
87
|
+
f"({downloaded / (1024*1024):.1f} MB / "
|
|
88
|
+
f"{total_size / (1024*1024):.1f} MB)"
|
|
89
|
+
)
|
|
90
|
+
sys.stdout.flush()
|
|
91
|
+
|
|
92
|
+
if show_progress:
|
|
93
|
+
print() # New line after progress
|
|
94
|
+
logger.info(f"Downloaded to: {destination}")
|
|
95
|
+
|
|
96
|
+
return destination
|
|
97
|
+
|
|
98
|
+
except requests.RequestException as e:
|
|
99
|
+
if destination.exists():
|
|
100
|
+
destination.unlink() # Clean up partial download
|
|
101
|
+
raise RuntimeError(
|
|
102
|
+
f"Failed to download {filename} from Google Drive.\n"
|
|
103
|
+
f"Error: {e}\n"
|
|
104
|
+
f"File ID: {file_id}\n"
|
|
105
|
+
f"Please check your internet connection or download manually."
|
|
106
|
+
) from e
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def get_google_drive_direct_link(file_id: str) -> str:
|
|
110
|
+
"""
|
|
111
|
+
Generate Google Drive direct download link.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
file_id: Google Drive file ID
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
Direct download URL
|
|
118
|
+
"""
|
|
119
|
+
return f"https://drive.google.com/uc?export=download&id={file_id}"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def extract_file_id_from_link(link: str) -> Optional[str]:
|
|
123
|
+
"""
|
|
124
|
+
Extract file ID from Google Drive link.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
link: Google Drive URL
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
File ID if found, None otherwise
|
|
131
|
+
|
|
132
|
+
Examples:
|
|
133
|
+
>>> link = "https://drive.google.com/file/d/1eXtw44VXhYM0jQyJGGY5Eevdrg8yui0w/view"
|
|
134
|
+
>>> extract_file_id_from_link(link)
|
|
135
|
+
'1eXtw44VXhYM0jQyJGGY5Eevdrg8yui0w'
|
|
136
|
+
"""
|
|
137
|
+
# Pattern: /d/{file_id}/ or id={file_id}
|
|
138
|
+
if '/d/' in link:
|
|
139
|
+
try:
|
|
140
|
+
return link.split('/d/')[1].split('/')[0]
|
|
141
|
+
except IndexError:
|
|
142
|
+
pass
|
|
143
|
+
|
|
144
|
+
if 'id=' in link:
|
|
145
|
+
try:
|
|
146
|
+
return link.split('id=')[1].split('&')[0]
|
|
147
|
+
except IndexError:
|
|
148
|
+
pass
|
|
149
|
+
|
|
150
|
+
return None
|