-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
391 lines (296 loc) · 9.67 KB
/
utils.py
File metadata and controls
391 lines (296 loc) · 9.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
"""
Utility Functions
Helper functions for formatting, data export, and visualization configuration.
"""
import json
import csv
from datetime import datetime
from typing import Dict, List, Any
import pandas as pd
def format_timestamp(timestamp: float, format_str: str = "%Y-%m-%d %H:%M:%S") -> str:
"""
Format a Unix timestamp as a human-readable string.
Args:
timestamp: Unix timestamp
format_str: strftime format string
Returns:
Formatted date/time string
"""
return datetime.fromtimestamp(timestamp).strftime(format_str)
def format_currency(amount: float, decimals: int = 2, symbol: str = "") -> str:
"""
Format a number as currency.
Args:
amount: Amount to format
decimals: Number of decimal places
symbol: Currency symbol (e.g., "$", "€")
Returns:
Formatted currency string
"""
formatted = f"{amount:,.{decimals}f}"
return f"{symbol}{formatted}" if symbol else formatted
def format_percentage(value: float, decimals: int = 1) -> str:
"""
Format a decimal as a percentage.
Args:
value: Decimal value (e.g., 0.25 for 25%)
decimals: Number of decimal places
Returns:
Formatted percentage string
"""
return f"{value * 100:.{decimals}f}%"
def get_color_scheme() -> Dict[str, str]:
"""
Get the default color scheme for visualizations.
Returns:
Dictionary mapping element types to colors
"""
return {
# Node types
'agent': '#FF6B6B',
'shard': '#4ECDC4',
'asset': '#FFE66D',
# Status colors
'active': '#00FF00',
'inactive': '#888888',
'pending': '#FFA500',
'completed': '#00FF00',
'failed': '#FF0000',
# Chain colors
'ethereum': '#627EEA',
'bsc': '#F3BA2F',
'polygon': '#8247E5',
# Shard types
'compute': '#FF6B6B',
'storage': '#4ECDC4',
'ai': '#A8E6CF',
# General
'primary': '#3498db',
'secondary': '#2ecc71',
'accent': '#e74c3c',
'background': '#f5f5f5'
}
def get_plotly_template() -> Dict[str, Any]:
"""
Get default Plotly template configuration.
Returns:
Dictionary with Plotly layout settings
"""
return {
'plot_bgcolor': 'rgba(240,240,240,0.9)',
'paper_bgcolor': 'white',
'font': {'family': 'Arial, sans-serif', 'size': 12},
'title': {'font': {'size': 16, 'color': '#333'}},
'showlegend': True,
'hovermode': 'closest'
}
def export_to_json(data: Any, filename: str) -> str:
"""
Export data to JSON file.
Args:
data: Data to export (must be JSON serializable)
filename: Output filename
Returns:
Success message
"""
try:
with open(filename, 'w') as f:
json.dump(data, f, indent=2, default=str)
return f"Data exported to {filename}"
except Exception as e:
return f"Export failed: {str(e)}"
def export_to_csv(data: List[Dict], filename: str) -> str:
"""
Export list of dictionaries to CSV file.
Args:
data: List of dictionaries with consistent keys
filename: Output filename
Returns:
Success message
"""
try:
if not data:
return "No data to export"
keys = data[0].keys()
with open(filename, 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=keys)
writer.writeheader()
writer.writerows(data)
return f"Data exported to {filename}"
except Exception as e:
return f"Export failed: {str(e)}"
def validate_amount(amount: float, min_value: float = 0.0,
max_value: float = float('inf')) -> tuple[bool, str]:
"""
Validate a numeric amount.
Args:
amount: Amount to validate
min_value: Minimum allowed value
max_value: Maximum allowed value
Returns:
Tuple of (is_valid, error_message)
"""
if not isinstance(amount, (int, float)):
return False, "Amount must be a number"
if amount < min_value:
return False, f"Amount must be at least {min_value}"
if amount > max_value:
return False, f"Amount must not exceed {max_value}"
return True, ""
def truncate_string(s: str, max_length: int = 20, suffix: str = "...") -> str:
"""
Truncate a string to maximum length.
Args:
s: String to truncate
max_length: Maximum length (including suffix)
suffix: Suffix to add if truncated
Returns:
Truncated string
"""
if len(s) <= max_length:
return s
return s[:max_length - len(suffix)] + suffix
def aggregate_by_key(data: List[Dict], key: str, value_key: str,
agg_func: str = 'sum') -> Dict:
"""
Aggregate data by a key.
Args:
data: List of dictionaries
key: Key to group by
value_key: Key containing values to aggregate
agg_func: Aggregation function ('sum', 'avg', 'count', 'min', 'max')
Returns:
Dictionary mapping key values to aggregated values
"""
from collections import defaultdict
groups = defaultdict(list)
for item in data:
if key in item and value_key in item:
groups[item[key]].append(item[value_key])
result = {}
for k, values in groups.items():
if agg_func == 'sum':
result[k] = sum(values)
elif agg_func == 'avg':
result[k] = sum(values) / len(values) if values else 0
elif agg_func == 'count':
result[k] = len(values)
elif agg_func == 'min':
result[k] = min(values) if values else 0
elif agg_func == 'max':
result[k] = max(values) if values else 0
return result
def create_dataframe(data: List[Dict]) -> pd.DataFrame:
"""
Create a pandas DataFrame from list of dictionaries.
Args:
data: List of dictionaries
Returns:
pandas DataFrame
"""
if not data:
return pd.DataFrame()
return pd.DataFrame(data)
def format_dict_for_display(d: Dict, indent: int = 2) -> str:
"""
Format a dictionary for readable display.
Args:
d: Dictionary to format
indent: Indentation spaces
Returns:
Formatted string
"""
lines = []
for key, value in d.items():
# Format key
key_str = str(key).replace('_', ' ').title()
# Format value
if isinstance(value, float):
value_str = f"{value:.2f}"
elif isinstance(value, dict):
value_str = json.dumps(value, indent=indent)
else:
value_str = str(value)
lines.append(f"{' ' * indent}{key_str}: {value_str}")
return '\n'.join(lines)
def calculate_growth_rate(old_value: float, new_value: float) -> float:
"""
Calculate percentage growth rate.
Args:
old_value: Previous value
new_value: Current value
Returns:
Growth rate as decimal (e.g., 0.25 for 25% growth)
"""
if old_value == 0:
return 0.0 if new_value == 0 else float('inf')
return (new_value - old_value) / old_value
def safe_divide(numerator: float, denominator: float, default: float = 0.0) -> float:
"""
Safely divide two numbers, returning default if denominator is zero.
Args:
numerator: Numerator
denominator: Denominator
default: Value to return if denominator is zero
Returns:
Result of division or default
"""
return numerator / denominator if denominator != 0 else default
def create_summary_stats(values: List[float]) -> Dict[str, float]:
"""
Calculate summary statistics for a list of values.
Args:
values: List of numeric values
Returns:
Dictionary with summary statistics
"""
if not values:
return {
'count': 0,
'sum': 0.0,
'mean': 0.0,
'min': 0.0,
'max': 0.0,
'std': 0.0
}
import statistics
return {
'count': len(values),
'sum': sum(values),
'mean': statistics.mean(values),
'min': min(values),
'max': max(values),
'std': statistics.stdev(values) if len(values) > 1 else 0.0
}
if __name__ == "__main__":
# Demo usage
import time
print("=== Utility Functions Demo ===\n")
# Timestamp formatting
now = time.time()
print(f"Timestamp: {format_timestamp(now)}")
# Currency formatting
print(f"Currency: {format_currency(1234.567, symbol='$')}")
# Percentage formatting
print(f"Percentage: {format_percentage(0.847)}")
# Colors
colors = get_color_scheme()
print(f"\nColor scheme has {len(colors)} colors")
print(f"Agent color: {colors['agent']}")
# Validation
is_valid, error = validate_amount(50.0, min_value=0, max_value=100)
print(f"\nValidation: {is_valid} (error: '{error}')")
# Aggregation
data = [
{'type': 'A', 'value': 10},
{'type': 'B', 'value': 20},
{'type': 'A', 'value': 15},
{'type': 'B', 'value': 25}
]
aggregated = aggregate_by_key(data, 'type', 'value', 'sum')
print(f"\nAggregated by type: {aggregated}")
# Summary stats
values = [10, 20, 30, 40, 50]
stats = create_summary_stats(values)
print(f"\nSummary statistics:")
print(format_dict_for_display(stats))