-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcom_analysis.py
More file actions
1507 lines (1207 loc) · 51.7 KB
/
com_analysis.py
File metadata and controls
1507 lines (1207 loc) · 51.7 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
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
"""
COM Framework Analysis Module Fixes
This module implements fixes for the analysis modules of the Continuous Oscillatory
Model (COM) framework, addressing issues identified in testing.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import pandas as pd
from scipy import stats, signal, optimize, fft
from sklearn import cluster, decomposition, manifold
from typing import List, Tuple, Dict, Optional, Union, Callable
import math
import itertools
# Import the core modules
from com_framework_core_fixed import LZModule, OctaveModule
class MathematicalAnalysisModule:
"""
Advanced mathematical analysis tools for the COM framework.
This module provides functions for analyzing mathematical properties
of LZ-based systems, octave patterns, and energy distributions.
"""
def __init__(self, lz_module: LZModule = None, octave_module: OctaveModule = None):
"""
Initialize the Mathematical Analysis module.
Args:
lz_module: Reference to LZ module
octave_module: Reference to Octave module
"""
self.lz_module = lz_module if lz_module else LZModule()
self.octave_module = octave_module if octave_module else OctaveModule(self.lz_module)
def analyze_fixed_points(self, start: float = 0.0, end: float = 10.0,
step: float = 0.01) -> Dict:
"""
Analyze all fixed points of the recursive function in a given range.
Args:
start: Start of search range
end: End of search range
step: Step size for search
Returns:
Dictionary with analysis results
"""
fixed_points = self.lz_module.find_fixed_points(start, end, step)
# Analyze each fixed point
results = {
'fixed_points': fixed_points,
'count': len(fixed_points),
'stability': [],
'basin_sizes': [],
'convergence_rates': []
}
for fp in fixed_points:
# Check stability
stability = self.lz_module.stability_at_point(fp)
results['stability'].append(stability)
# Estimate basin of attraction size
basin_size = self._estimate_basin_size(fp, start, end, step)
results['basin_sizes'].append(basin_size)
# Calculate convergence rate
conv_rate = self._calculate_convergence_rate(fp)
results['convergence_rates'].append(conv_rate)
return results
def _estimate_basin_size(self, fixed_point: float, start: float, end: float,
step: float) -> float:
"""
Estimate the size of the basin of attraction for a fixed point.
Args:
fixed_point: The fixed point to analyze
start: Start of search range
end: End of search range
step: Step size for search
Returns:
Estimated size of basin of attraction
"""
count = 0
total = 0
# Use fewer test points for efficiency
test_points = np.linspace(start, end, int((end - start) / step / 10))
for x in test_points:
total += 1
# Check if this point converges to the fixed point
current = x
for _ in range(50): # Limit iterations
current = self.lz_module.recursive_wave_function(current)
# Check if converged to this fixed point
if abs(current - fixed_point) < 1e-3:
count += 1
break
# Return proportion of points that converge to this fixed point
return count / total if total > 0 else 0
def _calculate_convergence_rate(self, fixed_point: float,
delta: float = 0.01) -> float:
"""
Calculate the convergence rate near a fixed point.
Args:
fixed_point: The fixed point to analyze
delta: Small perturbation for calculation
Returns:
Convergence rate (iterations needed to halve the distance)
"""
# Start slightly away from fixed point
x = fixed_point + delta
# Track distance from fixed point
distances = []
# Iterate until very close or max iterations
for _ in range(20): # Reduced iterations for efficiency
x = self.lz_module.recursive_wave_function(x)
dist = abs(x - fixed_point)
distances.append(dist)
if dist < 1e-6:
break
# Calculate average rate of convergence
if len(distances) < 2:
return 0
rates = []
for i in range(1, len(distances)):
if distances[i-1] > 0: # Avoid division by zero
rate = distances[i] / distances[i-1]
rates.append(rate)
# Return average rate
return np.mean(rates) if rates else 0
def analyze_lz_powers(self, max_power: int = 10) -> Dict:
"""
Analyze properties of powers of the LZ constant.
Args:
max_power: Maximum power to analyze
Returns:
Dictionary with analysis results
"""
powers = [self.lz_module.LZ ** i for i in range(-max_power, max_power + 1)]
# Analyze octave patterns in powers
octaves = [self.octave_module.lz_based_octave(p) for p in powers]
# Find patterns in the sequence
pattern_length = self._find_pattern_length(octaves)
# Calculate ratios between consecutive powers
ratios = [powers[i+1] / powers[i] for i in range(len(powers) - 1)]
return {
'powers': powers,
'octaves': octaves,
'pattern_length': pattern_length,
'ratios': ratios
}
def _find_pattern_length(self, sequence: List[float],
threshold: float = 1e-5) -> int:
"""
Find the length of a repeating pattern in a sequence.
Args:
sequence: Sequence to analyze
threshold: Threshold for considering values equal
Returns:
Length of the repeating pattern, or 0 if none found
"""
n = len(sequence)
# Try different pattern lengths
for length in range(1, n // 2 + 1):
is_pattern = True
# Check if the pattern repeats
for i in range(length, min(length * 3, n)):
if abs(sequence[i] - sequence[i % length]) > threshold:
is_pattern = False
break
if is_pattern:
return length
return 0
def analyze_octave_distribution(self, start: int = 1, end: int = 1000) -> Dict:
"""
Analyze the distribution of octaves in a range of numbers.
Args:
start: Start of range
end: End of range
Returns:
Dictionary with analysis results
"""
sequence = list(range(start, end + 1))
octaves = [self.octave_module.octave_reduction(n) for n in sequence]
# Count occurrences of each octave
counts = {i: octaves.count(i) for i in range(1, 10)}
# Calculate expected uniform distribution
expected = len(sequence) / 9
# Calculate chi-square statistic
chi2_stat = sum((counts[i] - expected) ** 2 / expected for i in range(1, 10))
# Calculate p-value (8 degrees of freedom)
p_value = 1 - stats.chi2.cdf(chi2_stat, 8)
# Check for patterns in the sequence
autocorr = self._calculate_autocorrelation(octaves)
return {
'counts': counts,
'chi2_stat': chi2_stat,
'p_value': p_value,
'is_uniform': p_value > 0.05, # Null hypothesis: distribution is uniform
'autocorrelation': autocorr
}
def _calculate_autocorrelation(self, sequence: List[int],
max_lag: int = 20) -> List[float]:
"""
Calculate autocorrelation of a sequence for different lags.
Args:
sequence: Sequence to analyze
max_lag: Maximum lag to consider
Returns:
List of autocorrelation values for each lag
"""
# Convert to numpy array
arr = np.array(sequence)
# Calculate mean and variance
mean = np.mean(arr)
var = np.var(arr)
if var == 0:
return [0] * max_lag
# Calculate autocorrelation for each lag
autocorr = []
n = len(arr)
for lag in range(1, min(max_lag + 1, n)):
# Calculate correlation between original and lagged sequence
corr = np.corrcoef(arr[:-lag], arr[lag:])[0, 1]
autocorr.append(corr)
return autocorr
def analyze_collatz_octave_properties(self, max_n: int = 100,
key: int = 7) -> Dict:
"""
Analyze properties of Collatz-Octave transformations.
Args:
max_n: Maximum starting number to analyze
key: Key for the transformation
Returns:
Dictionary with analysis results
"""
results = {
'cycle_lengths': [],
'sequence_lengths': [],
'unique_octaves': [],
'entropy': []
}
for n in range(1, max_n + 1):
# Get transformation
sequence = self.octave_module.collatz_octave_transform(n, key, 100)
# Record sequence length
results['sequence_lengths'].append(len(sequence))
# Count unique octaves
unique = len(set(sequence))
results['unique_octaves'].append(unique)
# Calculate entropy (randomness measure)
entropy = self._calculate_entropy(sequence)
results['entropy'].append(entropy)
# Detect cycle length
cycle_length = self._detect_cycle_length(sequence)
results['cycle_lengths'].append(cycle_length)
# Calculate statistics
stats_results = {
'avg_sequence_length': np.mean(results['sequence_lengths']),
'avg_unique_octaves': np.mean(results['unique_octaves']),
'avg_entropy': np.mean(results['entropy']),
'avg_cycle_length': np.mean(results['cycle_lengths']),
'max_sequence_length': max(results['sequence_lengths']),
'min_sequence_length': min(results['sequence_lengths'])
}
# Combine results
results.update(stats_results)
return results
def _calculate_entropy(self, sequence: List[int]) -> float:
"""
Calculate Shannon entropy of a sequence.
Args:
sequence: Sequence to analyze
Returns:
Entropy value
"""
# Count occurrences of each value
counts = {}
for val in sequence:
counts[val] = counts.get(val, 0) + 1
# Calculate probabilities
n = len(sequence)
probabilities = [count / n for count in counts.values()]
# Calculate entropy
entropy = -sum(p * math.log2(p) for p in probabilities)
return entropy
def _detect_cycle_length(self, sequence: List[int]) -> int:
"""
Detect the length of a cycle in a sequence.
Args:
sequence: Sequence to analyze
Returns:
Length of the cycle, or 0 if none detected
"""
n = len(sequence)
if n < 4: # Need at least a few elements to detect cycles
return 0
# Check for cycles of different lengths
for length in range(1, min(n // 2, 10) + 1): # Limit to cycles of length 10 or less
# Check if the last 'length' elements repeat
is_cycle = True
for i in range(length):
if n - length - 1 - i < 0:
is_cycle = False
break
if sequence[n - 1 - i] != sequence[n - length - 1 - i]:
is_cycle = False
break
if is_cycle:
return length
return 0
def analyze_lz_hqs_relationship(self, points: int = 1000) -> Dict:
"""
Analyze the relationship between LZ and HQS threshold.
Args:
points: Number of points to analyze
Returns:
Dictionary with analysis results
"""
# Generate values around LZ
x_values = np.linspace(self.lz_module.LZ * 0.5, self.lz_module.LZ * 1.5, points)
# Calculate function values
f_values = [self.lz_module.recursive_wave_function(x) for x in x_values]
# Calculate derivatives
derivatives = [self.lz_module.stability_at_point(x) for x in x_values]
# Find points where derivative crosses 1 (stability boundary)
stability_crossings = []
for i in range(1, len(derivatives)):
if (derivatives[i-1] < 1 and derivatives[i] >= 1) or (derivatives[i-1] >= 1 and derivatives[i] < 1):
# Linear interpolation to find crossing point
x_cross = x_values[i-1] + (x_values[i] - x_values[i-1]) * (1 - derivatives[i-1]) / (derivatives[i] - derivatives[i-1])
stability_crossings.append(x_cross)
# Calculate HQS-related metrics
hqs_values = [x * 0.235 for x in x_values] # HQS = 23.5% of x
# Find relationship between HQS and stability
hqs_stability_corr = np.corrcoef(hqs_values, derivatives)[0, 1]
return {
'x_values': x_values.tolist(), # Convert to list for serialization
'f_values': f_values,
'derivatives': derivatives,
'stability_crossings': stability_crossings,
'hqs_values': hqs_values,
'hqs_stability_correlation': hqs_stability_corr
}
def analyze_octave_scaling(self, base: float = 1.0,
octaves: int = 8) -> Dict:
"""
Analyze scaling relationships across octaves.
Args:
base: Base value
octaves: Number of octaves to analyze
Returns:
Dictionary with analysis results
"""
# Generate scaled values
scaled_values = [base * (self.lz_module.LZ ** i) for i in range(octaves)]
# Calculate ratios between consecutive octaves
ratios = [scaled_values[i+1] / scaled_values[i] for i in range(octaves - 1)]
# Calculate octave values
octave_values = [self.octave_module.octave_reduction(int(val * 100)) for val in scaled_values]
# Check for patterns in octave values
pattern_length = self._find_pattern_length(octave_values)
return {
'scaled_values': scaled_values,
'ratios': ratios,
'octave_values': octave_values,
'pattern_length': pattern_length
}
class PatternRecognitionModule:
"""
Pattern recognition and analysis tools for the COM framework.
This module provides functions for detecting and analyzing patterns
in data using COM principles.
"""
def __init__(self, lz_module: LZModule = None, octave_module: OctaveModule = None):
"""
Initialize the Pattern Recognition module.
Args:
lz_module: Reference to LZ module
octave_module: Reference to Octave module
"""
self.lz_module = lz_module if lz_module else LZModule()
self.octave_module = octave_module if octave_module else OctaveModule(self.lz_module)
def detect_octave_patterns(self, data: List[int]) -> Dict:
"""
Detect octave patterns in a sequence of numbers.
Args:
data: Sequence of numbers to analyze
Returns:
Dictionary with pattern analysis results
"""
# Convert to octaves
octaves = [self.octave_module.octave_reduction(n) for n in data]
# Find repeating subsequences
patterns = self._find_repeating_subsequences(octaves)
# Calculate frequency distribution
freq_dist = {i: octaves.count(i) for i in range(1, 10)}
# Calculate transition matrix
transitions = self._calculate_transition_matrix(octaves)
# Detect rhythm patterns
rhythm = self._detect_rhythm_pattern(octaves)
return {
'octaves': octaves,
'patterns': patterns,
'frequency_distribution': freq_dist,
'transition_matrix': transitions,
'rhythm': rhythm
}
def _find_repeating_subsequences(self, sequence: List[int],
min_length: int = 2,
min_occurrences: int = 2) -> List[Dict]:
"""
Find repeating subsequences in a sequence.
Args:
sequence: Sequence to analyze
min_length: Minimum length of subsequences to consider
min_occurrences: Minimum number of occurrences to report
Returns:
List of dictionaries with pattern information
"""
n = len(sequence)
patterns = []
# Check subsequences of different lengths
for length in range(min_length, min(20, n // 2 + 1)):
# Dictionary to store subsequences and their positions
subsequences = {}
# Find all subsequences of the current length
for i in range(n - length + 1):
subseq = tuple(sequence[i:i+length])
if subseq in subsequences:
subsequences[subseq].append(i)
else:
subsequences[subseq] = [i]
# Filter subsequences that appear multiple times
for subseq, positions in subsequences.items():
if len(positions) >= min_occurrences:
patterns.append({
'pattern': list(subseq),
'length': length,
'occurrences': len(positions),
'positions': positions
})
# Sort by number of occurrences (descending)
patterns.sort(key=lambda x: x['occurrences'], reverse=True)
return patterns
def _calculate_transition_matrix(self, sequence: List[int]) -> List[List[float]]:
"""
Calculate transition probabilities between octaves.
Args:
sequence: Sequence of octaves
Returns:
9x9 transition matrix (0-indexed, but octave 0 is not used)
"""
# Initialize 9x9 matrix with zeros
matrix = [[0.0 for _ in range(9)] for _ in range(9)]
# Count transitions
for i in range(len(sequence) - 1):
from_octave = sequence[i] - 1 # Convert to 0-indexed
to_octave = sequence[i+1] - 1 # Convert to 0-indexed
matrix[from_octave][to_octave] += 1
# Convert counts to probabilities
for i in range(9):
row_sum = sum(matrix[i])
if row_sum > 0:
matrix[i] = [count / row_sum for count in matrix[i]]
return matrix
def _detect_rhythm_pattern(self, sequence: List[int]) -> Dict:
"""
Detect rhythmic patterns in a sequence of octaves.
Args:
sequence: Sequence of octaves
Returns:
Dictionary with rhythm analysis
"""
if len(sequence) < 2:
return {
'differences': [],
'most_common_diff': (0, 0),
'alternating_pattern': False,
'increasing': False,
'decreasing': False
}
# Calculate differences between consecutive octaves
diffs = [sequence[i+1] - sequence[i] for i in range(len(sequence) - 1)]
# Count occurrences of each difference
diff_counts = {}
for diff in diffs:
diff_counts[diff] = diff_counts.get(diff, 0) + 1
# Calculate most common difference
most_common_diff = max(diff_counts.items(), key=lambda x: x[1]) if diff_counts else (0, 0)
# Detect alternating patterns (e.g., +2, -2, +2, -2)
alternating = False
if len(diffs) >= 4:
# Check if even-indexed and odd-indexed differences are consistent
even_diffs = diffs[0::2]
odd_diffs = diffs[1::2]
even_consistent = all(d == even_diffs[0] for d in even_diffs)
odd_consistent = all(d == odd_diffs[0] for d in odd_diffs)
alternating = even_consistent and odd_consistent and even_diffs[0] != odd_diffs[0]
# Detect if the sequence follows a scale-like pattern (consistently increasing or decreasing)
increasing = all(d > 0 for d in diffs)
decreasing = all(d < 0 for d in diffs)
return {
'differences': diffs,
'most_common_diff': most_common_diff,
'alternating_pattern': alternating,
'increasing': increasing,
'decreasing': decreasing
}
def cluster_by_octave_pattern(self, data_points: List[List[int]]) -> Dict:
"""
Cluster data points based on their octave patterns.
Args:
data_points: List of sequences to cluster
Returns:
Dictionary with clustering results
"""
if not data_points or len(data_points) < 2:
return {
'optimal_clusters': 1,
'labels': [0] * len(data_points),
'centers': [[0] * (len(data_points[0]) if data_points else 0)],
'silhouette_score': 0,
'inertia': [0]
}
# Convert each sequence to its octave representation
octave_sequences = []
for sequence in data_points:
octaves = [self.octave_module.octave_reduction(n) for n in sequence]
octave_sequences.append(octaves)
# Ensure all sequences have the same length
min_length = min(len(seq) for seq in octave_sequences)
octave_sequences = [seq[:min_length] for seq in octave_sequences]
# Convert to feature vectors
features = np.array(octave_sequences)
# Determine optimal number of clusters
max_clusters = min(10, len(data_points))
inertia = []
for k in range(1, max_clusters + 1):
kmeans = cluster.KMeans(n_clusters=k, random_state=42)
kmeans.fit(features)
inertia.append(kmeans.inertia_)
# Find elbow point
optimal_k = self._find_elbow_point(inertia) + 1
# Perform clustering with optimal k
kmeans = cluster.KMeans(n_clusters=optimal_k, random_state=42)
labels = kmeans.fit_predict(features)
# Calculate cluster centers
centers = kmeans.cluster_centers_
# Calculate silhouette score
silhouette = 0
if optimal_k > 1 and optimal_k < len(data_points):
try:
silhouette = cluster.silhouette_score(features, labels)
except:
silhouette = 0
return {
'optimal_clusters': optimal_k,
'labels': labels.tolist(), # Convert to list for serialization
'centers': centers.tolist(), # Convert to list for serialization
'silhouette_score': silhouette,
'inertia': inertia
}
def _find_elbow_point(self, inertia: List[float]) -> int:
"""
Find the elbow point in the inertia curve for K-means.
Args:
inertia: List of inertia values
Returns:
Index of the elbow point
"""
if len(inertia) <= 2:
return 0
# Calculate the angle at each point
angles = []
for i in range(1, len(inertia) - 1):
# Create vectors from point i to points i-1 and i+1
v1 = np.array([1, inertia[i-1] - inertia[i]])
v2 = np.array([1, inertia[i+1] - inertia[i]])
# Normalize vectors
v1_norm = np.linalg.norm(v1)
v2_norm = np.linalg.norm(v2)
if v1_norm == 0 or v2_norm == 0:
angles.append(0)
continue
v1 = v1 / v1_norm
v2 = v2 / v2_norm
# Calculate angle
dot_product = np.clip(np.dot(v1, v2), -1.0, 1.0)
angle = np.arccos(dot_product)
angles.append(angle)
# Return index of maximum angle
return np.argmax(angles) if angles else 0
def detect_lz_based_patterns(self, data: List[float]) -> Dict:
"""
Detect patterns based on LZ scaling in continuous data.
Args:
data: Sequence of values to analyze
Returns:
Dictionary with pattern analysis results
"""
if not data:
return {
'autocorrelation': [],
'peaks': [],
'dominant_frequencies': [],
'lz_related_periods': []
}
# Calculate autocorrelation
autocorr = self._calculate_autocorrelation(data)
# Find peaks in autocorrelation
peaks = []
try:
peaks, _ = signal.find_peaks(autocorr)
peaks = peaks.tolist() # Convert to list for serialization
except:
peaks = []
# Calculate Fourier transform
fft_result = np.abs(fft.fft(data))
freqs = fft.fftfreq(len(data))
# Find dominant frequencies
dominant_indices = np.argsort(fft_result)[-5:] # Top 5 frequencies
dominant_freqs = freqs[dominant_indices]
dominant_magnitudes = fft_result[dominant_indices]
# Check for LZ-related periods
lz_periods = []
for i, peak in enumerate(peaks):
period = peak + 1 # Convert index to period
# Check if period is close to a power of LZ
for power in range(-5, 6):
expected = self.lz_module.LZ ** power
if abs(period - expected) / expected < 0.1: # Within 10%
lz_periods.append({
'period': period,
'expected': expected,
'power': power,
'error': abs(period - expected) / expected
})
break
return {
'autocorrelation': autocorr,
'peaks': peaks,
'dominant_frequencies': [(float(f), float(m)) for f, m in zip(dominant_freqs, dominant_magnitudes)],
'lz_related_periods': lz_periods
}
def _calculate_autocorrelation(self, sequence: List[float],
max_lag: int = None) -> List[float]:
"""
Calculate autocorrelation of a sequence for different lags.
Args:
sequence: Sequence to analyze
max_lag: Maximum lag to consider (default: half of sequence length)
Returns:
List of autocorrelation values for each lag
"""
# Convert to numpy array
arr = np.array(sequence)
# Set default max_lag
if max_lag is None:
max_lag = len(arr) // 2
# Calculate autocorrelation
result = np.correlate(arr, arr, mode='full')
# Extract the relevant part (positive lags)
result = result[len(arr)-1:len(arr)+max_lag]
# Normalize
if result[0] != 0:
result = result / result[0]
return result.tolist()
def find_octave_based_features(self, data: List[int]) -> Dict:
"""
Extract octave-based features from a sequence.
Args:
data: Sequence of numbers to analyze
Returns:
Dictionary with extracted features
"""
if not data:
return {
'mean': 0,
'median': 0,
'mode': 0,
'std_dev': 0,
'frequency_distribution': {i: 0 for i in range(1, 10)},
'entropy': 0,
'runs': {'max_run': 0, 'avg_run': 0, 'run_counts': {}},
'transitions': {'direction_changes': 0, 'avg_step': 0, 'steps': []}
}
# Convert to octaves
octaves = [self.octave_module.octave_reduction(n) for n in data]
# Calculate basic statistics
mean = float(np.mean(octaves))
median = float(np.median(octaves))
# Calculate mode safely
try:
mode_result = stats.mode(octaves)
if hasattr(mode_result, 'mode'):
mode = float(mode_result.mode[0])
else:
mode = float(mode_result[0][0])
except:
# Fallback if stats.mode fails
counts = {}
for o in octaves:
counts[o] = counts.get(o, 0) + 1
mode = max(counts.items(), key=lambda x: x[1])[0] if counts else 0
std_dev = float(np.std(octaves))
# Calculate frequency distribution
freq_dist = {i: octaves.count(i) / len(octaves) for i in range(1, 10)}
# Calculate entropy
entropy = -sum(p * math.log2(p) for p in freq_dist.values() if p > 0)
# Calculate run lengths
runs = self._calculate_run_lengths(octaves)
# Calculate transition features
transitions = self._calculate_transition_features(octaves)
return {
'mean': mean,
'median': median,
'mode': mode,
'std_dev': std_dev,
'frequency_distribution': freq_dist,
'entropy': entropy,
'runs': runs,
'transitions': transitions
}
def _calculate_run_lengths(self, sequence: List[int]) -> Dict:
"""
Calculate statistics about runs of the same value.
Args:
sequence: Sequence to analyze
Returns:
Dictionary with run length statistics
"""
if not sequence:
return {'max_run': 0, 'avg_run': 0, 'run_counts': {}}
# Find runs
runs = []
current_run = 1
for i in range(1, len(sequence)):
if sequence[i] == sequence[i-1]:
current_run += 1
else:
runs.append(current_run)
current_run = 1
# Add the last run
runs.append(current_run)
# Calculate statistics
max_run = max(runs)
avg_run = float(np.mean(runs))
# Count occurrences of each run length
run_counts = {}
for run in runs:
run_counts[run] = run_counts.get(run, 0) + 1
return {
'max_run': max_run,
'avg_run': avg_run,
'run_counts': run_counts
}
def _calculate_transition_features(self, sequence: List[int]) -> Dict:
"""
Calculate features based on transitions between values.
Args:
sequence: Sequence to analyze
Returns:
Dictionary with transition features
"""
if len(sequence) < 2:
return {'direction_changes': 0, 'avg_step': 0, 'steps': []}
# Calculate steps between consecutive values
steps = [sequence[i+1] - sequence[i] for i in range(len(sequence) - 1)]
# Count direction changes
direction_changes = 0
for i in range(1, len(steps)):
if (steps[i] > 0 and steps[i-1] <= 0) or (steps[i] < 0 and steps[i-1] >= 0):
direction_changes += 1
# Calculate average absolute step
avg_step = float(np.mean([abs(step) for step in steps]))
return {
'direction_changes': direction_changes,
'avg_step': avg_step,
'steps': steps
}
class StatisticalAnalysisModule:
"""
Statistical analysis tools for the COM framework.
This module provides functions for statistical analysis of
COM-related data and patterns.
"""
def __init__(self, lz_module: LZModule = None, octave_module: OctaveModule = None):
"""
Initialize the Statistical Analysis module.
Args:
lz_module: Reference to LZ module
octave_module: Reference to Octave module
"""