Utilities¶
utilities
¶
Utility functions and helper classes for HeavyTails library.
This module contains various utility functions for data I/O, parameter estimation, and statistical analysis.
AutoFit
¶
Automatic parameter estimation for heavy-tailed distributions.
Provides MLE-based parameter estimation and model selection using AIC/BIC. Integrates with roadmap.py implementations.
Source code in heavytails/utilities.py
compare_distributions
¶
Compare multiple distribution fits and rank by quality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
list[float]
|
Sample data |
required |
distributions
|
list[str] | None
|
List of distribution names (if None, uses common ones) |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, Any]]
|
Dictionary of fit results for each distribution, with rankings |
Examples:
>>> from heavytails import Pareto
>>> dist = Pareto(alpha=2.5, xm=1.0)
>>> data = dist.rvs(500, seed=42)
>>> fitter = AutoFit()
>>> results = fitter.compare_distributions(data, ["pareto", "lognormal"])
>>> "pareto" in results
True
>>> results["pareto"]["rank_AIC"] == 1 # Pareto should rank best
True
Source code in heavytails/utilities.py
fit_distribution
¶
Fit distribution parameters to data using MLE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
list[float]
|
Sample data to fit |
required |
distribution
|
str
|
Distribution name or "auto" for automatic selection |
'auto'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with fitted parameters and fit quality metrics |
Examples:
>>> from heavytails import Pareto
>>> dist = Pareto(alpha=2.5, xm=1.0)
>>> data = dist.rvs(500, seed=42)
>>> fitter = AutoFit()
>>> result = fitter.fit_distribution(data, "pareto")
>>> "parameters" in result
True
>>> abs(result["parameters"]["alpha"] - 2.5) < 0.5
True
Source code in heavytails/utilities.py
DataIO
¶
Data import/export utilities for various file formats.
Supports CSV and JSON formats for data and metadata storage. Provides robust error handling and automatic column detection.
read_csv
staticmethod
¶
Read numerical data from CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
Path | str
|
Path to CSV file |
required |
column
|
str | None
|
Column name to read (if None, auto-detects first numerical column) |
None
|
Returns:
| Type | Description |
|---|---|
list[float]
|
List of numerical data values |
Raises:
| Type | Description |
|---|---|
ValueError
|
If file cannot be read or no numerical data found |
FileNotFoundError
|
If file does not exist |
Examples:
>>> # Create sample CSV
>>> import tempfile
>>> with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
... f.write('value\n1.5\n2.3\n3.7\n')
... temp_path = f.name
>>> data = DataIO.read_csv(temp_path)
>>> len(data)
3
>>> import os
>>> os.unlink(temp_path)
Source code in heavytails/utilities.py
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 | |
read_json
staticmethod
¶
Read data and metadata from JSON file.
Expected JSON structure: { "data": [1.5, 2.3, 3.7, ...], "metadata": { "distribution": "pareto", "parameters": {"alpha": 2.5, "xm": 1.0} } }
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
Path | str
|
Path to JSON file |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "data" and optional "metadata" keys |
Raises:
| Type | Description |
|---|---|
ValueError
|
If file cannot be read or has invalid format |
FileNotFoundError
|
If file does not exist |
Examples:
>>> import tempfile
>>> import json
>>> with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
... json.dump({"data": [1.5, 2.3], "metadata": {"dist": "test"}}, f)
... temp_path = f.name
>>> result = DataIO.read_json(temp_path)
>>> len(result["data"])
2
>>> import os
>>> os.unlink(temp_path)
Source code in heavytails/utilities.py
write_csv
staticmethod
¶
Write numerical data to CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
list[float]
|
List of numerical values |
required |
filepath
|
Path | str
|
Path to output CSV file |
required |
metadata
|
dict[str, Any] | None
|
Optional metadata to include as header comments |
None
|
column_name
|
str
|
Name for the data column (default: "value") |
'value'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If data is empty |
Examples:
>>> import tempfile
>>> import os
>>> data = [1.5, 2.3, 3.7]
>>> with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
... temp_path = f.name
>>> DataIO.write_csv(data, temp_path)
>>> os.path.exists(temp_path)
True
>>> os.unlink(temp_path)
Source code in heavytails/utilities.py
write_json
staticmethod
¶
Write data and metadata to JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
list[float]
|
List of numerical values |
required |
filepath
|
Path | str
|
Path to output JSON file |
required |
metadata
|
dict[str, Any] | None
|
Optional metadata dictionary |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If data is empty |
Examples:
>>> import tempfile
>>> import os
>>> data = [1.5, 2.3, 3.7]
>>> with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
... temp_path = f.name
>>> DataIO.write_json(data, temp_path, {"distribution": "test"})
>>> os.path.exists(temp_path)
True
>>> os.unlink(temp_path)
Source code in heavytails/utilities.py
ParameterValidator
¶
Enhanced parameter validation with informative error messages.
Provides detailed parameter validation with helpful suggestions and typical parameter ranges for all distributions.
suggest_parameters
staticmethod
¶
Suggest reasonable parameter ranges based on data or defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distribution
|
str
|
Distribution name |
required |
data
|
list[float] | None
|
Optional data for data-driven suggestions |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, tuple[float, float]]
|
Dictionary mapping parameter names to (min, max) ranges |
Examples:
>>> validator = ParameterValidator()
>>> ranges = validator.suggest_parameters("pareto")
>>> "alpha" in ranges
True
Source code in heavytails/utilities.py
validate_cauchy
staticmethod
¶
Validate Cauchy parameters.
Source code in heavytails/utilities.py
validate_lognormal
staticmethod
¶
Validate LogNormal parameters.
Source code in heavytails/utilities.py
validate_pareto
staticmethod
¶
Validate Pareto parameters with detailed feedback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Shape parameter (tail index) |
required |
xm
|
float
|
Scale parameter (minimum value) |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If parameters are invalid, with helpful suggestions |
Source code in heavytails/utilities.py
StatisticalSummary
¶
Comprehensive statistical summary for heavy-tailed data.
Provides descriptive statistics, tail-specific measures, and diagnostics for heavy-tail analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
list[float]
|
List of numerical values |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data is empty or contains non-finite values |
Source code in heavytails/utilities.py
basic_stats
¶
Calculate comprehensive basic statistics.
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary with mean, std, variance, skewness, kurtosis, quantiles |
Examples:
>>> data = [1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 20.0]
>>> summary = StatisticalSummary(data)
>>> stats = summary.basic_stats()
>>> "mean" in stats
True
>>> stats["n"]
7
Source code in heavytails/utilities.py
diagnostic_summary
¶
Provide comprehensive heavy-tail diagnostics.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with diagnostics and recommendations |
Examples:
>>> from heavytails import Pareto
>>> dist = Pareto(alpha=2.5, xm=1.0)
>>> data = dist.rvs(500, seed=42)
>>> summary = StatisticalSummary(data)
>>> diagnostics = summary.diagnostic_summary()
>>> "likely_heavy_tailed" in diagnostics
True
Source code in heavytails/utilities.py
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 | |
tail_statistics
¶
Calculate heavy-tail specific statistics.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with Hill estimates, tail ratios, and tail indicators |
Examples:
>>> from heavytails import Pareto
>>> dist = Pareto(alpha=2.5, xm=1.0)
>>> data = dist.rvs(500, seed=42)
>>> summary = StatisticalSummary(data)
>>> tail_stats = summary.tail_statistics()
>>> "tail_ratio_95_50" in tail_stats
True