File size: 6,632 Bytes
e2150b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
(* ::Package:: *)

(* MathUtils.wl - Mathematical Utility Functions for ChaosSim *)
(* Reusable functions for Bernoulli numbers, Fibonacci sequences, and game theory *)

BeginPackage["MathUtils`"]


(* ::Section:: *)
(* Public Function Declarations *)

BernoulliChaosWeight::usage = "BernoulliChaosWeight[n] returns the absolute value of the nth Bernoulli number for chaos weighting."

GenerateFibonacciSequence::usage = "GenerateFibonacciSequence[n] generates the first n Fibonacci numbers."

GoldenRatioApproximation::usage = "GoldenRatioApproximation[n] calculates the golden ratio using the nth Fibonacci number."

PayoffMatrixRandom::usage = "PayoffMatrixRandom[rows, cols] generates a random payoff matrix for game theory."

NormalizeWeights::usage = "NormalizeWeights[list] normalizes a list to sum to 1."

ChaosEntropy::usage = "ChaosEntropy[data] calculates the Shannon entropy of chaos data."

LyapunovExponent::usage = "LyapunovExponent[data] estimates the Lyapunov exponent from a time series."


Begin["`Private`"]


(* ::Section:: *)
(* Bernoulli Number Utilities *)

BernoulliChaosWeight[n_Integer] := Module[{b},
  If[n < 0, 
    Return[0.001],
    b = BernoulliB[n];
    If[b == 0, 0.001, Abs[N[b]]]
  ]
]


(* Generate Bernoulli polynomial *)
BernoulliPolynomialValue[n_Integer, x_Numeric] := BernoulliB[n, x]


(* Weighted sum using Bernoulli numbers *)
BernoulliWeightedSum[values_List, maxOrder_Integer: 10] := Module[
  {weights, normalized},
  weights = Table[BernoulliChaosWeight[i], {i, 1, Min[maxOrder, Length[values]]}];
  normalized = weights / Total[weights];
  Total[Take[values, Length[normalized]] * normalized]
]


(* ::Section:: *)
(* Fibonacci Utilities *)

GenerateFibonacciSequence[n_Integer] := Table[Fibonacci[i], {i, 1, n}]


GoldenRatioApproximation[n_Integer] := Module[{fn, fnMinus1},
  If[n < 2, Return[1.0]];
  fn = Fibonacci[n];
  fnMinus1 = Fibonacci[n - 1];
  N[fn / fnMinus1]
]


(* Generate Lucas numbers (related to Fibonacci) *)
GenerateLucasSequence[n_Integer] := Table[LucasL[i], {i, 1, n}]


(* Fibonacci-based golden spiral parameters *)
FibonacciSpiralRadius[n_Integer] := Sqrt[Fibonacci[n]]


(* Calculate Fibonacci ratios for chaos analysis *)
FibonacciRatioSequence[depth_Integer] := Module[{fibs, ratios},
  fibs = GenerateFibonacciSequence[depth];
  ratios = Table[N[fibs[[i + 1]] / fibs[[i]]], {i, 1, depth - 1}];
  ratios
]


(* ::Section:: *)
(* Game Theory Utilities *)

PayoffMatrixRandom[rows_Integer, cols_Integer, range_List: {-10, 10}] := 
  RandomInteger[range, {rows, cols}]


(* Check if a strategy profile is a Nash equilibrium *)
IsNashEquilibrium[strategy_List, payoffMatrix1_List, payoffMatrix2_List] := Module[
  {i, j, isEquilibrium},
  {i, j} = strategy;
  
  isEquilibrium = True;
  
  (* Check if player 1 can improve *)
  If[Max[payoffMatrix1[[All, j]]] > payoffMatrix1[[i, j]],
    isEquilibrium = False
  ];
  
  (* Check if player 2 can improve *)
  If[Max[payoffMatrix2[[i, All]]] > payoffMatrix2[[i, j]],
    isEquilibrium = False
  ];
  
  isEquilibrium
]


(* Calculate expected payoff for mixed strategy *)
ExpectedPayoff[strategy1_List, strategy2_List, payoffMatrix_List] := 
  Sum[
    strategy1[[i]] * strategy2[[j]] * payoffMatrix[[i, j]],
    {i, 1, Length[strategy1]},
    {j, 1, Length[strategy2]}
  ]


