python-stats 1.0.1__py3-none-any.whl → 2.0.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.
py_stats/multivariate.py CHANGED
@@ -1,690 +1,926 @@
1
- """
2
- Multivariate statistics functions for py-stats package.
3
-
4
- This module provides comprehensive multivariate statistical analysis functions
5
- including correlation coefficients, covariance, regression analysis, and
6
- association measures.
7
- """
8
-
9
- import math
10
- from typing import List, Union, Tuple, Optional
11
- import numpy as np
12
-
13
- from .univariate import _validate_data, arithmetic_mean
14
-
15
-
16
- def pearson_correlation(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
17
- """
18
- Calculate Pearson's correlation coefficient.
19
-
20
- Args:
21
- x: First variable data
22
- y: Second variable data
23
-
24
- Returns:
25
- Pearson correlation coefficient (-1 to 1)
26
-
27
- Example:
28
- >>> pearson_correlation([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
29
- 0.7745966692414834
30
- """
31
- x = _validate_data(x)
32
- y = _validate_data(y)
33
-
34
- if len(x) != len(y):
35
- raise ValueError("Variables must have the same length")
36
-
37
- if len(x) < 2:
38
- raise ValueError("At least 2 data points required")
39
-
40
- n = len(x)
41
- sum_x = sum(x)
42
- sum_y = sum(y)
43
- sum_xy = sum(xi * yi for xi, yi in zip(x, y))
44
- sum_x2 = sum(xi ** 2 for xi in x)
45
- sum_y2 = sum(yi ** 2 for yi in y)
46
-
47
- numerator = n * sum_xy - sum_x * sum_y
48
- denominator = math.sqrt((n * sum_x2 - sum_x ** 2) * (n * sum_y2 - sum_y ** 2))
49
-
50
- if denominator == 0:
51
- return 0.0
52
-
53
- return numerator / denominator
54
-
55
-
56
- def q_correlation(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
57
- """
58
- Calculate Q-correlation coefficient.
59
-
60
- Q-correlation is based on the ratio of the geometric mean to arithmetic mean.
61
-
62
- Args:
63
- x: First variable data
64
- y: Second variable data
65
-
66
- Returns:
67
- Q-correlation coefficient
68
-
69
- Example:
70
- >>> q_correlation([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
71
- 0.7745966692414834
72
- """
73
- x = _validate_data(x)
74
- y = _validate_data(y)
75
-
76
- if len(x) != len(y):
77
- raise ValueError("Variables must have the same length")
78
-
79
- if len(x) < 2:
80
- raise ValueError("At least 2 data points required")
81
-
82
- # Calculate geometric mean of products
83
- products = [xi * yi for xi, yi in zip(x, y)]
84
- geometric_mean = math.pow(math.prod(products), 1/len(products))
85
-
86
- # Calculate arithmetic mean of products
87
- arithmetic_mean_products = arithmetic_mean(products)
88
-
89
- if arithmetic_mean_products == 0:
90
- return 0.0
91
-
92
- return geometric_mean / arithmetic_mean_products
93
-
94
-
95
- def covariance(x: List[Union[int, float]], y: List[Union[int, float]], population: bool = False) -> float:
96
- """
97
- Calculate covariance between two variables.
98
-
99
- Args:
100
- x: First variable data
101
- y: Second variable data
102
- population: If True, calculate population covariance (n denominator)
103
- If False, calculate sample covariance (n-1 denominator)
104
-
105
- Returns:
106
- Covariance
107
-
108
- Example:
109
- >>> covariance([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
110
- 1.5
111
- """
112
- x = _validate_data(x)
113
- y = _validate_data(y)
114
-
115
- if len(x) != len(y):
116
- raise ValueError("Variables must have the same length")
117
-
118
- if len(x) < 2:
119
- raise ValueError("At least 2 data points required")
120
-
121
- mean_x = arithmetic_mean(x)
122
- mean_y = arithmetic_mean(y)
123
-
124
- sum_xy = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))
125
-
126
- denominator = len(x) if population else len(x) - 1
127
- return sum_xy / denominator
128
-
129
-
130
- def linear_regression(x: List[Union[int, float]], y: List[Union[int, float]]) -> Tuple[float, float, float]:
131
- """
132
- Perform simple linear regression.
133
-
134
- Args:
135
- x: Independent variable data
136
- y: Dependent variable data
137
-
138
- Returns:
139
- Tuple of (slope, intercept, r_squared)
140
-
141
- Example:
142
- >>> slope, intercept, r_squared = linear_regression([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
143
- >>> print(f"y = {slope:.2f}x + {intercept:.2f}, R² = {r_squared:.3f}")
144
- """
145
- x = _validate_data(x)
146
- y = _validate_data(y)
147
-
148
- if len(x) != len(y):
149
- raise ValueError("Variables must have the same length")
150
-
151
- if len(x) < 2:
152
- raise ValueError("At least 2 data points required")
153
-
154
- n = len(x)
155
- sum_x = sum(x)
156
- sum_y = sum(y)
157
- sum_xy = sum(xi * yi for xi, yi in zip(x, y))
158
- sum_x2 = sum(xi ** 2 for xi in x)
159
-
160
- # Calculate slope and intercept
161
- slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
162
- intercept = (sum_y - slope * sum_x) / n
163
-
164
- # Calculate R-squared
165
- mean_y = arithmetic_mean(y)
166
- ss_tot = sum((yi - mean_y) ** 2 for yi in y)
167
- ss_res = sum((yi - (slope * xi + intercept)) ** 2 for xi, yi in zip(x, y))
168
-
169
- r_squared = 1 - (ss_res / ss_tot) if ss_tot != 0 else 0
170
-
171
- return slope, intercept, r_squared
172
-
173
-
174
- def sum_xx(x: List[Union[int, float]]) -> float:
175
- """
176
- Calculate sum of squared deviations from mean (Sxx).
177
-
178
- Args:
179
- x: Variable data
180
-
181
- Returns:
182
- Sum of squared deviations
183
-
184
- Example:
185
- >>> sum_xx([1, 2, 3, 4, 5])
186
- 10.0
187
- """
188
- x = _validate_data(x)
189
- mean_x = arithmetic_mean(x)
190
- return sum((xi - mean_x) ** 2 for xi in x)
191
-
192
-
193
- def sum_yy(y: List[Union[int, float]]) -> float:
194
- """
195
- Calculate sum of squared deviations from mean (Syy).
196
-
197
- Args:
198
- y: Variable data
199
-
200
- Returns:
201
- Sum of squared deviations
202
-
203
- Example:
204
- >>> sum_yy([2, 4, 5, 4, 5])
205
- 6.0
206
- """
207
- y = _validate_data(y)
208
- mean_y = arithmetic_mean(y)
209
- return sum((yi - mean_y) ** 2 for yi in y)
210
-
211
-
212
- def sum_xy(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
213
- """
214
- Calculate sum of cross-products of deviations (Sxy).
215
-
216
- Args:
217
- x: First variable data
218
- y: Second variable data
219
-
220
- Returns:
221
- Sum of cross-products
222
-
223
- Example:
224
- >>> sum_xy([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
225
- 6.0
226
- """
227
- x = _validate_data(x)
228
- y = _validate_data(y)
229
-
230
- if len(x) != len(y):
231
- raise ValueError("Variables must have the same length")
232
-
233
- mean_x = arithmetic_mean(x)
234
- mean_y = arithmetic_mean(y)
235
-
236
- return sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))
237
-
238
-
239
- # Additional correlation functions
240
-
241
- def spearman_correlation(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
242
- """
243
- Calculate Spearman's rank correlation coefficient.
244
-
245
- Spearman correlation measures the strength of monotonic relationship.
246
-
247
- Args:
248
- x: First variable data
249
- y: Second variable data
250
-
251
- Returns:
252
- Spearman correlation coefficient (-1 to 1)
253
-
254
- Example:
255
- >>> spearman_correlation([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
256
- 0.8
257
- """
258
- x = _validate_data(x)
259
- y = _validate_data(y)
260
-
261
- if len(x) != len(y):
262
- raise ValueError("Variables must have the same length")
263
-
264
- if len(x) < 2:
265
- raise ValueError("At least 2 data points required")
266
-
267
- # Create rank mappings
268
- def get_ranks(data):
269
- sorted_data = sorted(enumerate(data), key=lambda x: x[1])
270
- ranks = [0] * len(data)
271
- for rank, (index, _) in enumerate(sorted_data):
272
- ranks[index] = rank + 1
273
- return ranks
274
-
275
- rank_x = get_ranks(x)
276
- rank_y = get_ranks(y)
277
-
278
- # Calculate correlation using Pearson's formula on ranks
279
- n = len(rank_x)
280
- sum_rank_x = sum(rank_x)
281
- sum_rank_y = sum(rank_y)
282
- sum_rank_xy = sum(rx * ry for rx, ry in zip(rank_x, rank_y))
283
- sum_rank_x2 = sum(rx ** 2 for rx in rank_x)
284
- sum_rank_y2 = sum(ry ** 2 for ry in rank_y)
285
-
286
- numerator = n * sum_rank_xy - sum_rank_x * sum_rank_y
287
- denominator = math.sqrt((n * sum_rank_x2 - sum_rank_x ** 2) * (n * sum_rank_y2 - sum_rank_y ** 2))
288
-
289
- if denominator == 0:
290
- return 0.0
291
-
292
- return numerator / denominator
293
-
294
-
295
- def kendall_tau(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
296
- """
297
- Calculate Kendall's tau correlation coefficient.
298
-
299
- Kendall's tau measures ordinal association between variables.
300
-
301
- Args:
302
- x: First variable data
303
- y: Second variable data
304
-
305
- Returns:
306
- Kendall's tau coefficient (-1 to 1)
307
-
308
- Example:
309
- >>> kendall_tau([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
310
- 0.6
311
- """
312
- x = _validate_data(x)
313
- y = _validate_data(y)
314
-
315
- if len(x) != len(y):
316
- raise ValueError("Variables must have the same length")
317
-
318
- if len(x) < 2:
319
- raise ValueError("At least 2 data points required")
320
-
321
- n = len(x)
322
- concordant = 0
323
- discordant = 0
324
-
325
- for i in range(n):
326
- for j in range(i + 1, n):
327
- x_diff = x[i] - x[j]
328
- y_diff = y[i] - y[j]
329
-
330
- if x_diff * y_diff > 0:
331
- concordant += 1
332
- elif x_diff * y_diff < 0:
333
- discordant += 1
334
-
335
- total_pairs = n * (n - 1) / 2
336
-
337
- if total_pairs == 0:
338
- return 0.0
339
-
340
- return (concordant - discordant) / total_pairs
341
-
342
-
343
- def point_biserial_correlation(x: List[Union[int, float]], y: List[bool]) -> float:
344
- """
345
- Calculate point-biserial correlation coefficient.
346
-
347
- Point-biserial correlation measures the relationship between a continuous
348
- variable and a binary variable.
349
-
350
- Args:
351
- x: Continuous variable data
352
- y: Binary variable data (True/False or 1/0)
353
-
354
- Returns:
355
- Point-biserial correlation coefficient (-1 to 1)
356
-
357
- Example:
358
- >>> point_biserial_correlation([1, 2, 3, 4, 5], [True, False, True, False, True])
359
- 0.31622776601683794
360
- """
361
- x = _validate_data(x)
362
-
363
- if len(x) != len(y):
364
- raise ValueError("Variables must have the same length")
365
-
366
- if len(x) < 2:
367
- raise ValueError("At least 2 data points required")
368
-
369
- # Convert boolean to numeric
370
- y_numeric = [1 if yi else 0 for yi in y]
371
-
372
- # Calculate means for each group
373
- group_1 = [xi for xi, yi in zip(x, y_numeric) if yi == 1]
374
- group_0 = [xi for xi, yi in zip(x, y_numeric) if yi == 0]
375
-
376
- if not group_1 or not group_0:
377
- return 0.0
378
-
379
- mean_1 = arithmetic_mean(group_1)
380
- mean_0 = arithmetic_mean(group_0)
381
-
382
- # Calculate standard deviation
383
- std_x = math.sqrt(sum_xx(x) / (len(x) - 1))
384
-
385
- if std_x == 0:
386
- return 0.0
387
-
388
- # Calculate proportions
389
- p = len(group_1) / len(x)
390
- q = 1 - p
391
-
392
- # Point-biserial correlation formula
393
- return (mean_1 - mean_0) / std_x * math.sqrt(p * q)
394
-
395
-
396
- # Multiple regression functions
397
-
398
- def multiple_linear_regression(x_vars: List[List[Union[int, float]]], y: List[Union[int, float]]) -> Tuple[List[float], float, float]:
399
- """
400
- Perform multiple linear regression.
401
-
402
- Args:
403
- x_vars: List of independent variable data (each inner list is one variable)
404
- y: Dependent variable data
405
-
406
- Returns:
407
- Tuple of (coefficients, intercept, r_squared)
408
-
409
- Example:
410
- >>> x1 = [1, 2, 3, 4, 5]
411
- >>> x2 = [2, 4, 6, 8, 10]
412
- >>> y = [3, 5, 7, 9, 11]
413
- >>> coeffs, intercept, r_sq = multiple_linear_regression([x1, x2], y)
414
- """
415
- if not x_vars:
416
- raise ValueError("At least one independent variable required")
417
-
418
- # Validate all variables have same length
419
- lengths = [len(x) for x in x_vars] + [len(y)]
420
- if len(set(lengths)) != 1:
421
- raise ValueError("All variables must have the same length")
422
-
423
- # Validate data
424
- x_vars = [_validate_data(x) for x in x_vars]
425
- y = _validate_data(y)
426
-
427
- n = len(y)
428
- k = len(x_vars)
429
-
430
- if n <= k:
431
- raise ValueError("Number of observations must be greater than number of variables")
432
-
433
- # For educational purposes, we'll use a simple approach
434
- # In practice, you'd use numpy.linalg or scipy for better numerical stability
435
-
436
- # Create design matrix
437
- X = []
438
- for i in range(n):
439
- row = [1] # Intercept term
440
- for j in range(k):
441
- row.append(x_vars[j][i])
442
- X.append(row)
443
-
444
- # Simple least squares solution (for educational purposes)
445
- # In practice, use numpy.linalg.lstsq
446
-
447
- # Calculate coefficients using normal equations
448
- XT = list(zip(*X)) # Transpose
449
- XTX = [[sum(XT[i][r] * XT[j][r] for r in range(n)) for j in range(k+1)] for i in range(k+1)]
450
- XTy = [sum(XT[i][r] * y[r] for r in range(n)) for i in range(k+1)]
451
-
452
- # Simple matrix inversion (for educational purposes)
453
- # In practice, use numpy.linalg.inv
454
-
455
- # For 2x2 case (intercept + 1 variable)
456
- if k == 1:
457
- det = XTX[0][0] * XTX[1][1] - XTX[0][1] * XTX[1][0]
458
- if abs(det) < 1e-10:
459
- raise ValueError("Singular matrix - variables may be collinear")
460
-
461
- inv_00 = XTX[1][1] / det
462
- inv_01 = -XTX[0][1] / det
463
- inv_10 = -XTX[1][0] / det
464
- inv_11 = XTX[0][0] / det
465
-
466
- intercept = inv_00 * XTy[0] + inv_01 * XTy[1]
467
- coeff = inv_10 * XTy[0] + inv_11 * XTy[1]
468
- coefficients = [coeff]
469
- else:
470
- # For educational purposes, return simple approximation
471
- # In practice, use proper matrix operations
472
- coefficients = [0.0] * k
473
- intercept = arithmetic_mean(y)
474
-
475
- # Calculate R-squared
476
- y_pred = [intercept + sum(coeff * x_vars[j][i] for j, coeff in enumerate(coefficients)) for i in range(n)]
477
- ss_tot = sum((yi - arithmetic_mean(y)) ** 2 for yi in y)
478
- ss_res = sum((yi - y_pred[i]) ** 2 for i, yi in enumerate(y))
479
-
480
- r_squared = 1 - (ss_res / ss_tot) if ss_tot != 0 else 0
481
-
482
- return coefficients, intercept, r_squared
483
-
484
-
485
- def polynomial_regression(x: List[Union[int, float]], y: List[Union[int, float]], degree: int = 2) -> Tuple[List[float], float]:
486
- """
487
- Perform polynomial regression.
488
-
489
- Args:
490
- x: Independent variable data
491
- y: Dependent variable data
492
- degree: Degree of polynomial (1=linear, 2=quadratic, etc.)
493
-
494
- Returns:
495
- Tuple of (coefficients, r_squared)
496
-
497
- Example:
498
- >>> x = [1, 2, 3, 4, 5]
499
- >>> y = [1, 4, 9, 16, 25]
500
- >>> coeffs, r_sq = polynomial_regression(x, y, degree=2)
501
- """
502
- x = _validate_data(x)
503
- y = _validate_data(y)
504
-
505
- if len(x) != len(y):
506
- raise ValueError("Variables must have the same length")
507
-
508
- if degree < 1:
509
- raise ValueError("Degree must be at least 1")
510
-
511
- if len(x) <= degree:
512
- raise ValueError("Number of observations must be greater than degree")
513
-
514
- # Create polynomial features
515
- x_vars = []
516
- for d in range(1, degree + 1):
517
- x_vars.append([xi ** d for xi in x])
518
-
519
- # Use multiple regression
520
- coefficients, intercept, r_squared = multiple_linear_regression(x_vars, y)
521
-
522
- # Add intercept as first coefficient
523
- all_coefficients = [intercept] + coefficients
524
-
525
- return all_coefficients, r_squared
526
-
527
-
528
- def residual_analysis(x: List[Union[int, float]], y: List[Union[int, float]]) -> Tuple[List[float], float, float]:
529
- """
530
- Perform residual analysis for linear regression.
531
-
532
- Args:
533
- x: Independent variable data
534
- y: Dependent variable data
535
-
536
- Returns:
537
- Tuple of (residuals, r_squared, adjusted_r_squared)
538
-
539
- Example:
540
- >>> x = [1, 2, 3, 4, 5]
541
- >>> y = [2, 4, 5, 4, 5]
542
- >>> residuals, r_sq, adj_r_sq = residual_analysis(x, y)
543
- """
544
- x = _validate_data(x)
545
- y = _validate_data(y)
546
-
547
- if len(x) != len(y):
548
- raise ValueError("Variables must have the same length")
549
-
550
- if len(x) < 3:
551
- raise ValueError("At least 3 data points required")
552
-
553
- # Perform regression
554
- slope, intercept, r_squared = linear_regression(x, y)
555
-
556
- # Calculate residuals
557
- residuals = [yi - (slope * xi + intercept) for xi, yi in zip(x, y)]
558
-
559
- # Calculate adjusted R-squared
560
- n = len(x)
561
- k = 1 # Number of independent variables
562
- adjusted_r_squared = 1 - ((1 - r_squared) * (n - 1) / (n - k - 1))
563
-
564
- return residuals, r_squared, adjusted_r_squared
565
-
566
-
567
- # Association measures for categorical data
568
-
569
- def chi_square_test(observed: List[List[int]]) -> Tuple[float, float, int]:
570
- """
571
- Perform chi-square test of independence.
572
-
573
- Args:
574
- observed: Observed frequency table (2D list)
575
-
576
- Returns:
577
- Tuple of (chi_square_statistic, p_value, degrees_of_freedom)
578
-
579
- Example:
580
- >>> observed = [[10, 20], [15, 25]]
581
- >>> chi_sq, p_val, df = chi_square_test(observed)
582
- """
583
- if not observed or not observed[0]:
584
- raise ValueError("Invalid observed frequency table")
585
-
586
- rows = len(observed)
587
- cols = len(observed[0])
588
-
589
- if rows < 2 or cols < 2:
590
- raise ValueError("Table must be at least 2x2")
591
-
592
- # Calculate row and column totals
593
- row_totals = [sum(row) for row in observed]
594
- col_totals = [sum(observed[i][j] for i in range(rows)) for j in range(cols)]
595
- total = sum(row_totals)
596
-
597
- if total == 0:
598
- raise ValueError("Total frequency cannot be zero")
599
-
600
- # Calculate expected frequencies
601
- expected = []
602
- for i in range(rows):
603
- expected_row = []
604
- for j in range(cols):
605
- expected_freq = (row_totals[i] * col_totals[j]) / total
606
- expected_row.append(expected_freq)
607
- expected.append(expected_row)
608
-
609
- # Calculate chi-square statistic
610
- chi_square = 0
611
- for i in range(rows):
612
- for j in range(cols):
613
- if expected[i][j] != 0:
614
- chi_square += ((observed[i][j] - expected[i][j]) ** 2) / expected[i][j]
615
-
616
- # Calculate degrees of freedom
617
- df = (rows - 1) * (cols - 1)
618
-
619
- # Simple p-value approximation (for educational purposes)
620
- # In practice, use scipy.stats.chi2.sf
621
- if df == 1:
622
- # For 1 degree of freedom, use normal approximation
623
- p_value = 2 * (1 - 0.5 * (1 + math.erf(math.sqrt(chi_square/2) / math.sqrt(2))))
624
- else:
625
- # Simple approximation for other degrees of freedom
626
- p_value = max(0, 1 - chi_square / (df + chi_square))
627
-
628
- return chi_square, p_value, df
629
-
630
-
631
- def cramers_v(observed: List[List[int]]) -> float:
632
- """
633
- Calculate Cramer's V association measure.
634
-
635
- Cramer's V measures the strength of association between categorical variables.
636
-
637
- Args:
638
- observed: Observed frequency table (2D list)
639
-
640
- Returns:
641
- Cramer's V (0 to 1)
642
-
643
- Example:
644
- >>> observed = [[10, 20], [15, 25]]
645
- >>> v = cramers_v(observed)
646
- """
647
- chi_square, _, df = chi_square_test(observed)
648
-
649
- rows = len(observed)
650
- cols = len(observed[0])
651
- total = sum(sum(row) for row in observed)
652
-
653
- # Calculate minimum of rows-1 and cols-1
654
- min_dim = min(rows - 1, cols - 1)
655
-
656
- if min_dim == 0 or total == 0:
657
- return 0.0
658
-
659
- # Cramer's V formula
660
- v = math.sqrt(chi_square / (total * min_dim))
661
-
662
- return min(v, 1.0) # Ensure V doesn't exceed 1
663
-
664
-
665
- def contingency_coefficient(observed: List[List[int]]) -> float:
666
- """
667
- Calculate contingency coefficient.
668
-
669
- Contingency coefficient measures association between categorical variables.
670
-
671
- Args:
672
- observed: Observed frequency table (2D list)
673
-
674
- Returns:
675
- Contingency coefficient (0 to less than 1)
676
-
677
- Example:
678
- >>> observed = [[10, 20], [15, 25]]
679
- >>> c = contingency_coefficient(observed)
680
- """
681
- chi_square, _, _ = chi_square_test(observed)
682
- total = sum(sum(row) for row in observed)
683
-
684
- if total == 0:
685
- return 0.0
686
-
687
- # Contingency coefficient formula
688
- c = math.sqrt(chi_square / (chi_square + total))
689
-
1
+ """
2
+ Multivariate statistics functions for py-stats package.
3
+
4
+ This module provides comprehensive multivariate statistical analysis functions
5
+ including correlation coefficients, covariance, regression analysis, and
6
+ association measures.
7
+ """
8
+
9
+ import math
10
+ import numbers
11
+ from typing import List, Union, Tuple, Optional
12
+
13
+ from .univariate import _validate_data, arithmetic_mean
14
+
15
+
16
+ def pearson_correlation(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
17
+ """
18
+ Calculate Pearson's correlation coefficient.
19
+
20
+ Args:
21
+ x: First variable data
22
+ y: Second variable data
23
+
24
+ Returns:
25
+ Pearson correlation coefficient (-1 to 1)
26
+
27
+ Example:
28
+ >>> pearson_correlation([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
29
+ 0.7745966692414834
30
+ """
31
+ x = _validate_data(x)
32
+ y = _validate_data(y)
33
+
34
+ if len(x) != len(y):
35
+ raise ValueError("Variables must have the same length")
36
+
37
+ if len(x) < 2:
38
+ raise ValueError("At least 2 data points required")
39
+
40
+ n = len(x)
41
+ sum_x = sum(x)
42
+ sum_y = sum(y)
43
+ sum_xy = sum(xi * yi for xi, yi in zip(x, y))
44
+ sum_x2 = sum(xi ** 2 for xi in x)
45
+ sum_y2 = sum(yi ** 2 for yi in y)
46
+
47
+ numerator = n * sum_xy - sum_x * sum_y
48
+ denominator = math.sqrt((n * sum_x2 - sum_x ** 2) * (n * sum_y2 - sum_y ** 2))
49
+
50
+ if denominator == 0:
51
+ return 0.0
52
+
53
+ return numerator / denominator
54
+
55
+
56
+ def product_concentration_ratio(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
57
+ """
58
+ Ratio of the geometric to the arithmetic mean of the paired products x*y.
59
+
60
+ This measures how EVEN the products are, not whether x and y are related.
61
+ It is 1 when every product is identical and falls towards 0 as they spread
62
+ apart, so it is a concentration (inequality) index rather than a
63
+ correlation. It cannot express direction and never goes negative.
64
+
65
+ This function was called q_correlation up to version 1.0.1, which was
66
+ misleading: anti-correlated data scores higher than perfectly correlated
67
+ data under it. q_correlation now implements Yule's Q. For the strength and
68
+ direction of a relationship use pearson_correlation, spearman_correlation
69
+ or kendall_tau.
70
+
71
+ Requires every x*y product to be strictly positive, since the geometric
72
+ mean of a negative number is undefined.
73
+
74
+ Args:
75
+ x: First variable data
76
+ y: Second variable data
77
+
78
+ Returns:
79
+ Ratio in (0, 1]
80
+
81
+ Example:
82
+ >>> product_concentration_ratio([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
83
+ 0.7514157873352774
84
+ >>> product_concentration_ratio([1, 2, 4], [4, 2, 1]) # products all 4
85
+ 1.0
86
+ """
87
+ x = _validate_data(x)
88
+ y = _validate_data(y)
89
+
90
+ if len(x) != len(y):
91
+ raise ValueError("Variables must have the same length")
92
+
93
+ if len(x) < 2:
94
+ raise ValueError("At least 2 data points required")
95
+
96
+ products = [xi * yi for xi, yi in zip(x, y)]
97
+
98
+ # The geometric mean is only defined for positive values. A single negative
99
+ # product used to surface as "math domain error" from inside math.pow.
100
+ if any(pr <= 0 for pr in products):
101
+ raise ValueError(
102
+ "This index requires every x*y product to be positive; "
103
+ "it is undefined for data with differing signs or zeros"
104
+ )
105
+
106
+ # Sum of logs rather than prod-then-root, which overflows for large inputs.
107
+ geometric_mean = math.exp(
108
+ math.fsum(math.log(pr) for pr in products) / len(products)
109
+ )
110
+ arithmetic_mean_products = arithmetic_mean(products)
111
+
112
+ if arithmetic_mean_products == 0:
113
+ return 0.0
114
+
115
+ return geometric_mean / arithmetic_mean_products
116
+
117
+
118
+ def q_correlation(x: List[Union[int, float, bool]], y: List[Union[int, float, bool]]) -> float:
119
+ """
120
+ Calculate Yule's Q, the association between two binary variables.
121
+
122
+ Yule's Q is the standard coefficient named Q. It is built from the 2x2
123
+ table of counts
124
+
125
+ a = both 1 b = x is 1, y is 0
126
+ c = x is 0, y is 1 d = both 0
127
+
128
+ as (ad - bc) / (ad + bc), which is equivalent to (OR - 1) / (OR + 1) for
129
+ the odds ratio OR = ad / bc. It runs from -1 (perfect negative
130
+ association) through 0 (none) to +1 (perfect positive association), and
131
+ reaches +-1 as soon as any one cell is empty.
132
+
133
+ Both variables must be binary: booleans, or the numbers 0 and 1. For two
134
+ continuous variables use pearson_correlation or spearman_correlation.
135
+
136
+ Args:
137
+ x: First binary variable
138
+ y: Second binary variable
139
+
140
+ Returns:
141
+ Yule's Q, between -1 and 1
142
+
143
+ Raises:
144
+ ValueError: If the inputs are not binary, differ in length, or leave
145
+ a margin of the table empty, which makes Q undefined.
146
+
147
+ Example:
148
+ >>> q_correlation([1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0])
149
+ 1.0
150
+ >>> q_correlation([1, 1, 0, 0], [1, 0, 1, 0])
151
+ 0.0
152
+ """
153
+ if len(x) != len(y):
154
+ raise ValueError("Variables must have the same length")
155
+
156
+ if len(x) < 2:
157
+ raise ValueError("At least 2 data points required")
158
+
159
+ def as_binary(values, name):
160
+ out = []
161
+ for v in values:
162
+ if isinstance(v, bool):
163
+ out.append(1 if v else 0)
164
+ elif isinstance(v, numbers.Real) and float(v) in (0.0, 1.0):
165
+ out.append(int(v))
166
+ else:
167
+ raise ValueError(
168
+ f"{name} must contain only booleans or 0/1 values"
169
+ )
170
+ return out
171
+
172
+ xb = as_binary(x, "x")
173
+ yb = as_binary(y, "y")
174
+
175
+ a = sum(1 for xi, yi in zip(xb, yb) if xi == 1 and yi == 1)
176
+ b = sum(1 for xi, yi in zip(xb, yb) if xi == 1 and yi == 0)
177
+ c = sum(1 for xi, yi in zip(xb, yb) if xi == 0 and yi == 1)
178
+ d = sum(1 for xi, yi in zip(xb, yb) if xi == 0 and yi == 0)
179
+
180
+ # An empty row or column means one variable never varies, so there is no
181
+ # association to measure and both ad and bc are zero.
182
+ if (a + b) == 0 or (c + d) == 0 or (a + c) == 0 or (b + d) == 0:
183
+ raise ValueError(
184
+ "Yule's Q is undefined when either variable is constant"
185
+ )
186
+
187
+ return (a * d - b * c) / (a * d + b * c)
188
+
189
+
190
+ def covariance(x: List[Union[int, float]], y: List[Union[int, float]], population: bool = False) -> float:
191
+ """
192
+ Calculate covariance between two variables.
193
+
194
+ Args:
195
+ x: First variable data
196
+ y: Second variable data
197
+ population: If True, calculate population covariance (n denominator)
198
+ If False, calculate sample covariance (n-1 denominator)
199
+
200
+ Returns:
201
+ Covariance
202
+
203
+ Example:
204
+ >>> covariance([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
205
+ 1.5
206
+ """
207
+ x = _validate_data(x)
208
+ y = _validate_data(y)
209
+
210
+ if len(x) != len(y):
211
+ raise ValueError("Variables must have the same length")
212
+
213
+ if len(x) < 2:
214
+ raise ValueError("At least 2 data points required")
215
+
216
+ mean_x = arithmetic_mean(x)
217
+ mean_y = arithmetic_mean(y)
218
+
219
+ sum_xy = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))
220
+
221
+ denominator = len(x) if population else len(x) - 1
222
+ return sum_xy / denominator
223
+
224
+
225
+ def linear_regression(x: List[Union[int, float]], y: List[Union[int, float]]) -> Tuple[float, float, float]:
226
+ """
227
+ Perform simple linear regression.
228
+
229
+ Args:
230
+ x: Independent variable data
231
+ y: Dependent variable data
232
+
233
+ Returns:
234
+ Tuple of (slope, intercept, r_squared)
235
+
236
+ Example:
237
+ >>> slope, intercept, r_squared = linear_regression([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
238
+ >>> print(f"y = {slope:.2f}x + {intercept:.2f}, R-squared = {r_squared:.3f}")
239
+ y = 0.60x + 2.20, R-squared = 0.600
240
+ """
241
+ x = _validate_data(x)
242
+ y = _validate_data(y)
243
+
244
+ if len(x) != len(y):
245
+ raise ValueError("Variables must have the same length")
246
+
247
+ if len(x) < 2:
248
+ raise ValueError("At least 2 data points required")
249
+
250
+ n = len(x)
251
+ sum_x = sum(x)
252
+ sum_y = sum(y)
253
+ sum_xy = sum(xi * yi for xi, yi in zip(x, y))
254
+ sum_x2 = sum(xi ** 2 for xi in x)
255
+
256
+ # Calculate slope and intercept
257
+ # A constant x has no spread to regress against; without this the division
258
+ # surfaced as a bare ZeroDivisionError.
259
+ denominator = n * sum_x2 - sum_x ** 2
260
+ if denominator == 0:
261
+ raise ValueError(
262
+ "Cannot fit a line when x has no variation (all x values are equal)"
263
+ )
264
+
265
+ slope = (n * sum_xy - sum_x * sum_y) / denominator
266
+ intercept = (sum_y - slope * sum_x) / n
267
+
268
+ # Calculate R-squared
269
+ mean_y = arithmetic_mean(y)
270
+ ss_tot = sum((yi - mean_y) ** 2 for yi in y)
271
+ ss_res = sum((yi - (slope * xi + intercept)) ** 2 for xi, yi in zip(x, y))
272
+
273
+ # R-squared has no meaning when y is constant: there is no variance to
274
+ # explain. Reported as 0.0 (a float, so the return type does not change
275
+ # with the data) rather than 1.0, which would claim a perfect fit.
276
+ r_squared = 1 - (ss_res / ss_tot) if ss_tot != 0 else 0.0
277
+
278
+ return slope, intercept, r_squared
279
+
280
+
281
+ def sum_xx(x: List[Union[int, float]]) -> float:
282
+ """
283
+ Calculate sum of squared deviations from mean (Sxx).
284
+
285
+ Args:
286
+ x: Variable data
287
+
288
+ Returns:
289
+ Sum of squared deviations
290
+
291
+ Example:
292
+ >>> sum_xx([1, 2, 3, 4, 5])
293
+ 10.0
294
+ """
295
+ x = _validate_data(x)
296
+ mean_x = arithmetic_mean(x)
297
+ return sum((xi - mean_x) ** 2 for xi in x)
298
+
299
+
300
+ def sum_yy(y: List[Union[int, float]]) -> float:
301
+ """
302
+ Calculate sum of squared deviations from mean (Syy).
303
+
304
+ Args:
305
+ y: Variable data
306
+
307
+ Returns:
308
+ Sum of squared deviations
309
+
310
+ Example:
311
+ >>> sum_yy([2, 4, 5, 4, 5])
312
+ 6.0
313
+ """
314
+ y = _validate_data(y)
315
+ mean_y = arithmetic_mean(y)
316
+ return sum((yi - mean_y) ** 2 for yi in y)
317
+
318
+
319
+ def sum_xy(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
320
+ """
321
+ Calculate sum of cross-products of deviations (Sxy).
322
+
323
+ Args:
324
+ x: First variable data
325
+ y: Second variable data
326
+
327
+ Returns:
328
+ Sum of cross-products
329
+
330
+ Example:
331
+ >>> sum_xy([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
332
+ 6.0
333
+ """
334
+ x = _validate_data(x)
335
+ y = _validate_data(y)
336
+
337
+ if len(x) != len(y):
338
+ raise ValueError("Variables must have the same length")
339
+
340
+ mean_x = arithmetic_mean(x)
341
+ mean_y = arithmetic_mean(y)
342
+
343
+ return sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))
344
+
345
+
346
+ # Additional correlation functions
347
+
348
+ def spearman_correlation(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
349
+ """
350
+ Calculate Spearman's rank correlation coefficient.
351
+
352
+ Spearman correlation measures the strength of monotonic relationship.
353
+
354
+ Args:
355
+ x: First variable data
356
+ y: Second variable data
357
+
358
+ Returns:
359
+ Spearman correlation coefficient (-1 to 1)
360
+
361
+ Example:
362
+ >>> spearman_correlation([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
363
+ 0.7378647873726218
364
+ """
365
+ x = _validate_data(x)
366
+ y = _validate_data(y)
367
+
368
+ if len(x) != len(y):
369
+ raise ValueError("Variables must have the same length")
370
+
371
+ if len(x) < 2:
372
+ raise ValueError("At least 2 data points required")
373
+
374
+ # Create rank mappings
375
+ def get_ranks(data):
376
+ """Rank with ties averaged (the midrank), as Spearman requires.
377
+
378
+ Assigning tied values distinct index-ordered ranks made the measure
379
+ depend on input order and reported a perfect 1.0 for data that was
380
+ merely non-decreasing.
381
+ """
382
+ order = sorted(range(len(data)), key=lambda i: data[i])
383
+ ranks = [0.0] * len(data)
384
+ i = 0
385
+ while i < len(order):
386
+ j = i
387
+ while j + 1 < len(order) and data[order[j + 1]] == data[order[i]]:
388
+ j += 1
389
+ midrank = (i + j) / 2.0 + 1.0
390
+ for k in range(i, j + 1):
391
+ ranks[order[k]] = midrank
392
+ i = j + 1
393
+ return ranks
394
+
395
+ rank_x = get_ranks(x)
396
+ rank_y = get_ranks(y)
397
+
398
+ # Calculate correlation using Pearson's formula on ranks
399
+ n = len(rank_x)
400
+ sum_rank_x = sum(rank_x)
401
+ sum_rank_y = sum(rank_y)
402
+ sum_rank_xy = sum(rx * ry for rx, ry in zip(rank_x, rank_y))
403
+ sum_rank_x2 = sum(rx ** 2 for rx in rank_x)
404
+ sum_rank_y2 = sum(ry ** 2 for ry in rank_y)
405
+
406
+ numerator = n * sum_rank_xy - sum_rank_x * sum_rank_y
407
+ denominator = math.sqrt((n * sum_rank_x2 - sum_rank_x ** 2) * (n * sum_rank_y2 - sum_rank_y ** 2))
408
+
409
+ # A constant variable has no ranking to correlate with. Returning 0.0 here
410
+ # would assert independence we cannot know; the old code reached this only
411
+ # by accident and returned 1.0 for a constant y.
412
+ if denominator == 0:
413
+ raise ValueError(
414
+ "Spearman correlation is undefined when a variable is constant"
415
+ )
416
+
417
+ return numerator / denominator
418
+
419
+
420
+ def kendall_tau(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
421
+ """
422
+ Calculate Kendall's tau correlation coefficient.
423
+
424
+ Kendall's tau measures ordinal association between variables.
425
+
426
+ Args:
427
+ x: First variable data
428
+ y: Second variable data
429
+
430
+ Returns:
431
+ Kendall's tau coefficient (-1 to 1)
432
+
433
+ Example:
434
+ >>> kendall_tau([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
435
+ 0.6708203932499369
436
+ """
437
+ x = _validate_data(x)
438
+ y = _validate_data(y)
439
+
440
+ if len(x) != len(y):
441
+ raise ValueError("Variables must have the same length")
442
+
443
+ if len(x) < 2:
444
+ raise ValueError("At least 2 data points required")
445
+
446
+ n = len(x)
447
+ concordant = 0
448
+ discordant = 0
449
+ ties_x = 0
450
+ ties_y = 0
451
+
452
+ for i in range(n):
453
+ for j in range(i + 1, n):
454
+ # Classify on the signs of the two differences, never on their
455
+ # product. A product underflows to 0.0 when both differences are
456
+ # tiny -- (1e-300 - 0.0) ** 2 is exactly 0.0 -- and the pair then
457
+ # looked tied on neither variable, so it fell out of the numerator
458
+ # while staying in the denominator. [1e-310, 2e-310, 3e-310,
459
+ # 4e-310] against itself reported tau = 0.0 instead of 1.0.
460
+ x_sign = (x[i] > x[j]) - (x[i] < x[j])
461
+ y_sign = (y[i] > y[j]) - (y[i] < y[j])
462
+
463
+ if x_sign == 0 or y_sign == 0:
464
+ # Tied on at least one variable. These were previously left in
465
+ # the denominator untouched (tau-a), which silently reported a
466
+ # different statistic than the tau-b every other tool returns.
467
+ if x_sign == 0:
468
+ ties_x += 1
469
+ if y_sign == 0:
470
+ ties_y += 1
471
+ elif x_sign == y_sign:
472
+ concordant += 1
473
+ else:
474
+ discordant += 1
475
+
476
+ total_pairs = n * (n - 1) / 2
477
+
478
+ # tau-b normalises by the pairs that were actually comparable on each
479
+ # variable, so ties do not drag the coefficient towards zero.
480
+ denominator = math.sqrt((total_pairs - ties_x) * (total_pairs - ties_y))
481
+
482
+ if denominator == 0:
483
+ raise ValueError(
484
+ "Kendall's tau is undefined when every pair is tied on a variable"
485
+ )
486
+
487
+ return (concordant - discordant) / denominator
488
+
489
+
490
+ def point_biserial_correlation(x: List[Union[int, float]], y: List[bool]) -> float:
491
+ """
492
+ Calculate point-biserial correlation coefficient.
493
+
494
+ Point-biserial correlation measures the relationship between a continuous
495
+ variable and a binary variable.
496
+
497
+ Args:
498
+ x: Continuous variable data
499
+ y: Binary variable data (True/False or 1/0)
500
+
501
+ Returns:
502
+ Point-biserial correlation coefficient (-1 to 1)
503
+
504
+ Example:
505
+ >>> point_biserial_correlation([1, 2, 3, 4, 5], [False, False, True, True, True])
506
+ 0.8660254037844385
507
+ """
508
+ x = _validate_data(x)
509
+
510
+ if len(x) != len(y):
511
+ raise ValueError("Variables must have the same length")
512
+
513
+ if len(x) < 2:
514
+ raise ValueError("At least 2 data points required")
515
+
516
+ # Convert boolean to numeric. "1 if yi else 0" accepted any truthy object,
517
+ # so a stray string like "maybe" was silently counted as the 1 group.
518
+ y_numeric = []
519
+ for yi in y:
520
+ if isinstance(yi, bool):
521
+ y_numeric.append(1 if yi else 0)
522
+ elif isinstance(yi, numbers.Real) and float(yi) in (0.0, 1.0):
523
+ y_numeric.append(int(yi))
524
+ else:
525
+ raise ValueError(
526
+ "Binary variable must contain only booleans or 0/1 values"
527
+ )
528
+
529
+ # Calculate means for each group
530
+ group_1 = [xi for xi, yi in zip(x, y_numeric) if yi == 1]
531
+ group_0 = [xi for xi, yi in zip(x, y_numeric) if yi == 0]
532
+
533
+ if not group_1 or not group_0:
534
+ return 0.0
535
+
536
+ mean_1 = arithmetic_mean(group_1)
537
+ mean_0 = arithmetic_mean(group_0)
538
+
539
+ # Calculate standard deviation
540
+ # Population SD (divide by n). The point-biserial coefficient is defined to
541
+ # equal Pearson's r on the same data; using the sample SD (n-1) made the
542
+ # two disagree, e.g. -0.7746 against Pearson's -0.8660.
543
+ std_x = math.sqrt(sum_xx(x) / len(x))
544
+
545
+ if std_x == 0:
546
+ return 0.0
547
+
548
+ # Calculate proportions
549
+ p = len(group_1) / len(x)
550
+ q = 1 - p
551
+
552
+ # Point-biserial correlation formula
553
+ return (mean_1 - mean_0) / std_x * math.sqrt(p * q)
554
+
555
+
556
+ # Multiple regression functions
557
+
558
+ def multiple_linear_regression(x_vars: List[List[Union[int, float]]], y: List[Union[int, float]]) -> Tuple[List[float], float, float]:
559
+ """
560
+ Perform multiple linear regression.
561
+
562
+ Args:
563
+ x_vars: List of independent variable data (each inner list is one variable)
564
+ y: Dependent variable data
565
+
566
+ Returns:
567
+ Tuple of (coefficients, intercept, r_squared)
568
+
569
+ Example:
570
+ >>> x1 = [1, 2, 3, 4, 5]
571
+ >>> x2 = [1, 1, 2, 3, 5]
572
+ >>> y = [1 + 2 * a + 3 * b for a, b in zip(x1, x2)]
573
+ >>> coeffs, intercept, r_sq = multiple_linear_regression([x1, x2], y)
574
+ >>> [round(c, 6) for c in coeffs], round(intercept, 6)
575
+ ([2.0, 3.0], 1.0)
576
+ """
577
+ if not x_vars:
578
+ raise ValueError("At least one independent variable required")
579
+
580
+ # Validate all variables have same length
581
+ lengths = [len(x) for x in x_vars] + [len(y)]
582
+ if len(set(lengths)) != 1:
583
+ raise ValueError("All variables must have the same length")
584
+
585
+ # Validate data
586
+ x_vars = [_validate_data(x) for x in x_vars]
587
+ y = _validate_data(y)
588
+
589
+ n = len(y)
590
+ k = len(x_vars)
591
+
592
+ if n <= k:
593
+ raise ValueError("Number of observations must be greater than number of variables")
594
+
595
+ # Solve the normal equations (X'X) b = X'y by Gaussian elimination with
596
+ # partial pivoting. The previous implementation special-cased k == 1 and
597
+ # returned [0.0] * k for anything larger, so every fit with two or more
598
+ # predictors silently reported zero coefficients.
599
+ X = []
600
+ for i in range(n):
601
+ row = [1.0] # intercept term
602
+ for j in range(k):
603
+ row.append(float(x_vars[j][i]))
604
+ X.append(row)
605
+
606
+ size = k + 1
607
+ # Augmented matrix [X'X | X'y]
608
+ aug = []
609
+ for i in range(size):
610
+ row = [sum(X[r][i] * X[r][j] for r in range(n)) for j in range(size)]
611
+ row.append(sum(X[r][i] * y[r] for r in range(n)))
612
+ aug.append(row)
613
+
614
+ # Scale the singularity threshold to the matrix, so the test means the same
615
+ # thing whether the data is in millimetres or kilometres.
616
+ scale = max(abs(v) for row in aug for v in row[:size]) or 1.0
617
+
618
+ for col in range(size):
619
+ pivot_row = max(range(col, size), key=lambda r: abs(aug[r][col]))
620
+ if abs(aug[pivot_row][col]) <= 1e-12 * scale:
621
+ raise ValueError(
622
+ "Singular matrix - variables may be collinear"
623
+ )
624
+ aug[col], aug[pivot_row] = aug[pivot_row], aug[col]
625
+
626
+ pivot = aug[col][col]
627
+ for r in range(size):
628
+ if r == col:
629
+ continue
630
+ factor = aug[r][col] / pivot
631
+ if factor:
632
+ for c in range(col, size + 1):
633
+ aug[r][c] -= factor * aug[col][c]
634
+
635
+ solution = [aug[i][size] / aug[i][i] for i in range(size)]
636
+ intercept = solution[0]
637
+ coefficients = solution[1:]
638
+
639
+ # Calculate R-squared
640
+ y_pred = [intercept + sum(coeff * x_vars[j][i] for j, coeff in enumerate(coefficients)) for i in range(n)]
641
+ ss_tot = sum((yi - arithmetic_mean(y)) ** 2 for yi in y)
642
+ ss_res = sum((yi - y_pred[i]) ** 2 for i, yi in enumerate(y))
643
+
644
+ r_squared = 1 - (ss_res / ss_tot) if ss_tot != 0 else 0
645
+
646
+ return coefficients, intercept, r_squared
647
+
648
+
649
+ def polynomial_regression(x: List[Union[int, float]], y: List[Union[int, float]], degree: int = 2) -> Tuple[List[float], float]:
650
+ """
651
+ Perform polynomial regression.
652
+
653
+ Args:
654
+ x: Independent variable data
655
+ y: Dependent variable data
656
+ degree: Degree of polynomial (1=linear, 2=quadratic, etc.)
657
+
658
+ Returns:
659
+ Tuple of (coefficients, r_squared). Coefficients are ordered highest
660
+ degree first, as numpy.polyfit returns them: for degree=2 the list is
661
+ [a, b, c] for a*x**2 + b*x + c.
662
+
663
+ Example:
664
+ >>> x = [1, 2, 3, 4, 5]
665
+ >>> y = [1, 4, 9, 16, 25]
666
+ >>> coeffs, r_sq = polynomial_regression(x, y, degree=2)
667
+ """
668
+ x = _validate_data(x)
669
+ y = _validate_data(y)
670
+
671
+ if len(x) != len(y):
672
+ raise ValueError("Variables must have the same length")
673
+
674
+ if degree < 1:
675
+ raise ValueError("Degree must be at least 1")
676
+
677
+ if len(x) <= degree:
678
+ raise ValueError("Number of observations must be greater than degree")
679
+
680
+ # Create polynomial features
681
+ x_vars = []
682
+ for d in range(1, degree + 1):
683
+ x_vars.append([xi ** d for xi in x])
684
+
685
+ # Use multiple regression
686
+ coefficients, intercept, r_squared = multiple_linear_regression(x_vars, y)
687
+
688
+ # Highest degree first, matching numpy.polyfit, so coefficients[0] is the
689
+ # leading term. The order was previously undocumented and ran the other
690
+ # way, which made the returned list easy to misread.
691
+ all_coefficients = list(reversed(coefficients)) + [intercept]
692
+
693
+ return all_coefficients, r_squared
694
+
695
+
696
+ def residual_analysis(x: List[Union[int, float]], y: List[Union[int, float]]) -> Tuple[List[float], float, float]:
697
+ """
698
+ Perform residual analysis for linear regression.
699
+
700
+ Args:
701
+ x: Independent variable data
702
+ y: Dependent variable data
703
+
704
+ Returns:
705
+ Tuple of (residuals, r_squared, adjusted_r_squared)
706
+
707
+ Example:
708
+ >>> x = [1, 2, 3, 4, 5]
709
+ >>> y = [2, 4, 5, 4, 5]
710
+ >>> residuals, r_sq, adj_r_sq = residual_analysis(x, y)
711
+ """
712
+ x = _validate_data(x)
713
+ y = _validate_data(y)
714
+
715
+ if len(x) != len(y):
716
+ raise ValueError("Variables must have the same length")
717
+
718
+ if len(x) < 3:
719
+ raise ValueError("At least 3 data points required")
720
+
721
+ # Perform regression
722
+ slope, intercept, r_squared = linear_regression(x, y)
723
+
724
+ # Calculate residuals
725
+ residuals = [yi - (slope * xi + intercept) for xi, yi in zip(x, y)]
726
+
727
+ # Calculate adjusted R-squared
728
+ n = len(x)
729
+ k = 1 # Number of independent variables
730
+ adjusted_r_squared = 1 - ((1 - r_squared) * (n - 1) / (n - k - 1))
731
+
732
+ return residuals, r_squared, adjusted_r_squared
733
+
734
+
735
+ # Association measures for categorical data
736
+
737
+ def _upper_regularized_gamma(s_param: float, x: float) -> float:
738
+ """Regularized upper incomplete gamma Q(s, x) = 1 - P(s, x).
739
+
740
+ Returns the UPPER function directly rather than 1 - lower. In the far tail
741
+ the lower function is indistinguishable from 1.0 in double precision, so
742
+ subtracting it collapses the answer to exactly 0.0 -- at df=1, chi2=120
743
+ that turned 6.3e-28 into nothing. The continued fraction below computes Q
744
+ without that cancellation.
745
+
746
+ Series expansion for x < s+1, continued fraction otherwise, which is where
747
+ each converges quickly. Pure Python so the package keeps no dependencies.
748
+ """
749
+ if x <= 0:
750
+ return 1.0
751
+
752
+ log_gamma_s = math.lgamma(s_param)
753
+
754
+ if x < s_param + 1.0:
755
+ # Series for the lower function; Q is not small in this region, so
756
+ # taking 1 - P here costs no meaningful precision.
757
+ term = 1.0 / s_param
758
+ total = term
759
+ for n in range(1, 1000):
760
+ term *= x / (s_param + n)
761
+ total += term
762
+ if abs(term) < abs(total) * 1e-16:
763
+ break
764
+ lower = total * math.exp(-x + s_param * math.log(x) - log_gamma_s)
765
+ return 1.0 - lower
766
+
767
+ # Lentz's continued fraction for Q(s, x), accurate deep into the tail.
768
+ tiny = 1e-300
769
+ b = x + 1.0 - s_param
770
+ c = 1.0 / tiny
771
+ d = 1.0 / b
772
+ h = d
773
+ for i in range(1, 1000):
774
+ an = -i * (i - s_param)
775
+ b += 2.0
776
+ d = an * d + b
777
+ if abs(d) < tiny:
778
+ d = tiny
779
+ c = b + an / c
780
+ if abs(c) < tiny:
781
+ c = tiny
782
+ d = 1.0 / d
783
+ delta = d * c
784
+ h *= delta
785
+ if abs(delta - 1.0) < 1e-16:
786
+ break
787
+ return math.exp(-x + s_param * math.log(x) - log_gamma_s) * h
788
+
789
+
790
+ def _chi_square_sf(chi_square: float, df: int) -> float:
791
+ """Upper tail probability of the chi-square distribution.
792
+
793
+ This replaces two approximations that were wrong in different ways: the
794
+ df == 1 branch halved the z-score, and the df > 1 branch used
795
+ 1 - chi/(df+chi), which is not a distribution function at all. Both could
796
+ reverse a significance decision.
797
+ """
798
+ if df <= 0:
799
+ raise ValueError("Degrees of freedom must be positive")
800
+ if chi_square <= 0:
801
+ return 1.0
802
+ return max(0.0, min(1.0, _upper_regularized_gamma(df / 2.0, chi_square / 2.0)))
803
+
804
+
805
+ def chi_square_test(observed: List[List[int]]) -> Tuple[float, float, int]:
806
+ """
807
+ Perform chi-square test of independence.
808
+
809
+ Args:
810
+ observed: Observed frequency table (2D list)
811
+
812
+ Returns:
813
+ Tuple of (chi_square_statistic, p_value, degrees_of_freedom)
814
+
815
+ Example:
816
+ >>> observed = [[10, 20], [15, 25]]
817
+ >>> chi_sq, p_val, df = chi_square_test(observed)
818
+ """
819
+ if not observed or not observed[0]:
820
+ raise ValueError("Invalid observed frequency table")
821
+
822
+ rows = len(observed)
823
+ cols = len(observed[0])
824
+
825
+ if rows < 2 or cols < 2:
826
+ raise ValueError("Table must be at least 2x2")
827
+
828
+ # A ragged table used to fall through and raise IndexError from deep inside
829
+ # the expected-frequency loop.
830
+ if any(len(row) != cols for row in observed):
831
+ raise ValueError("All rows of the table must have the same length")
832
+ if any(value < 0 for row in observed for value in row):
833
+ raise ValueError("Frequencies cannot be negative")
834
+
835
+ # Calculate row and column totals
836
+ row_totals = [sum(row) for row in observed]
837
+ col_totals = [sum(observed[i][j] for i in range(rows)) for j in range(cols)]
838
+ total = sum(row_totals)
839
+
840
+ if total == 0:
841
+ raise ValueError("Total frequency cannot be zero")
842
+
843
+ # Calculate expected frequencies
844
+ expected = []
845
+ for i in range(rows):
846
+ expected_row = []
847
+ for j in range(cols):
848
+ expected_freq = (row_totals[i] * col_totals[j]) / total
849
+ expected_row.append(expected_freq)
850
+ expected.append(expected_row)
851
+
852
+ # Calculate chi-square statistic
853
+ chi_square = 0
854
+ for i in range(rows):
855
+ for j in range(cols):
856
+ if expected[i][j] != 0:
857
+ chi_square += ((observed[i][j] - expected[i][j]) ** 2) / expected[i][j]
858
+
859
+ # Calculate degrees of freedom
860
+ df = (rows - 1) * (cols - 1)
861
+
862
+ p_value = _chi_square_sf(chi_square, df)
863
+
864
+ return chi_square, p_value, df
865
+
866
+
867
+ def cramers_v(observed: List[List[int]]) -> float:
868
+ """
869
+ Calculate Cramer's V association measure.
870
+
871
+ Cramer's V measures the strength of association between categorical variables.
872
+
873
+ Args:
874
+ observed: Observed frequency table (2D list)
875
+
876
+ Returns:
877
+ Cramer's V (0 to 1)
878
+
879
+ Example:
880
+ >>> observed = [[10, 20], [15, 25]]
881
+ >>> v = cramers_v(observed)
882
+ """
883
+ chi_square, _, df = chi_square_test(observed)
884
+
885
+ rows = len(observed)
886
+ cols = len(observed[0])
887
+ total = sum(sum(row) for row in observed)
888
+
889
+ # Calculate minimum of rows-1 and cols-1
890
+ min_dim = min(rows - 1, cols - 1)
891
+
892
+ if min_dim == 0 or total == 0:
893
+ return 0.0
894
+
895
+ # Cramer's V formula
896
+ v = math.sqrt(chi_square / (total * min_dim))
897
+
898
+ return min(v, 1.0) # Ensure V doesn't exceed 1
899
+
900
+
901
+ def contingency_coefficient(observed: List[List[int]]) -> float:
902
+ """
903
+ Calculate contingency coefficient.
904
+
905
+ Contingency coefficient measures association between categorical variables.
906
+
907
+ Args:
908
+ observed: Observed frequency table (2D list)
909
+
910
+ Returns:
911
+ Contingency coefficient (0 to less than 1)
912
+
913
+ Example:
914
+ >>> observed = [[10, 20], [15, 25]]
915
+ >>> c = contingency_coefficient(observed)
916
+ """
917
+ chi_square, _, _ = chi_square_test(observed)
918
+ total = sum(sum(row) for row in observed)
919
+
920
+ if total == 0:
921
+ return 0.0
922
+
923
+ # Contingency coefficient formula
924
+ c = math.sqrt(chi_square / (chi_square + total))
925
+
690
926
  return c