### Getting Started with kstats-distributions Source: https://github.com/oremif/kstats/blob/master/kstats-distributions/Module.md Demonstrates basic usage of continuous and discrete distributions from the kstats-distributions library. Shows how to instantiate distributions like Normal and Poisson and perform operations such as calculating probability density function (pdf), cumulative distribution function (cdf), quantiles, and sampling. ```kotlin val normal = NormalDistribution(mu = 0.0, sigma = 1.0) normal.pdf(0.0) // 0.3989... normal.cdf(1.96) // 0.975... normal.quantile(0.975) // 1.96 normal.sample(Random(42)) // a single random draw val poisson = PoissonDistribution(rate = 4.0) poisson.pmf(3) // P(X = 3) poisson.cdf(5) // P(X <= 5) poisson.mean // 4.0 ``` -------------------------------- ### Gradle KTS Setup for KMP commonMain Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/installation.mdx This configuration shows how to declare kstats dependencies within the `commonMain` source set of a Kotlin Multiplatform (KMP) project. It utilizes the BOM for version management and lists core kstats modules required for cross-platform compatibility. ```kotlin kotlin { sourceSets { commonMain.dependencies { implementation(project.dependencies.platform("org.oremif:kstats-bom:{{kstats-version}}")) implementation("org.oremif:kstats-core") implementation("org.oremif:kstats-distributions") } } } ``` -------------------------------- ### Gradle KTS Setup with BOM Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/installation.mdx This configuration adds kstats to a Gradle KTS project using the Bill of Materials (BOM). The BOM ensures all included kstats modules are aligned to the same version, simplifying dependency management. It's recommended for projects using multiple kstats modules. ```kotlin dependencies { implementation(platform("org.oremif:kstats-bom:{{kstats-version}}")) implementation("org.oremif:kstats-core") implementation("org.oremif:kstats-distributions") implementation("org.oremif:kstats-hypothesis") implementation("org.oremif:kstats-correlation") implementation("org.oremif:kstats-sampling") } ``` -------------------------------- ### Example Usage of Statistics Pipeline Source: https://github.com/oremif/kstats/blob/master/docs/guides/how-to/building-a-pipeline.mdx Provides a practical example of using the `analyze` function with sample data for control and treatment groups. It demonstrates how to access and interpret the results from the generated AnalysisReport. ```kotlin val pageLoadControl = doubleArrayOf( 1.23, 1.45, 1.31, 1.52, 1.38, 1.41, 1.29, 1.47, 1.35, 1.44, 1.33, 1.50, 1.27, 1.42, 1.36, 1.48, 1.30, 1.46, 1.39, 1.43 ) val pageLoadTreatment = doubleArrayOf( 1.10, 1.25, 1.18, 1.32, 1.15, 1.22, 1.12, 1.28, 1.19, 1.26, 1.14, 1.30, 1.11, 1.24, 1.17, 1.29, 1.13, 1.27, 1.20, 1.23 ) val report = analyze(pageLoadControl, pageLoadTreatment) report.controlSummary.mean report.treatmentSummary.mean report.assumptions.isNormal report.assumptions.isVarianceEqual report.comparison.testName report.comparison.pValue report.comparison.isSignificant report.comparison.confidenceInterval ``` -------------------------------- ### Gradle KTS Setup with Single Module Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/installation.mdx This configuration demonstrates how to add a single kstats module to a Gradle KTS project. It's suitable for projects that only require specific functionality from one module, such as kstats-core. The version is specified directly for the chosen module. ```kotlin dependencies { implementation("org.oremif:kstats-core:{{kstats-version}}") } ``` -------------------------------- ### Data Transformation and Sampling Utilities in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/quickstart.mdx Provides common data preprocessing utilities including ranking, Z-score calculation, and min-max normalization. ```kotlin val data = doubleArrayOf(3.0, 1.0, 4.0, 1.0, 5.0) data.rank() // [3.0, 1.5, 4.0, 1.5, 5.0] data.zScore() // [-0.16, -1.47, 0.49, -1.47, 1.14] data.minMaxNormalize() // [0.5, 0.0, 0.75, 0.0, 1.0] ``` -------------------------------- ### Define and Summarize Data in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/quickstart.mdx Demonstrates how to initialize a dataset and compute descriptive statistics such as mean, median, standard deviation, and skewness using the describe() function. ```kotlin val sample = doubleArrayOf(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0) val stats = sample.describe() stats.mean // 5.0 stats.median // 4.5 stats.standardDeviation // 2.1380 stats.skewness // 0.6563 stats.interquartileRange // 1.5 ``` -------------------------------- ### Fit Probability Distributions in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/quickstart.mdx Creates a normal distribution model based on sample parameters and calculates cumulative distribution functions and quantiles. ```kotlin val normal = NormalDistribution(mu = stats.mean, sigma = stats.standardDeviation) normal.cdf(6.0) // probability that X ≤ 6.0 normal.quantile(0.95) // value below which 95% of the distribution falls ``` -------------------------------- ### Advanced Distribution Modeling in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/quickstart.mdx Demonstrates usage of Normal and Poisson distributions to calculate probability density, cumulative distribution, and probability mass functions. ```kotlin val normal = NormalDistribution(mu = 0.0, sigma = 1.0) normal.pdf(0.0) // 0.3989 normal.cdf(1.96) // 0.9750 normal.quantile(0.975) // 1.9600 val poisson = PoissonDistribution(rate = 3.0) poisson.pmf(5) // 0.1008 poisson.cdf(5) // 0.9161 ``` -------------------------------- ### Execute Hypothesis Testing in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/quickstart.mdx Runs a t-test against a population mean to determine if the sample significantly deviates from the expected value. ```kotlin val result = tTest(sample, mu = 5.0) result.statistic // 0.0 result.pValue // 1.0 result.isSignificant() // false — cannot reject H₀: μ = 5.0 result.confidenceInterval // (3.21, 6.79) ``` -------------------------------- ### StudentTDistribution Example in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Illustrates the StudentTDistribution in Kotlin, known for its heavier tails compared to the normal distribution. It requires the degrees of freedom (df) as a parameter. The example shows instantiation and calculation of mean, CDF, and quantile. ```kotlin val d = StudentTDistribution(degreesOfFreedom = 10.0) d.mean // 0.0 d.cdf(2.228) // ≈ 0.975 d.quantile(0.975) // 2.2281 ``` -------------------------------- ### Basic Usage of kstats for Descriptive Statistics in Kotlin Source: https://github.com/oremif/kstats/blob/master/README.md A quickstart example for using the kstats library to calculate descriptive statistics on a dataset. It shows how to compute the mean, median, standard deviation, and skewness of a double array using extension functions. ```kotlin val data = doubleArrayOf(2.0, 4.0, 4.0, 5.0, 7.0, 9.0) val summary = data.describe() // => DescriptiveStatistics(count=6, mean=5.17, median=4.5, standardDeviation=2.48, ...) data.mean() // => 5.1667 data.standardDeviation() // => 2.4833 data.skewness() // => 0.3942 ``` -------------------------------- ### CauchyDistribution Example in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Demonstrates the CauchyDistribution in Kotlin, characterized by extremely heavy tails and undefined mean and variance. It requires location and scale parameters. The example shows instantiation and calculation of PDF, CDF, and quantile. ```kotlin val d = CauchyDistribution(location = 0.0, scale = 1.0) d.pdf(0.0) // 0.3183 d.cdf(0.0) // 0.5 d.quantile(0.75) // 1.0 ``` -------------------------------- ### Getting Started with Correlation and Regression in Kotlin Source: https://github.com/oremif/kstats/blob/master/kstats-correlation/Module.md Demonstrates basic usage of Pearson correlation and simple linear regression functions. Requires the kstats-correlation library. Inputs are DoubleArrays for x and y, outputs include correlation coefficient, p-value, slope, intercept, R-squared, and a prediction function. ```kotlin val x = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0) val y = doubleArrayOf(2.1, 3.9, 6.2, 7.8, 10.1) val r = pearsonCorrelation(x, y) r.coefficient // 0.999... r.pValue // < 0.001 val reg = simpleLinearRegression(x, y) reg.slope // ~2.0 reg.intercept // ~0.04 reg.rSquared // 0.999... reg.predict(6.0) // predicted y for x = 6 ``` -------------------------------- ### ExponentialDistribution Example in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Shows the ExponentialDistribution in Kotlin, used for modeling the time between events in a Poisson process. It is memoryless and requires a rate parameter. The example demonstrates instantiation and calculation of mean, CDF, and quantile. ```kotlin val d = ExponentialDistribution(rate = 2.0) d.mean // 0.5 d.cdf(1.0) // 0.8647 d.quantile(0.5) // 0.3466 ``` -------------------------------- ### Setup kstats Dependencies (Python) Source: https://github.com/oremif/kstats/blob/master/samples/choosing-a-distribution.ipynb This snippet shows how to set up the kstats project by declaring its dependencies using the %use directive and @file:DependsOn annotations. It ensures that the necessary core, distributions, and hypothesis modules are available for use. ```python %use kandy @file:DependsOn("org.oremif:kstats-core-jvm:0.3.0") @file:DependsOn("org.oremif:kstats-distributions-jvm:0.3.0") @file:DependsOn("org.oremif:kstats-hypothesis-jvm:0.3.0") ``` -------------------------------- ### GammaDistribution Example in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Demonstrates the GammaDistribution in Kotlin, a generalization of the exponential distribution. It models the sum of independent exponential random variables and requires shape and rate parameters. The example shows instantiation and calculation of mean, variance, and CDF. ```kotlin val d = GammaDistribution(shape = 2.0, rate = 0.5) d.mean // 4.0 d.variance // 8.0 d.cdf(4.0) // 0.5940 ``` -------------------------------- ### NormalDistribution Example in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Demonstrates the usage of the NormalDistribution in Kotlin. This distribution models data that clusters symmetrically around a mean. It requires the mean (mu) and standard deviation (sigma) as parameters. The example shows how to instantiate the distribution and calculate its mean, cumulative distribution function (CDF), and quantile. ```kotlin val d = NormalDistribution(mu = 100.0, sigma = 15.0) d.mean // 100.0 d.cdf(115.0) // 0.8413 d.quantile(0.975) // 129.3994 ``` -------------------------------- ### LaplaceDistribution Example in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Illustrates the LaplaceDistribution (double-exponential) in Kotlin, featuring a sharper peak and heavier tails than the normal distribution. It requires location (mu) and scale parameters. The example shows instantiation and calculation of mean, variance, and PDF. ```kotlin val d = LaplaceDistribution(mu = 0.0, scale = 1.0) d.mean // 0.0 d.variance // 2.0 d.pdf(0.0) // 0.5 ``` -------------------------------- ### Install kstats using Gradle (Kotlin) Source: https://context7.com/oremif/kstats/llms.txt Add kstats to your project using Gradle. The recommended approach is to use the Bill of Materials (BOM) for version alignment across modules. You can also add individual modules or specific versions. ```kotlin dependencies { implementation(platform("org.oremif:kstats-bom:0.3.0")) implementation("org.oremif:kstats-core") implementation("org.oremif:kstats-distributions") implementation("org.oremif:kstats-hypothesis") implementation("org.oremif:kstats-correlation") implementation("org.oremif:kstats-sampling") } kotlin { sourceSets { commonMain.dependencies { implementation(project.dependencies.platform("org.oremif:kstats-bom:0.3.0")) implementation("org.oremif:kstats-core") } } } // Single module without BOM dependencies { implementation("org.oremif:kstats-core:0.3.0") } ``` -------------------------------- ### Measure Association and Linear Regression in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/quickstart.mdx Calculates Pearson correlation coefficients and performs simple linear regression to model relationships between two variables. ```kotlin val x = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0) val y = doubleArrayOf(2.1, 3.9, 6.2, 7.8, 10.1) val r = pearsonCorrelation(x, y) r.coefficient // 0.9987 r.pValue // 0.0001 val model = simpleLinearRegression(x, y) model.slope // 1.99 model.rSquared // 0.9973 model.predict(6.0) // 11.99 ``` -------------------------------- ### Visualize Statistical Results Source: https://github.com/oremif/kstats/blob/master/samples/ab-testing.ipynb Provides examples for plotting statistical data, including confidence intervals for mean differences and bar charts comparing p-values on a -log10 scale. These visualizations help in interpreting the significance of experimental outcomes. ```kotlin plot { points { x(listOf(meanDiff)); y(listOf("Mean Difference")); size = 8.0; color = Color.hex("#1971c2") } line { x(listOf(ciLow, ciHigh)); y(listOf("Mean Difference", "Mean Difference")); color = Color.hex("#1971c2"); width = 3.0 } layout { title = "Mean Difference with 95% Confidence Interval"; size = 700 to 300 } } val negLog10 = testPvalues.map { -kotlin.math.ln(it) / kotlin.math.ln(10.0) } plot { bars { x(testNames); y(negLog10); fillColor = Color.hex("#9775fa"); alpha = 0.8 } layout { title = "-log10(p-value) — Higher = More Significant"; size = 800 to 400 } } ``` -------------------------------- ### Perform Normality Testing in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/quickstart.mdx Uses the Shapiro-Wilk test to check if a sample follows a normal distribution, returning a statistic and p-value to determine significance. ```kotlin val normality = shapiroWilkTest(sample) normality.statistic // W statistic normality.pValue // > 0.05 → no evidence against normality normality.isSignificant() // false ``` -------------------------------- ### Performing a One-Sample T-Test in Kotlin Source: https://github.com/oremif/kstats/blob/master/kstats-hypothesis/Module.md Demonstrates how to perform a one-sample t-test using the kstats-hypothesis library. It shows how to obtain the t-statistic, p-value, confidence interval, and check for significance. It also includes an example of performing a Shapiro-Wilk test for normality before selecting a hypothesis test. ```kotlin val sample = doubleArrayOf(5.0, 6.0, 7.0, 5.5, 6.5) val result = tTest(sample, mu = 5.0) result.statistic // t-statistic result.pValue // p-value result.confidenceInterval // 95% CI for the mean result.isSignificant() // true if p < 0.05 // Normality check before choosing a test val sw = shapiroWilkTest(sample) if (!sw.isSignificant()) { /* data is consistent with normality */ } ``` -------------------------------- ### Descriptive Statistics and Online Statistics in Kotlin Source: https://github.com/oremif/kstats/blob/master/README.md Demonstrates calculating descriptive statistics for a dataset and using online statistics for streaming data. It shows how to get count, mean, median, standard deviation, and skewness from a double array. The OnlineStatistics class allows adding data incrementally and calculating statistics on the fly. ```kotlin val data = doubleArrayOf(2.0, 4.0, 4.0, 5.0, 7.0, 9.0) val summary = data.describe() summary.mean // => 5.1667 summary.median // => 4.5 summary.standardDeviation // => 2.4833 val stats = OnlineStatistics() stats.addAll(doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0)) stats.mean // => 3.0 stats.standardDeviation() // => 1.5811 ``` -------------------------------- ### Perform descriptive statistics and hypothesis testing in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/getting-started/introduction.mdx Demonstrates basic usage of the kstats library, including calculating descriptive statistics with describe(), performing a Shapiro-Wilk normality test, and fitting data to a Normal distribution. ```kotlin val sample = doubleArrayOf(2.0, 4.0, 4.0, 5.0, 7.0, 9.0) val summary = sample.describe() summary.mean // 5.1667 summary.standardDeviation // 2.4833 val normality = shapiroWilkTest(sample) normality.pValue // 0.8933 val fitted = NormalDistribution(mu = summary.mean, sigma = summary.standardDeviation) fitted.cdf(6.0) // 0.6335 ``` -------------------------------- ### WeibullDistribution Example in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Illustrates the WeibullDistribution in Kotlin, a flexible distribution used in reliability and survival analysis. It requires shape and scale parameters. The example shows instantiation and calculation of mean and CDF. ```kotlin val d = WeibullDistribution(shape = 1.5, scale = 1.0) d.mean // 0.9027 d.cdf(1.0) // 0.6321 ``` -------------------------------- ### Execute Gradle Build and Test Commands Source: https://github.com/oremif/kstats/blob/master/README.md Provides common Gradle commands for running tests across platforms, building the project, and executing performance benchmarks against Apache Commons Math. ```bash ./gradlew jvmTest # run JVM tests ./gradlew allTests # run all platform tests ./gradlew build # full build ./gradlew :benchmark:benchmark # JMH benchmarks (kstats vs Apache Commons Math) ./gradlew :benchmark:smokeBenchmark # quick smoke run ``` -------------------------------- ### Configure kstats dependencies and imports Source: https://github.com/oremif/kstats/blob/master/samples/exploratory-analysis.ipynb Sets up the necessary kstats modules via dependency injection and imports the required statistical packages for descriptive analysis, distributions, and hypothesis testing. ```kotlin @file:DependsOn("org.oremif:kstats-core-jvm:0.3.0") @file:DependsOn("org.oremif:kstats-distributions-jvm:0.3.0") @file:DependsOn("org.oremif:kstats-hypothesis-jvm:0.3.0") @file:DependsOn("org.oremif:kstats-correlation-jvm:0.3.0") @file:DependsOn("org.oremif:kstats-sampling-jvm:0.3.0") import org.oremif.kstats.descriptive.* import org.oremif.kstats.distributions.* import org.oremif.kstats.hypothesis.* import org.oremif.kstats.correlation.* import org.oremif.kstats.sampling.* ``` -------------------------------- ### Initialize and use ZipfDistribution in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Demonstrates how to instantiate a ZipfDistribution with a specific number of elements and exponent, and how to calculate the probability mass function (PMF) for specific ranks. ```kotlin val d = ZipfDistribution(numberOfElements = 100, exponent = 1.0) d.pmf(1) // probability of rank 1 (the most common) d.pmf(100) // probability of rank 100 (the least common) ``` -------------------------------- ### LogNormalDistribution Example in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Shows the LogNormalDistribution in Kotlin, where the logarithm of the variable is normally distributed, resulting in a positive, right-skewed distribution. It requires the mean (mu) and standard deviation (sigma) of the log. The example demonstrates instantiation and calculation of mean and quantile. ```kotlin val d = LogNormalDistribution(mu = 0.0, sigma = 1.0) d.mean // 1.6487 d.quantile(0.5) // 1.0 ``` -------------------------------- ### Model Symmetric Data with Normal and Student-T Distributions Source: https://github.com/oremif/kstats/blob/master/docs/guides/how-to/choosing-a-distribution.mdx Demonstrates how to model symmetric data using Normal distributions for general cases and Student-T distributions for small-sample scenarios requiring more conservative intervals. ```kotlin val sessionDuration = NormalDistribution(mu = 12.5, sigma = 3.2) sessionDuration.cdf(15.0) // probability of session under 15 min sessionDuration.quantile(0.95) // 95th percentile val smallSampleEstimate = StudentTDistribution(degreesOfFreedom = 8.0) smallSampleEstimate.quantile(0.975) // critical value for 95% CI ``` -------------------------------- ### LogisticDistribution Example in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Shows the LogisticDistribution in Kotlin, which has a shape similar to the normal distribution but with heavier tails and a closed-form CDF. It requires location (mu) and scale parameters. The example demonstrates instantiation and calculation of mean, CDF, and probability density function (PDF). ```kotlin val d = LogisticDistribution(mu = 0.0, scale = 1.0) d.mean // 0.0 d.cdf(0.0) // 0.5 d.pdf(0.0) // 0.25 ``` -------------------------------- ### Initialize statistical modules in kstats Source: https://github.com/oremif/kstats/blob/master/docs/guides/how-to/building-a-pipeline.mdx This snippet demonstrates how to import and structure the core modules of the kstats library. It provides a conceptual entry point for accessing sampling, core summarization, and hypothesis testing functions. ```javascript import { zScore, bootstrapSample } from 'kstats-sampling'; import { describe, mean } from 'kstats-core'; import { tTest } from 'kstats-hypothesis'; const data = [1, 2, 3, 4, 5]; const stats = describe(data); console.log(mean(data)); ``` -------------------------------- ### Execute Analysis Pipeline and Print Report (Kotlin) Source: https://github.com/oremif/kstats/blob/master/samples/building-a-pipeline.ipynb Demonstrates the usage of the `analyze` function with sample page load time data for control and treatment groups. It then prints a formatted analysis report to the console, including means, assumption P-values, test used, and significance. ```kotlin val pageLoadControl = doubleArrayOf( 1.23, 1.45, 1.31, 1.52, 1.38, 1.41, 1.29, 1.47, 1.35, 1.44, 1.33, 1.50, 1.27, 1.42, 1.36, 1.48, 1.30, 1.46, 1.39, 1.43 ) val pageLoadTreatment = doubleArrayOf( 1.10, 1.25, 1.18, 1.32, 1.15, 1.22, 1.12, 1.28, 1.19, 1.26, 1.14, 1.30, 1.11, 1.24, 1.17, 1.29, 1.13, 1.27, 1.20, 1.23 ) val report = analyze(pageLoadControl, pageLoadTreatment) println("=== Analysis Report ===") println("Control mean: ${String.format("%.3f", report.controlSummary.mean)} s") println("Treatment mean: ${String.format("%.3f", report.treatmentSummary.mean)} s") println("Normal: ${report.assumptions.isNormal} (p=${String.format("%.4f", report.assumptions.normalityPValue)})") println("Equal variance: ${report.assumptions.isVarianceEqual} (p=${String.format("%.4f", report.assumptions.varianceEqualityPValue)})") println("Test used: ${report.comparison.testName}") println("p-value: ${String.format("%.6f", report.comparison.pValue)})") println("Significant: ${report.comparison.isSignificant}") println("95% CI: ${report.comparison.confidenceInterval?.let { "[${String.format("%.3f", it.first)}, ${String.format("%.3f", it.second)}]]" } ?: "N/A"}") ``` -------------------------------- ### Initialize performance metric datasets Source: https://github.com/oremif/kstats/blob/master/samples/exploratory-analysis.ipynb Defines arrays for response time, error rates, memory usage, and throughput metrics, along with a range for the 30-day observation period. These datasets serve as the foundation for subsequent statistical modeling and anomaly detection. ```kotlin val responseTimeMs = doubleArrayOf( 89.2, 95.1, 87.6, 102.3, 91.8, 88.4, 96.7, 103.5, 90.1, 94.3, 88.9, 97.2, 105.8, 91.4, 93.6, 87.1, 99.0, 92.5, 96.1, 104.2, 90.7, 88.3, 101.6, 93.9, 95.4, 89.8, 98.3, 106.1, 91.0, 94.7 ) val errorsPerHour = doubleArrayOf( 2.0, 3.0, 1.0, 5.0, 2.0, 1.0, 4.0, 6.0, 2.0, 3.0, 1.0, 4.0, 7.0, 2.0, 3.0, 1.0, 5.0, 2.0, 4.0, 6.0, 2.0, 1.0, 5.0, 3.0, 3.0, 1.0, 4.0, 8.0, 2.0, 3.0 ) val memoryUsageMb = doubleArrayOf( 512.3, 528.1, 505.7, 545.2, 519.6, 508.4, 534.8, 551.3, 515.0, 526.7, 509.2, 537.1, 558.4, 517.8, 524.3, 503.1, 541.6, 520.9, 531.5, 549.7, 514.2, 506.8, 543.9, 522.5, 529.0, 511.4, 539.3, 561.2, 516.3, 527.4 ) val throughputRps = doubleArrayOf( 245.0, 238.0, 251.0, 225.0, 242.0, 249.0, 232.0, 218.0, 244.0, 236.0, 250.0, 230.0, 212.0, 243.0, 237.0, 253.0, 227.0, 241.0, 233.0, 220.0, 246.0, 252.0, 224.0, 239.0, 235.0, 248.0, 228.0, 210.0, 243.0, 234.0 ) val days = (1..30).toList() ``` -------------------------------- ### Generate Bar Chart for Mean Page Load Times (Kotlin) Source: https://github.com/oremif/kstats/blob/master/samples/building-a-pipeline.ipynb Generates a bar chart comparing the mean page load times between the control and treatment groups. This provides a clear visual representation of the average performance for each group. ```kotlin val ciLow = report.comparison.confidenceInterval?.first ?: 0.0 val ciHigh = report.comparison.confidenceInterval?.second ?: 0.0 val meanDiff = report.controlSummary.mean - report.treatmentSummary.mean plot { bars { x(listOf("Control", "Treatment")); y(listOf(report.controlSummary.mean, report.treatmentSummary.mean)) fillColor = Color.hex("#4dabf7") alpha = 0.7 } layout { title = "Mean Page Load Times"; size = 500 to 400 } } ``` -------------------------------- ### Run kstats Benchmarks with Gradle Source: https://github.com/oremif/kstats/blob/master/benchmark/README.md Commands to execute the full benchmark suite or a quick smoke test for kstats. These commands utilize Gradle and are designed for a Kotlin/Java environment. The full run takes approximately 40 minutes, while the smoke test takes about 5 minutes. ```bash # Full benchmark run (~40 min) ./gradlew :benchmark:benchmark # Quick smoke test (~5 min) ./gradlew :benchmark:smokeBenchmark ``` -------------------------------- ### Analyze Poisson Distributions Source: https://github.com/oremif/kstats/blob/master/samples/choosing-a-distribution.ipynb Models event counts per interval using the Poisson distribution. Includes examples for calculating PMF, CDF, and visualizing the distribution as a bar chart. ```kotlin val errorsPerHour = PoissonDistribution(rate = 3.2) println("P(0 errors): ${errorsPerHour.pmf(0)}") println("P(<=5 errors): ${errorsPerHour.cdf(5)}") println("99th percentile: ${errorsPerHour.quantileInt(0.99)} errors") val kValues = (0..12).toList() val pmfValues = kValues.map { errorsPerHour.pmf(it) } plot { bars { x(kValues); y(pmfValues) fillColor = Color.hex("#9775fa") alpha = 0.8 } layout { title = "Poisson PMF — Errors per Hour (lambda=3.2)" size = 800 to 400 } } ``` -------------------------------- ### Initialize and use LogarithmicDistribution in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/distributions/overview.mdx Shows the initialization of a LogarithmicDistribution using a probability parameter and accessing its mean and PMF values. ```kotlin val d = LogarithmicDistribution(probability = 0.5) d.mean // 1.4427 d.pmf(1) // 0.7213 d.pmf(2) // 0.1803 ``` -------------------------------- ### T-Test for Hypothesis Testing in Kotlin Source: https://github.com/oremif/kstats/blob/master/README.md Shows how to perform a one-sample t-test using the kstats library. This example calculates the test statistic, p-value, and determines if the result is statistically significant at a given alpha level. ```kotlin val sample = doubleArrayOf(2.0, 4.0, 4.0, 5.0, 7.0, 9.0) val result = tTest(sample, mu = 5.0) result.statistic // => 0.1644 result.pValue // => 0.8759 result.isSignificant(alpha = 0.05) // => false ``` -------------------------------- ### Chi-Squared Goodness-of-Fit Tests in Kotlin Source: https://github.com/oremif/kstats/blob/master/samples/testing-assumptions.ipynb Performs Chi-Squared goodness-of-fit tests. The first example tests for uniformity against a uniform distribution, while the second tests against a specific set of expected counts. Dependencies include the `org.jetbrains.kotlinx.statistics` library. ```kotlin val observedDefects = intArrayOf(12, 18, 25, 15, 30) val uniform = chiSquaredTest(observedDefects) println("Uniform test p=${String.format("%.4f", uniform.pValue)}") val expectedCounts = doubleArrayOf(20.0, 20.0, 20.0, 20.0, 20.0) val specific = chiSquaredTest(observedDefects, expectedCounts) println("Specific expected p=${String.format("%.4f", specific.pValue)}") ``` -------------------------------- ### Visualize Mean Difference and Confidence Interval (Kotlin) Source: https://github.com/oremif/kstats/blob/master/samples/building-a-pipeline.ipynb Visualizes the difference between the mean page load times of the control and treatment groups, along with its confidence interval. This plot helps in understanding the magnitude and uncertainty of the observed difference. ```kotlin plot { points { x(listOf(meanDiff)); y(listOf("Difference")) size = 8.0 color = Color.hex("#1971c2") } line { x(listOf(ciLow, ciHigh)); y(listOf("Difference", "Difference")) color = Color.hex("#1971c2") } } ``` -------------------------------- ### Generate Density Plot for Group Comparisons (Kotlin) Source: https://github.com/oremif/kstats/blob/master/samples/building-a-pipeline.ipynb Creates a density plot visualizing the distribution of page load times for both control and treatment groups. This plot helps in visually assessing the distributions and potential differences between the groups. ```kotlin plot { densityPlot(pageLoadControl.toList()) { fillColor = Color.hex("#4dabf7") alpha = 0.4 } densityPlot(pageLoadTreatment.toList()) { fillColor = Color.hex("#ff8787") alpha = 0.4 } layout { title = "Page Load Times: Control (blue) vs Treatment (red)"; size = 800 to 400 } } ``` -------------------------------- ### Percentile-Based Anomaly Detection - Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/guides/how-to/quality-control.mdx Detects anomalies by identifying data points that fall outside specified percentiles. This example flags readings below the 1st percentile or above the 99th percentile, providing a robust method for outlier detection that is less sensitive to extreme values than Z-scores. ```kotlin val lowerBound = sensorReadings.quantile(0.01) val upperBound = sensorReadings.quantile(0.99) val outliers = sensorReadings.filter { it < lowerBound || it > upperBound } ``` -------------------------------- ### Estimate Proportions and Rates with Beta Distribution Source: https://github.com/oremif/kstats/blob/master/docs/guides/how-to/choosing-a-distribution.mdx Calculates point estimates and credible intervals for proportions like click-through rates. It uses the Beta distribution, which is ideal for modeling probabilities based on observed successes and failures. ```kotlin val ctr = BetaDistribution(alpha = 120.0, beta = 3880.0) ctr.mean // point estimate of CTR ctr.quantile(0.025) // lower bound of 95% credible interval ctr.quantile(0.975) // upper bound ctr.cdf(0.035) // probability that true CTR is below 3.5% ``` -------------------------------- ### Model Fixed Trials with BinomialDistribution Source: https://github.com/oremif/kstats/blob/master/docs/guides/how-to/choosing-a-distribution.mdx Models the number of successes in a fixed number of independent trials, such as conversion rates from page views. ```kotlin val conversions = BinomialDistribution(trials = 1000, probability = 0.035) conversions.mean // expected number of conversions conversions.pmf(40) // probability of exactly 40 conversions conversions.sf(50) // probability of more than 50 conversions ``` -------------------------------- ### Create Bins and Frequency Tables in Kotlin Source: https://context7.com/oremif/kstats/llms.txt Groups numeric data into intervals based on bin count or width. Provides frequency tables including counts, relative frequencies, and cumulative frequencies. ```kotlin val data = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) // By bin count val bins = data.asIterable().bin(3) bins.size // 3 bins[0].range // interval of the first bin bins[0].items // values that fall in the first bin bins[0].count // number of values // By bin width val wideBins = data.asIterable().bin(5.0) // Frequency table — counts and proportions val freq = data.asIterable().frequencyTable(3) freq[0].count // number of values in the first bin freq[0].relativeFrequency // proportion of total freq[0].cumulativeFrequency // running total of relative frequencies ``` -------------------------------- ### Compute descriptive statistics in Kotlin Source: https://github.com/oremif/kstats/blob/master/kstats-core/Module.md Demonstrates how to calculate descriptive statistics using extension functions on DoubleArray and how to perform memory-efficient streaming calculations using the OnlineStatistics class. ```kotlin val data = doubleArrayOf(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0) val stats = data.describe() stats.mean // 5.0 stats.standardDeviation // 2.0 stats.median // 4.5 stats.skewness // 0.656... // Streaming computation — no need to hold all data in memory val online = OnlineStatistics() online.addAll(data) online.mean // 5.0 online.variance() // 4.571... ``` -------------------------------- ### Configure kstats Dependencies Source: https://github.com/oremif/kstats/blob/master/samples/ab-testing.ipynb Defines the necessary library dependencies for kstats core, hypothesis testing, and correlation modules using Kotlin script syntax. ```kotlin @file:DependsOn("org.oremif:kstats-core-jvm:0.3.0") @file:DependsOn("org.oremif:kstats-hypothesis-jvm:0.3.0") @file:DependsOn("org.oremif:kstats-correlation-jvm:0.3.0") ``` -------------------------------- ### Calculate Quantiles and Percentiles in Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/core/overview.mdx Demonstrates how to compute quantiles and percentiles from a double array. It includes support for specific probability thresholds and batch extraction of quartiles. ```kotlin val data = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) data.quantile(0.5) // 5.5 (median) data.quantile(0.25) // 3.25 (Q1) data.percentile(90.0) // 9.1 (90th percentile) val (q1, median, q3) = data.quartiles() // q1 = 3.25, median = 5.5, q3 = 7.75 ``` -------------------------------- ### Compare Batch Distributions via Density Plots Source: https://github.com/oremif/kstats/blob/master/samples/testing-assumptions.ipynb Creates a multi-layered density plot to visualize the spread and overlap of data distributions for three different batches. Useful for exploratory data analysis. ```kotlin plot { densityPlot(batchA.toList()) { fillColor = Color.hex("#4dabf7") alpha = 0.3 } densityPlot(batchB.toList()) { fillColor = Color.hex("#ff8787") alpha = 0.3 } densityPlot(batchC.toList()) { fillColor = Color.hex("#69db7c") alpha = 0.3 } layout { title = "Batch A (blue) / B (red) / C (green) — Visual Spread Comparison"; size = 800 to 400 } } ``` -------------------------------- ### Generate Full Analysis Report Source: https://github.com/oremif/kstats/blob/master/docs/guides/how-to/building-a-pipeline.mdx Orchestrates the statistical analysis by first checking assumptions and then comparing groups. It returns a comprehensive AnalysisReport containing descriptive statistics for both groups, assumption check results, and the group comparison outcome. ```kotlin fun analyze( control: DoubleArray, treatment: DoubleArray, alpha: Double = 0.05 ): AnalysisReport { val assumptions = checkAssumptions(control, treatment, alpha) val comparison = compareGroups(control, treatment, assumptions, alpha) return AnalysisReport( controlSummary = control.describe(), treatmentSummary = treatment.describe(), assumptions = assumptions, comparison = comparison ) } ``` -------------------------------- ### Perform Weighted Random Sampling with Kotlin Source: https://github.com/oremif/kstats/blob/master/docs/sampling/overview.mdx Demonstrates the use of WeightedCoin for binary outcomes and WeightedDice for multi-outcome selection. The library automatically normalizes weights, allowing for flexible input values. ```kotlin val coin = WeightedCoin(probability = 0.7) coin.flip() // true with 70% probability val dice = WeightedDice(mapOf("A" to 3.0, "B" to 1.0)) dice.roll() // "A" with 75% probability, "B" with 25% ``` -------------------------------- ### Verify Distribution Fit with Kolmogorov-Smirnov Test Source: https://github.com/oremif/kstats/blob/master/docs/guides/how-to/choosing-a-distribution.mdx Compares observed data against a fitted distribution using the Kolmogorov-Smirnov test. It evaluates the goodness-of-fit by analyzing the KS statistic and p-value to determine if the data contradicts the chosen distribution. ```kotlin val processingTimesMs = doubleArrayOf( 45.2, 51.8, 48.1, 52.3, 47.6, 49.9, 53.1, 46.5, 50.7, 48.8, 51.2, 47.3, 49.1, 52.8, 46.9, 50.3, 48.5, 51.6, 47.8, 49.4 ) val fitted = NormalDistribution( mu = processingTimesMs.mean(), sigma = processingTimesMs.standardDeviation() ) val ks = kolmogorovSmirnovTest(processingTimesMs, fitted) ks.statistic // KS statistic — smaller means better fit ks.pValue // high p-value means data does not contradict the distribution ``` -------------------------------- ### Perform Statistical Operations and Weighted Sampling in Kotlin Source: https://github.com/oremif/kstats/blob/master/kstats-sampling/Module.md Demonstrates basic usage of kstats-sampling, including array ranking, z-score standardization, min-max normalization, and weighted categorical sampling using WeightedDice. ```kotlin val data = doubleArrayOf(3.0, 1.0, 4.0, 1.0, 5.0) data.rank() // [3.0, 1.5, 4.0, 1.5, 5.0] (average ties) data.zScore() // standardized to mean=0, sd=1 data.minMaxNormalize() // scaled to [0.0, 1.0] val die = WeightedDice(mapOf("A" to 0.7, "B" to 0.2, "C" to 0.1), Random(42)) die.roll() // "A" (most likely) ``` -------------------------------- ### Summarize Statistical Data Source: https://github.com/oremif/kstats/blob/master/samples/ab-testing.ipynb Calculates descriptive statistics for two groups of data and prints the mean, standard deviation, and difference between them. ```kotlin val controlSummary = controlDurationSec.describe() val treatmentSummary = treatmentDurationSec.describe() println("Control — mean: %.1f s, sd: %.1f".format(controlSummary.mean, controlSummary.standardDeviation)) println("Treatment — mean: %.1f s, sd: %.1f".format(treatmentSummary.mean, treatmentSummary.standardDeviation)) println("Difference: %.1f s".format(controlSummary.mean - treatmentSummary.mean)) ```