-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHyperionSort.py
3620 lines (2993 loc) · 135 KB
/
HyperionSort.py
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import numpy.typing as npt
from dataclasses import dataclass, field
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import math
import pandas as pd
import psutil
import time
import warnings
from enum import Enum
import cProfile
import io
import pstats
from collections import deque
import heapq
from functools import partial, lru_cache
import logging
import sys
from contextlib import contextmanager
import pickle
import os
from datetime import datetime
import threading
import multiprocessing as mp
import random
from sklearn.cluster import MiniBatchKMeans, DBSCAN
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from scipy.stats import skew, kurtosis, entropy
from lz4.frame import compress, decompress
import tensorflow as tf
import asyncio
import numba
import json
import gc
from multiprocessing import shared_memory
import mmap
import socket
import dask.array as da
import ray
from tqdm import tqdm
import xgboost as xgb
from typing import Dict, Any, List, Union, Optional, Tuple, Callable, Generator
import lightgbm as lgb
from catboost import CatBoostClassifier
from retrying import retry
import pytest
from hilbertcurve.hilbertcurve import HilbertCurve
import seaborn as sns
import matplotlib.pyplot as plt
from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource
from bokeh.palettes import Category20
from bokeh.io import output_notebook
import statsmodels.api as sm
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
warnings.filterwarnings('ignore', category=UserWarning, module='xgboost')
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s - %(processName)s - %(threadName)s'
)
logger = logging.getLogger(__name__)
def log_system_metrics():
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
disk_io = psutil.disk_io_counters()
logger.info(f"CPU Usage: {cpu_usage}%")
logger.info(f"Memory Usage: {memory_info.percent}%")
logger.info(f"Disk Read: {disk_io.read_bytes / (1024 * 1024):.2f} MB")
logger.info(f"Disk Write: {disk_io.write_bytes / (1024 * 1024):.2f} MB")
def plot_performance_metrics(results):
df = pd.DataFrame(results)
df['size'] = pd.to_numeric(df['size'], errors='coerce')
df['time'] = pd.to_numeric(df['time'], errors='coerce')
df = df.replace([np.inf, -np.inf], np.nan)
df = df.dropna(subset=['size', 'time'])
if len(df) == 0:
print("Không có dữ liệu hợp lệ để vẽ biểu đồ!")
return
plt.figure(figsize=(14, 8))
sns.lineplot(data=df, x='size', y='time', hue='strategy', marker='o', ci=None)
plt.title('Execution Time vs Data Size')
plt.xlabel('Data Size')
plt.ylabel('Execution Time (seconds)')
plt.legend(title='Strategy')
plt.grid(True)
plt.show()
def plot_interactive_performance_metrics(results):
output_notebook()
df = pd.DataFrame(results)
source = ColumnDataSource(df)
p = figure(title="Execution Time vs Data Size", x_axis_label='Data Size', y_axis_label='Execution Time (seconds)', plot_width=800, plot_height=400)
strategies = df['strategy'].unique()
colors = Category20[len(strategies)]
for i, strategy in enumerate(strategies):
strategy_df = df[df['strategy'] == strategy]
p.line(strategy_df['size'], strategy_df['time'], legend_label=strategy, line_width=2, color=colors[i])
p.circle(strategy_df['size'], strategy_df['time'], fill_color=colors[i], size=8)
p.legend.title = 'Strategy'
show(p)
def analyze_performance_metrics(results):
df = pd.DataFrame(results)
df['log_size'] = np.log(df['size'])
df['log_time'] = np.log(df['time'])
model = sm.OLS(df['log_time'], sm.add_constant(df[['log_size', 'strategy']]))
results = model.fit()
print(results.summary())
@retry(stop_max_attempt_number=3, wait_fixed=2000)
def critical_function():
log_system_metrics()
sorter = EnhancedHyperionSort()
data = np.random.randint(0, 1000, size=1_000_000)
sorted_data, stats = asyncio.run(sorter.sort(data))
logger.info(f"Sorting completed. Execution time: {stats.execution_time:.4f} seconds")
@dataclass
class SortStrategy(Enum):
AUTO = "auto"
PARALLEL = "parallel"
MEMORY_EFFICIENT = "memory_efficient"
HYBRID = "hybrid"
ADAPTIVE = "adaptive"
STREAM = "stream"
BLOCK_SORT = "block_sort"
BUCKET_SORT = "bucket_sort"
RADIX_SORT = "radix_sort"
COMPRESSION_SORT = "compression_sort"
EXTERNAL_SORT = "external_sort"
COUNTING_SORT = "counting_sort"
LAZY_SORT = "lazy_sort"
SEQUENTIAL_SORT = "sequential_sort"
MICRO_SORT = "micro_sort"
HYBRID_COMPRESSION_SORT = "hybrid_compression_sort"
HOT_SWAP_SORT = "hot_swap_sort"
STREAMING_HYBRID_SORT = "streaming_hybrid_sort"
SHELL_SORT = "shell_sort"
COMB_SORT = "comb_sort"
PANCAKE_SORT = "pancake_sort"
GNOME_SORT = "gnome_sort"
CYCLE_SORT = "cycle_sort"
BITONIC_SORT = "bitonic_sort"
ODD_EVEN_SORT = "odd_even_sort"
STOOGE_SORT = "stooge_sort"
SMOOTH_SORT = "smooth_sort"
@classmethod
def from_str(cls, strategy: str):
return cls[strategy.upper()]
class MultiLayerCache:
def __init__(self, l1_size: int, l2_size: int):
self.l1_cache = LRUCache(l1_size)
self.l2_cache = LRUCache(l2_size)
class Algorithm(Enum):
QUICKSORT = "quicksort"
MERGESORT = "mergesort"
HEAPSORT = "heapsort"
TIMSORT = "timsort"
INTROSORT = "introsort"
RADIXSORT = "radixsort"
EXTERNALMERGESORT = "externalmergesort"
COUNTINGSORT = "countingsort"
QUICKSELECT = "quickselect"
INSERTIONSORT = "insertionsort"
NONE = "none"
class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return TreeNode(key)
else:
if root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root
def inorder_traversal(root, res):
if root:
inorder_traversal(root.left, res)
res.append(root.val)
inorder_traversal(root.right, res)
def _tree_sort(self, arr: npt.NDArray) -> npt.NDArray:
if len(arr) == 0:
return arr
root = TreeNode(arr[0])
for i in range(1, len(arr)):
insert(root, arr[i])
sorted_arr = []
inorder_traversal(root, sorted_arr)
return np.array(sorted_arr)
@dataclass
class PerformanceMetrics:
cpu_time: float = 0.0
wall_time: float = 0.0
memory_peak: float = 0.0
cache_hits: int = 0
cache_misses: int = 0
thread_count: int = 0
context_switches: int = 0
io_operations: int = 0
network_usage: float = 0.0
disk_io: float = 0.0
cache_efficiency: float = 0.0
compression_ratio: float = 1.0
class AdaptiveCache:
def __init__(self, initial_size: int = 1000):
self.cache = {}
self.size = initial_size
self.hits = 0
self.misses = 0
self._access_history = deque(maxlen=initial_size)
self._resize_threshold = 0.8
self.min_size = initial_size // 2
self.l1_cache = {}
self.l2_cache = {}
def _should_resize(self) -> bool:
if not self._access_history:
return False
hit_rate = self.hits / (self.hits + self.misses + 1)
return hit_rate < self._resize_threshold or len(self._access_history) < self.min_size
def resize(self):
if self._should_resize():
self.size = max(self.min_size, int(self.size * 1.5))
self._access_history = deque(maxlen=self.size)
@lru_cache(maxsize=256)
def get(self, key: Union[int, str]) -> Any:
if key in self.l1_cache:
self.hits += 1
self._access_history.append(key)
return self.l1_cache[key]
elif key in self.l2_cache:
self.hits += 1
self._access_history.append(key)
return self.l2_cache[key]
self.misses += 1
self.resize()
return None
def put(self, key: Union[int, str], value: Any) -> None:
if len(self.l1_cache) >= self.size:
oldest = self._access_history.popleft()
self.l1_cache.pop(oldest, None)
self.l1_cache[key] = value
self._access_history.append(key)
if len(self.l2_cache) >= self.size * 2:
self.l2_cache.pop(next(iter(self.l2_cache)))
self.l2_cache[key] = value
class BlockManager:
def __init__(self, block_size: int = 4096):
self.block_size = block_size
self.blocks = []
def split_into_blocks(self, arr: npt.NDArray) -> List[npt.NDArray]:
return np.array_split(arr, max(1, len(arr) // self.block_size))
def merge_blocks(self, blocks: List[npt.NDArray]) -> npt.NDArray:
if not blocks:
return np.array([])
result = np.zeros(sum(len(block)
for block in blocks), dtype=blocks[0].dtype)
pos = 0
for block in blocks:
result[pos:pos + len(block)] = block
pos += len(block)
return result
def tune_xgboost_model(X_train, y_train):
param_grid = {
'learning_rate': [0.01, 0.1, 0.2],
'max_depth': [3, 5, 7],
'n_estimators': [50, 100, 200],
'subsample': [0.8, 1.0],
'colsample_bytree': [0.8, 1.0]
}
model = xgb.XGBClassifier(objective='multi:softmax', use_label_encoder=False)
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=3, scoring='accuracy', verbose=1)
grid_search.fit(X_train, y_train)
return grid_search.best_estimator_
@dataclass
class SortStats:
execution_time: float
memory_usage: float
items_processed: int
cpu_usage: float
bucket_distribution: List[int]
strategy_used: str
algorithm_used: str
performance: PerformanceMetrics = field(default_factory=PerformanceMetrics)
optimization_history: List[Dict[str, Any]] = field(default_factory=list)
stream_chunks: int = 0
compression_ratio: float = 1.0
error_detected: bool = False
fallback_strategy: str = "None"
class CacheManager:
def __init__(self, max_size: int = 1000):
self.cache = {}
self.max_size = max_size
self.hits = 0
self.misses = 0
self._access_history = deque(maxlen=max_size)
@lru_cache(maxsize=128)
def get(self, key: Union[int, str]) -> Any:
if key in self.cache:
self.hits += 1
self._access_history.append(key)
return self.cache[key]
self.misses += 1
return None
def put(self, key: Union[int, str], value: Any) -> None:
if len(self.cache) >= self.max_size:
oldest = self._access_history.popleft()
self.cache.pop(oldest, None)
self.cache[key] = value
self._access_history.append(key)
class StreamProcessor:
def __init__(self, chunk_size: int = 1000):
self.chunk_size = chunk_size
self.buffer = deque(maxlen=chunk_size)
self._lock = threading.Lock()
self.chunks_processed = 0
self.linear_model = LinearRegression()
self.last_chunk_size = chunk_size
self.chunk_history = deque(maxlen=5)
def process_stream(self, data_stream: Generator) -> Generator:
for item in data_stream:
with self._lock:
self.buffer.append(item)
if len(self.buffer) >= self.chunk_size:
self.chunks_processed += 1
sorted_buffer = sorted(list(self.buffer), key=lambda x: float(
x) if isinstance(x, (int, float, np.number)) else str(x))
yield sorted_buffer
self.chunk_history.append(len(self.buffer))
self.buffer.clear()
self._update_chunk_size()
if self.buffer:
self.chunks_processed += 1
sorted_buffer = sorted(list(self.buffer), key=lambda x: float(
x) if isinstance(x, (int, float, np.number)) else str(x))
yield sorted_buffer
self.chunk_history.append(len(self.buffer))
def _update_chunk_size(self):
if len(self.chunk_history) < 2:
return
x = np.arange(1, len(self.chunk_history) + 1).reshape(-1, 1)
y = np.array(self.chunk_history)
self.linear_model.fit(x, y)
next_chunk_size = self.linear_model.predict(
np.array([[len(self.chunk_history) + 1]]))[0]
self.chunk_size = max(1000, int(next_chunk_size))
class MetricsCollector:
def __init__(self):
self.metrics = []
self.disk_io_start = psutil.disk_io_counters()
self.start_time = time.perf_counter()
def record(self, metric_name: str, value: Any):
self.metrics.append({
'name': metric_name,
'value': value,
'timestamp': time.perf_counter() - self.start_time
})
def get_summary(self) -> Dict[str, Any]:
disk_io_end = psutil.disk_io_counters()
read_count = disk_io_end.read_bytes - self.disk_io_start.read_bytes
write_count = disk_io_end.write_bytes - self.disk_io_start.write_bytes
return {
'total_duration': time.perf_counter() - self.start_time,
'metrics': self.metrics,
'disk_io': {
'read_count': read_count,
'write_count': write_count,
}
}
@contextmanager
def performance_tracker():
start_time = time.perf_counter()
start_cpu = time.process_time()
try:
yield
finally:
end_cpu = time.process_time()
end_time = time.perf_counter()
logger.debug(f"CPU Time: {end_cpu - start_cpu:.4f}s")
logger.debug(f"Wall Time: {end_time - start_time:.4f}s")
def is_distributed_env():
if os.getenv('ENV_TYPE') == "cluster":
return True
try:
ip_address = socket.gethostbyname(socket.gethostname())
if len(ip_address.split('.')) > 3:
return True
except OSError:
pass
if psutil.cpu_count() > 4:
return True
return False
class EnhancedHyperionSort:
def __init__(
self,
strategy: SortStrategy = SortStrategy.AUTO,
n_workers: Optional[int] = None,
chunk_size: Optional[int] = None,
profile: bool = False,
cache_size: int = 2000,
adaptive_threshold: float = 0.8,
stream_mode: bool = False,
block_size: int = 4096,
use_ml_prediction: bool = True,
compression_threshold: int = 10000,
external_sort_threshold=100000,
duplicate_threshold=0.5,
eco_mode=False,
priority_mode="speed",
deduplicate_sort=False,
service_mode=False,
data_type="number",
log_level=logging.INFO,
benchmark=False,
data_distribution_test=False,
distributed=False
):
self.strategy = strategy
self.profile = profile
self.benchmark = benchmark
self.data_distribution_test = data_distribution_test
self.distributed = distributed
self.n_workers = n_workers or max(1, psutil.cpu_count() - 1)
self.chunk_size = chunk_size
self.cache = AdaptiveCache(cache_size)
self.adaptive_threshold = adaptive_threshold
self.stream_mode = stream_mode
self.block_manager = BlockManager(block_size)
self.metrics = MetricsCollector()
self._setup_logging(log_level)
self.start_time = time.perf_counter()
self.stream_processor = StreamProcessor(
chunk_size=self.chunk_size or 1000)
self.use_ml_prediction = use_ml_prediction
self.ml_model_path = "ml_model.pkl"
self.models = self._load_ml_models() if use_ml_prediction else []
self.compression_threshold = compression_threshold
self.fallback_strategy = Algorithm.MERGESORT
self.external_sort_threshold = external_sort_threshold
self.buffer_size = 4096
self.duplicate_threshold = duplicate_threshold
self.eco_mode = eco_mode
self.priority_mode = priority_mode
self.historical_runs = {}
self.deduplicate_sort = deduplicate_sort
self.service_mode = service_mode
self.data_type = data_type
self.comparator = self._get_default_comparator()
self.cpu_load_data = deque(maxlen=10)
self.load_balancer_enabled = True
self.cache = AdaptiveCache(cache_size)
self.historical_runs = {}
def _setup_metrics(self) -> Dict[str, Any]:
return {
'sort_times': [],
'memory_usage': [],
'cache_stats': {'hits': 0, 'misses': 0},
'block_stats': {'splits': 0, 'merges': 0}
}
@staticmethod
def train_predict_label(feature_sample: Dict[str, Any]) -> str:
is_nearly_sorted = feature_sample.get("is_nearly_sorted", False)
std_dev = feature_sample.get("std_dev", 0)
range_size = feature_sample.get("range_size", 1)
n = feature_sample.get("n", 1)
data_skewness = feature_sample.get("data_skewness", 0)
data_kurtosis = feature_sample.get("data_kurtosis", 0)
data_type = feature_sample.get("data_type", "number")
if data_type != "number":
return SortStrategy.ADAPTIVE.value.upper()
if data_skewness > 2 or data_kurtosis > 5:
return SortStrategy.BUCKET_SORT.value.upper()
if is_nearly_sorted:
return SortStrategy.ADAPTIVE.value.upper()
if n > 1_000_000:
return SortStrategy.PARALLEL.value.upper()
if std_dev < range_size / 100:
return SortStrategy.HYBRID.value.upper()
if n > 100_000:
return SortStrategy.EXTERNAL_SORT.value.upper()
if n > 10_000:
return SortStrategy.SEQUENTIAL_SORT.value.upper()
if n > 1000:
return SortStrategy.MICRO_SORT.value.upper()
return SortStrategy.ADAPTIVE.value.upper()
def _load_ml_models(self):
if os.path.exists(self.ml_model_path):
try:
with open(self.ml_model_path, "rb") as f:
loaded_data = pickle.load(f)
if "models" in loaded_data:
models = loaded_data["models"]
self.logger.info("Loaded ML models from disk.")
return models
else:
self.logger.warning("No 'models' key found in loaded data. Training new models.")
return self._train_ml_models()
except Exception as e:
self.logger.warning(f"Error loading models from disk: {e}. Training new models.")
return self._train_ml_models()
else:
self.logger.info("ML models not found on disk. Training new models.")
return self._train_ml_models()
def _save_ml_models(self, models):
try:
with open(self.ml_model_path, "wb") as f:
pickle.dump({"models": models}, f)
self.logger.info("Saved ML models to disk.")
except Exception as e:
self.logger.error(f"Error saving models to disk: {e}")
def _tune_xgboost_model(self, X_train, y_train):
param_grid = {
'learning_rate': [0.01, 0.1, 0.2],
'max_depth': [3, 5, 7],
'n_estimators': [50, 100, 200],
'subsample': [0.8, 1.0],
'colsample_bytree': [0.8, 1.0]
}
model = xgb.XGBClassifier(objective='multi:softmax', use_label_encoder=False)
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=3, scoring='accuracy', verbose=1)
grid_search.fit(X_train, y_train)
return grid_search.best_estimator_
def _fine_tune_ml_models(self, X_train, y_train):
param_grid = {
'learning_rate': [0.01, 0.1, 0.2],
'max_depth': [3, 5, 7],
'n_estimators': [50, 100, 200],
'subsample': [0.8, 1.0],
'colsample_bytree': [0.8, 1.0]
}
model = xgb.XGBClassifier(objective='multi:softmax', use_label_encoder=False)
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=3, scoring='accuracy', verbose=1)
grid_search.fit(X_train, y_train)
return grid_search.best_estimator_
def _incremental_ml_training(self, new_data: List[Dict[str, Any]]):
for record in new_data:
self.training_data.append(record)
self._train_ml_models(training_data_set=self.training_data)
def _feature_importance_analysis(self, features: np.ndarray, labels: np.ndarray):
model = RandomForestClassifier()
model.fit(features, labels)
importances = model.feature_importances_
return importances
def _simulate_data(self, size: int) -> npt.NDArray:
return np.random.randint(0, size * 10, size=size)
def incremental_training(self, new_data: List[Dict[str, Any]]):
self.training_data.extend(new_data)
self._train_ml_models(training_data_set=self.training_data)
def _train_ml_models(self, training_data_set=None, n_samples_train=100000, **kwargs):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"Benchmark_results/benchmark_train_{timestamp}.pkl"
train_file_names = [filename, f"benchmark_train_{timestamp}.pkl"]
unique_strategies = sorted(strategy.name for strategy in SortStrategy)
strategy_mapping = {name: idx for idx, name in enumerate(unique_strategies)}
if training_data_set is None:
training_data_set = []
benchmark_folder = "Benchmark_results"
if not os.path.exists(benchmark_folder):
self.logger.warning(
"'Benchmark_results' folder not found. "
"Cannot train ML models without benchmark data."
)
return []
benchmark_files = [
f for f in os.listdir(benchmark_folder)
if (f.startswith("benchmark_results_") or f.startswith("benchmark_train_")) and f.endswith(".pkl")
]
if not benchmark_files:
self.logger.warning(
"No benchmark result files found in 'Benchmark_results' folder. "
"Cannot train ML models without benchmark data."
)
return []
loaded_files_count = 0
skipped_files_count = 0
skipped_records_count = 0
for file in tqdm(benchmark_files, desc="Loading benchmark data", leave=False):
try:
file_path = os.path.join(benchmark_folder, file)
with open(file_path, 'rb') as f:
benchmark_data = pickle.load(f)
if isinstance(benchmark_data, list):
training_data_set.extend(benchmark_data)
loaded_files_count += 1
else:
skipped_files_count += 1
except Exception as e:
self.logger.warning(f"Error loading {file_path}: {e}")
if loaded_files_count > 0:
self.logger.info(f"Loaded benchmark data from {loaded_files_count} files.")
if skipped_files_count > 0:
self.logger.warning(f"Skipped {skipped_files_count} files because they did not contain a list.")
if not training_data_set:
self.logger.error("No training data available after loading benchmark results.")
return []
labels = []
data = []
used_strategies = set()
for record in tqdm(training_data_set, desc="Preparing training data", leave=False):
try:
strategy_str = record.get('strategy', SortStrategy.ADAPTIVE.value)
if isinstance(strategy_str, SortStrategy):
strategy_str = strategy_str.value
strategy_name = SortStrategy.from_str(strategy_str).name
if strategy_name in strategy_mapping:
labels.append(strategy_mapping[strategy_name])
used_strategies.add(strategy_name)
data.append([
record.get('std_dev', 0.0),
record.get('range_size', 1.0),
float(record.get('is_nearly_sorted', False)),
record.get('n', 1000.0),
record.get('data_skewness', 0.0),
record.get('data_kurtosis', 0.0)
])
except Exception as e:
skipped_records_count += 1
if skipped_records_count > 0:
self.logger.warning(f"Skipped {skipped_records_count} records due to errors.")
if len(data) < 2:
raise ValueError(f"Not enough training data: {len(data)} samples")
data = np.array(data, dtype=np.float64)
labels = np.array(labels, dtype=np.int64)
unique_labels = sorted(set(labels))
label_mapping = {old_label: new_label for new_label, old_label in enumerate(unique_labels)}
labels = np.array([label_mapping[label] for label in labels])
scaler = StandardScaler()
data = scaler.fit_transform(data)
X_train, X_val, y_train, y_val = train_test_split(data, labels, test_size=0.2, random_state=42)
models = []
xgb_model = xgb.XGBClassifier(
objective='multi:softmax',
num_class=len(set(labels)),
use_label_encoder=False,
learning_rate=0.1,
max_depth=5,
n_estimators=100,
subsample=0.8,
colsample_bytree=0.8,
reg_alpha=0.1,
reg_lambda=1.0,
early_stopping_rounds=10,
n_jobs=psutil.cpu_count() - 1 if psutil.cpu_count() > 1 else 1
)
xgb_model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)
models.append(xgb_model)
lgb_model = lgb.LGBMClassifier(
objective='multiclass',
num_class=len(set(labels)),
learning_rate=0.1,
max_depth=5,
n_estimators=100,
subsample=0.8,
colsample_bytree=0.8,
reg_alpha=0.1,
reg_lambda=1.0,
n_jobs=psutil.cpu_count() - 1 if psutil.cpu_count() > 1 else 1,
verbose=-1
)
lgb_model.fit(X_train, y_train, eval_set=[(X_val, y_val)])
models.append(lgb_model)
cat_model = CatBoostClassifier(
iterations=100,
learning_rate=0.1,
depth=5,
loss_function='MultiClass',
verbose=False
)
cat_model.fit(X_train, y_train, eval_set=(X_val, y_val))
models.append(cat_model)
rf_model = RandomForestClassifier(
n_estimators=100,
max_depth=5,
random_state=42,
n_jobs=psutil.cpu_count() - 1 if psutil.cpu_count() > 1 else 1
)
rf_model.fit(X_train, y_train)
models.append(rf_model)
for model in models:
y_pred = model.predict(X_val)
accuracy = accuracy_score(y_val, y_pred)
self.logger.info(f"Model accuracy: {accuracy:.4f}")
self._save_ml_models(models)
return models
def _predict_strategy(self, arr: npt.NDArray) -> SortStrategy:
if not self.models:
return self._choose_optimal_strategy(arr)
n = len(arr)
sample_size = min(1000, n)
sample = arr[np.random.choice(n, sample_size, replace=False)]
if self.data_type != "number":
is_nearly_sorted = False
else:
is_nearly_sorted = np.sum(np.diff(sample) < 0) < len(sample) * 0.1
std_dev = np.std(sample)
range_size = np.ptp(sample)
data_skewness = skew(sample)
data_kurtosis = kurtosis(sample)
features = np.array([std_dev, range_size, is_nearly_sorted, n, data_skewness, data_kurtosis]).reshape(1, -1)
predictions = [int(model.predict(features)[0]) for model in self.models]
predicted_strategy_idx = max(set(predictions), key=predictions.count)
strategy_mapping = {
0: SortStrategy.ADAPTIVE,
1: SortStrategy.BUCKET_SORT,
2: SortStrategy.HYBRID,
3: SortStrategy.PARALLEL,
4: SortStrategy.RADIX_SORT,
5: SortStrategy.COMPRESSION_SORT,
6: SortStrategy.MICRO_SORT,
7: SortStrategy.MEMORY_EFFICIENT,
8: SortStrategy.STREAMING_HYBRID_SORT,
9: SortStrategy.HOT_SWAP_SORT,
10: SortStrategy.EXTERNAL_SORT,
11: SortStrategy.COUNTING_SORT,
12: SortStrategy.LAZY_SORT,
13: SortStrategy.SEQUENTIAL_SORT
}
return strategy_mapping.get(predicted_strategy_idx, SortStrategy.ADAPTIVE)
def adaptive_thread_scaling(self, arr: npt.NDArray):
n = len(arr)
if n < 1000:
self.n_workers = 1
elif n < 10000:
self.n_workers = min(2, psutil.cpu_count() - 1)
else:
self.n_workers = min(4, psutil.cpu_count() - 1)
def pipeline_processing(self, data_stream: Generator) -> Generator:
for chunk in data_stream:
yield np.sort(chunk)
def chunk_wise_processing(self, arr: npt.NDArray) -> npt.NDArray:
chunk_size = self._adaptive_chunk_size(len(arr), arr.itemsize)
chunks = np.array_split(arr, max(1, len(arr) // chunk_size))
with ThreadPoolExecutor(max_workers=self.n_workers) as executor:
sorted_chunks = list(executor.map(np.sort, chunks))
return self._merge_sorted_arrays(sorted_chunks)
def hierarchical_parallelism(self, arr: npt.NDArray) -> npt.NDArray:
chunk_size = self._adaptive_chunk_size(len(arr), arr.itemsize)
chunks = np.array_split(arr, max(1, len(arr) // chunk_size))
with ProcessPoolExecutor(max_workers=self.n_workers) as executor:
sorted_chunks = list(executor.map(self._parallel_sort_block, chunks))
return self._merge_sorted_arrays(sorted_chunks)
def set_thread_affinity(self):
p = psutil.Process(os.getpid())
p.cpu_affinity([i for i in range(psutil.cpu_count())])
def use_shared_memory(self, arr: npt.NDArray) -> npt.NDArray:
shm = shared_memory.SharedMemory(create=True, size=arr.nbytes)
shared_arr = np.ndarray(arr.shape, dtype=arr.dtype, buffer=shm.buf)
np.copyto(shared_arr, arr)
return shared_arr
def feature_reduction(self, features: np.ndarray) -> np.ndarray:
important_features = [0, 1, 2, 3]
return features[:, important_features]
def cross_validation(self, X_train, y_train):
param_grid = {'n_estimators': [50, 100], 'max_depth': [3, 5]}
grid_search = GridSearchCV(RandomForestClassifier(), param_grid, cv=3)
grid_search.fit(X_train, y_train)
return grid_search.best_estimator_
def incremental_updates(self, new_data: List[Dict[str, Any]]):
self.training_data.extend(new_data)
self._train_ml_models(training_data_set=self.training_data)
def bagging_models(self, X_train, y_train):
model = BaggingClassifier(base_estimator=DecisionTreeClassifier(), n_estimators=10)
model.fit(X_train, y_train)
return model
def performance_benchmarks(self, models: List):
for model in models:
y_pred = model.predict(self.X_val)
accuracy = accuracy_score(self.y_val, y_pred)
self.logger.info(f"Model accuracy: {accuracy:.4f}")
async def async_file_access(self, file_path: str, offset: int, size: int, dtype: np.dtype) -> np.ndarray:
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, partial(self._read_chunk_sync, file_path, offset, size, dtype))
def reduce_disk_io(self, arr: npt.NDArray) -> npt.NDArray:
compressed_data = compress(arr.tobytes())
decompressed_arr = np.frombuffer(decompress(compressed_data), dtype=arr.dtype)
return decompressed_arr
def data_compression(self, arr: npt.NDArray) -> npt.NDArray:
compressed_data = compress(arr.tobytes())
decompressed_arr = np.frombuffer(decompress(compressed_data), dtype=arr.dtype)
return decompressed_arr
def task_scheduling(self, tasks: List[Callable]):
with ThreadPoolExecutor(max_workers=self.n_workers) as executor:
executor.map(lambda task: task(), tasks)
def data_distribution_detection(self, arr: npt.NDArray) -> str:
skewness = skew(arr)
kurtosis = kurtosis(arr)
if abs(skewness) < 0.5 and abs(kurtosis) < 3:
return "uniform"
else:
return "skewed"
async def chunked_external_sorting(self, arr: npt.NDArray) -> npt.NDArray:
chunk_size = self._adaptive_chunk_size(len(arr), arr.itemsize)
chunks = np.array_split(arr, max(1, len(arr) // chunk_size))
sorted_chunks = []
for chunk in chunks:
sorted_chunks.append(np.sort(chunk))
return self._merge_sorted_arrays(sorted_chunks)
def statistical_insights(self, arr: npt.NDArray) -> Dict[str, float]:
return {
"skewness": skew(arr),
"kurtosis": kurtosis(arr)
}
def realtime_monitoring(self):
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
self.logger.info(f"CPU Usage: {cpu_usage}%")
self.logger.info(f"Memory Usage: {memory_info.percent}%")
def dynamic_model_switching(self, arr: npt.NDArray):
if self.data_distribution_detection(arr) == "uniform":
self.strategy = SortStrategy.BUCKET_SORT
else:
self.strategy = SortStrategy.INTROSORT
def _advanced_block_sort(self, arr: npt.NDArray) -> npt.NDArray:
if len(arr) < 1000:
return np.sort(arr)
blocks = self.block_manager.split_into_blocks(arr)
self.metrics.record('block_splits', 1)
with ProcessPoolExecutor(max_workers=self.n_workers) as executor:
sorted_blocks = list(tqdm(executor.map(self._optimize_block_sort, blocks), total=len(blocks), desc="Sorting blocks", leave=False))
while len(sorted_blocks) > 1:
new_blocks = []
for i in tqdm(range(0, len(sorted_blocks), 2), desc="Merging blocks", leave=False):
if i + 1 < len(sorted_blocks):
merged = self._merge_sorted_arrays([sorted_blocks[i], sorted_blocks[i + 1]])
new_blocks.append(merged)
else:
new_blocks.append(sorted_blocks[i])
sorted_blocks = new_blocks
self.metrics.record('block_merges', 1)
return sorted_blocks[0]
def _optimize_block_sort(self, block: npt.NDArray) -> npt.NDArray:
if len(block) < 16:
return self._insertion_sort(block)
std_dev = np.std(block)
range_size = np.ptp(block)
if std_dev < range_size / 100:
return self._bucket_sort(block)
elif len(block) < 1000:
return self._quicksort(block)
else:
return self._introsort(block)
def _radix_sort(self, arr: npt.NDArray) -> npt.NDArray:
max_val = int(np.max(arr))
exp = 1