(* Generate symmetric game payoff matrix *)
SymmetricPayoffMatrix[size_Integer] := Module[{matrix},
  matrix = PayoffMatrixRandom[size, size];
  (matrix + Transpose[matrix]) / 2
]


(* ::Section:: *)
(* General Chaos Analysis Utilities *)

NormalizeWeights[list_List] := Module[{total},
  total = Total[list];
  If[total == 0, Table[1/Length[list], Length[list]], list / total]
]


(* Calculate Shannon entropy *)
ChaosEntropy[data_List] := Module[{probs, bins, counts},
  bins = 20;
  counts = BinCounts[data, {Min[data], Max[data], (Max[data] - Min[data])/bins}];
  probs = NormalizeWeights[counts + 0.0001]; (* Add small value to avoid log(0) *)
  -Total[probs * Log[2, probs]]
]


(* Estimate Lyapunov exponent from time series *)
LyapunovExponent[data_List, delay_Integer: 1] := Module[
  {diffs, nonZeroDiffs, lyapunov},
  If[Length[data] < delay + 2, Return[0.0]];
  
  diffs = Abs[Differences[data, 1, delay]];
  nonZeroDiffs = Select[diffs, # > 0.00001 &];
  
  If[Length[nonZeroDiffs] < 2,
    Return[0.0],
    lyapunov = Mean[Log[nonZeroDiffs]]
  ];
  
  lyapunov
]


(* Calculate correlation dimension *)
CorrelationDimension[data_List, epsilon_Real: 0.1] := Module[
  {distances, correlationSum},
  distances = Flatten[DistanceMatrix[Partition[data, 1]]];
  correlationSum = Count[distances, x_ /; x < epsilon && x > 0];
  If[correlationSum > 0,
    Log[correlationSum] / Log[epsilon],
    0.0
  ]
]


(* Detect periodic orbits in chaos data *)
DetectPeriodicOrbit[data_List, tolerance_Real: 0.01] := Module[
  {n, periods, found},
  n = Length[data];
  found = False;
  periods = {};
  
  Do[
    If[Abs[data[[i]] - data[[1]]] < tolerance && i > 1,
      AppendTo[periods, i - 1];
      found = True
    ],
    {i, 2, Min[n, 100]}
  ];
  
  If[found, First[periods], 0]
]


(* Calculate Hurst exponent for long-range dependence *)
HurstExponent[data_List] := Module[{n, mean, std, ranges, scaledRanges},
  n = Length[data];
  mean = Mean[data];
  std = StandardDeviation[data];
  
  If[std == 0, Return[0.5]];
  
  ranges = Table[
    Max[Accumulate[Take[data, k] - mean]] - Min[Accumulate[Take[data, k] - mean]],
    {k, 10, n, Max[1, Floor[n/20]]}
  ];
  
  scaledRanges = ranges / (std * Sqrt[Range[10, n, Max[1, Floor[n/20]]]]);
  
  (* Fit log-log plot to estimate Hurst exponent *)
  If[Length[scaledRanges] > 2,
    Fit[
      Transpose[{Log[Range[10, n, Max[1, Floor[n/20]]]], Log[scaledRanges]}],
      {1, x}, x
    ][[2]],
    0.5
  ]
]


(* ::Section:: *)
(* Chaos Metrics and Analysis *)

ChaoticityScore[data_List] := Module[
  {entropy, lyapunov, hurst, score},
  entropy = ChaosEntropy[data];
  lyapunov = Abs[LyapunovExponent[data]];
  hurst = Abs[HurstExponent[data] - 0.5];
  
  (* Weighted combination *)
  score = 0.4 * entropy + 0.4 * lyapunov + 0.2 * hurst;
  score
]


(* Compare two chaos sequences *)
ChaosDistance[data1_List, data2_List] := Module[{minLen},
  minLen = Min[Length[data1], Length[data2]];
  EuclideanDistance[Take[data1, minLen], Take[data2, minLen]]
]


End[]

EndPackage[]


Print["MathUtils package loaded successfully."]