Elamur Research

powerlaw: A Python Package for Analysis of Heavy-Tailed Distributions

Paper · 2014 · Jeff Alstott, Edward Thomas Bullmore and Dietmar Plenz

Summary

How far into the range of observations does a power law hold, and what else could account for the same pattern? Those questions arise when some observations are much larger than most, as with the frequency of common words, the number of connections of highly connected neurons, or the populations affected by major electricity blackouts. A power law describes how probability decreases with size. Its tail can retain appreciable probability at large sizes, but so can the tails of other distributions. The authors introduce powerlaw, a Python package that brings together the calculations needed to decide where to fit a distribution, estimate its parameters, and assess it alongside alternatives.

The package connects the original observations, the range used for fitting, and the distributions evaluated over that range. It supports cumulative plots and density plots, continuous and integer-valued data, user-supplied upper limits, and restrictions on the fitted parameters or their uncertainty. By default, it searches for the lower boundary of a power-law fit using the Kolmogorov–Smirnov distance, which measures the largest gap between observed and fitted cumulative probabilities. The electricity-blackout example shows how much that choice can matter. Beginning at the automatically selected boundary of 230.000 gives an exponent of 2.273 and a distance of 0.061. Beginning at the fixed boundary of 1.0 gives an exponent of 1.220 and a distance of 0.376. The smaller distance describes agreement over the selected tail. It leaves the behavior of the smaller blackouts open.

Comparisons with other distributions qualify what a tail fit can establish. In the C. elegans neuronal data, the power law is favored over an exponential, with a log-likelihood ratio of 16.384 and a significance value of 0.024. A comparison with an exponentially truncated power law leaves open whether the decline steepens at large connection counts. The word frequencies of Moby Dick, an example in the tradition of Zipf’s law, give a log-likelihood ratio of 0.928 for the power law against the lognormal, with a significance value of 0.426. The data leave those candidates unresolved. For the blackout tail, the comparison with an exponential also remains inconclusive, despite a likelihood ratio whose sign favors the power law.

The examples show why the authors give separate roles to visualization, fitting, and comparison. Plots reveal features of the observations, a fitted curve describes an admitted range, and a statistical comparison evaluates specified rivals on the same observations. The package makes these steps easier to carry out together. The evidential decisions still depend on how the data were collected, whether observations can reasonably be treated as independent, and which processes might have generated them. When plausible processes yield distributions that the available data cannot distinguish, the authors argue that an experiment aimed at the processes themselves can answer a question that further fitting leaves open.

Deep dive: powerlaw: A Python Package for Analysis of Heavy-Tailed Distributions

The powerlaw Python package fits heavy-tailed data, finds where power-law scaling begins, and tests it against competing distributions. · about 36 minutes to read

The problem and its context

What a heavy tail changes

A distribution describes how the chances of observing different values are spread across a range. In the examples that motivate the paper, the right side of that range contains the unusually large observations. An electricity failure can affect many more people than a typical event in the same record. A word can occur much more frequently than most words in a novel. The label heavy-tailed concerns the rate at which the probability of such large outcomes falls away. The paper uses the absence of an exponential bound as the usual quantitative basis for that label. The distinction matters because a distribution can look broad over the available observations while still declining exponentially in its far tail.

Power laws are of special interest because the same exponent governs the decline throughout the range where the law applies. That relationship is the basis for the paper’s description of scale-free behavior. Within the ideal unbounded form, the large values can carry enough weight to make the theoretical standard deviation or even the theoretical mean undefined at the exponents the authors discuss. A collection of measurements can still have an ordinary sample average. The distinction concerns what the proposed distribution implies about the underlying process, especially about outcomes at scales that the observations cover sparsely.

The authors point to work in astrophysics, linguistics, and neuroscience. The statistical task travels across these fields, but the interpretation of a fitted range travels less easily. In one setting the variable may be an integer count. In another the relevant range may end at a physical ceiling. A recording from part of a larger system may impose a ceiling of its own. And observations that enter a dataset as separate values may still be linked by the way the system works or by where they were measured. A fitting procedure can accommodate some of these distinctions only after someone with knowledge of the data has made them explicit.

The range also matters at its lower end. A researcher may have a reason to expect the power law to describe larger observations while smaller observations follow a different pattern. In that case the exponent is an answer about the tail. It need not describe the common events that make up the rest of the distribution. A method for locating the start of the tail therefore has a substantive effect on the claim, even when the data and the family of curves are already agreed upon. Two fits to the same dataset can address different populations of observations simply because they begin at different values.

The fitting methods already existed

The authors build on earlier work by Clauset, Shalizi, and Newman, and on statistical analyses by Klaus, Yu, and Plenz. They credit this line of work with procedures for estimating power-law parameters and evaluating the fits. The lower-bound search is one example. It turns a choice that might otherwise be made by inspecting a plot into a search that compares explicit discrepancies. Earlier research also supplied methods for likelihood-based comparisons and for assessing an individual fit with simulated samples. Powerlaw takes these procedures as its starting point.

Freely available implementations existed as well, including plfit and code that earlier researchers shared with the authors. The paper describes those implementations as important starting material. Its argument for a new package concerns the amount of work needed to put the operations together and the range of cases the resulting workflow can handle. An analyst might need to change the lower boundary, switch from continuous values to counts, or compare the power law with a distribution whose parameters require a different numerical search. If those tasks are carried out by separate routines with different conventions, the analyst has to maintain the common dataset, fitting range, and settings across the whole analysis.

Powerlaw addresses that implementation problem by giving the dataset and its fitted distributions a common interface. The authors treat breadth and extensibility as part of the statistical design. An interface that makes the exponential easy to fit but makes another credible alternative costly to implement could shape which comparisons are attempted. Similarly, a continuous-only routine leaves the user to solve the normalization problem for counts elsewhere. The paper’s software contribution is to make such changes ordinary parts of an analysis and to organize the implementation so that other candidate distributions can be added.

Why there are two questions about fit

An individual goodness-of-fit test asks whether discrepancies of the observed size could plausibly arise from a fitted distribution. The paper describes a bootstrap approach that uses the Kolmogorov–Smirnov distance for this purpose. A bootstrap calibration assesses the observed discrepancy against the discrepancies obtained from simulated data. The resulting significance calculation refers to the candidate being tested. A candidate can be compatible with the observations by this criterion even when an alternative gives those observations higher likelihood.

A comparative test asks how the same observations fare under two fitted candidates. Here the likelihoods provide a common basis for asking which curve assigns greater probability mass or density to the observed values. Such a comparison can distinguish between candidates that both appear reasonable in a plot. It can also leave their relative merits unresolved. Its answer concerns the candidates that enter the calculation, whereas the individual goodness-of-fit question concerns the size of the discrepancy from a particular distribution.

The authors favor comparisons for practical and scientific reasons. Likelihood comparisons require less computation than the bootstrap procedure they discuss. They can also be closer to the question of interest when the goal is to find a useful statistical description of an imperfect empirical system. With enough observations, subtle departures from an ideal curve can become detectable, even if the curve describes much of the behavior that motivated the analysis. Conversely, when observations are scarce, an individual test may have little ability to discriminate. The paper’s approach is to compare serious candidates and use the domain to decide what makes each candidate serious.

The method, step by step

Define the measurement and its range

The input is a collection of observed values. For the neuron example, a value describes the number of connections associated with a neuron. For the word-frequency example, it describes a word’s frequency in the novel. The package works with those numerical observations after they have been assembled. Its settings concern the numerical variable and the way it was observed, so it matters whether a value denotes a count, whether values beyond a ceiling were possible, and whether the units behind separate observations can be treated as independent.

The package’s main object, Fit, holds the dataset and the settings shared across its candidate distributions. A Distribution object represents a fitted family over the relevant range. The power law plays a special role at initialization because it supplies the default lower-bound search. Other families can be fitted when requested, and their parameter estimates are then available through the same surrounding object. The paper also describes a functional interface for operations such as plotting and constructs distributions directly when it needs a specified probability law for simulation.

Fitting and assessing a candidate power-law tail

The steps in order.

Fitting and assessing a candidate power-law tailStep 1: Identify observation type and collection bounds1. Identify observation type and collection boundsStep 2: Inspect density and cumulative displays2. Inspect density and cumulative displaysStep 3: Set or search the lower fitting boundary3. Set or search the lower fitting boundaryStep 4: Estimate parameters over the admitted range4. Estimate parameters over the admitted rangeStep 5: Fit plausible alternatives over that range5. Fit plausible alternatives over that rangeStep 6: Compare likelihoods and inspect fit diagnostics6. Compare likelihoods and inspect fit diagnostics

The order describes the logic of the analysis. Within the automatic boundary search, parameter fitting and range selection are interleaved. The program needs an estimated distribution for each candidate starting point before it can judge how well the curve follows the retained observations. The choice of alternative families has a different source. It follows from what the question and the setting make plausible, even when the computation is performed only after the power-law fit is available.

Read the power law as a probability statement

The paper starts from the proportional form of the power law.

p(x) ∝ x^(−α)

Here x is a possible value of the measured quantity, p(x) is its probability mass in the discrete case or its probability density in the continuous case, and α is the exponent. The caret indicates exponentiation, and the minus sign makes the exponent of x negative for positive α. The proportionality sign indicates that the expression gives the relative weights of different values. A normalization constant scales those weights so that total probability over the admitted range is unity.

The range of the distribution is part of that statement. The paper writes the lower boundary as x_min and an upper boundary, where one is supplied, as x_max. Since the power law is undefined at zero, even a fit intended to span all the positive observations needs a starting point. That point might come from theory, from a threshold below which readings are dominated by noise, or from the lowest value in the data. A boundary found by searching for agreement has a different justification from one imposed by any of those considerations.

The exponent gives the curve its shape. With a larger exponent, the relative weight given to very large values declines more quickly. For the ideal power law with its tail unbounded above, the authors give the following condition under which the theoretical standard deviation can be undefined.

α < 3

The α in this inequality is the power-law exponent, and the less-than sign gives the condition stated in the paper. The condition concerns a property of the theoretical distribution. Whether a finite set of observations has a computable sample standard deviation is a separate matter.

The paper also gives a condition for the theoretical mean to be undefined.

α < 2

Again, α denotes the exponent, and the inequality specifies the range cited by the authors. In this part of the paper, the behavior at arbitrarily large values is what makes the existence of these quantities consequential. A finite upper boundary changes the setting for that argument.

Look at the data using complementary displays

A density plot shows how observations are distributed locally over the measurement range. Constructing an empirical density requires grouping values into intervals and accounting for the widths of those intervals. Equal-width bins preserve a consistent resolution in the original measurement units, but can leave the large-value region fragmented into intervals containing very few observations. Some of the intervals can be empty, as the blackout illustration makes particularly clear.

Powerlaw defaults to logarithmically spaced bins for the density display. The bins cover increasingly wide intervals as the values grow. A wider interval can pool sparsely observed values in the tail so that the local density is easier to see. Normalizing for bin width matters here because a wider interval can contain more observations simply by covering more of the measurement range. The choice changes the display of the empirical distribution. The fitting procedure described in the paper operates on the data in the selected range.

A cumulative display asks how much probability lies on one side of a threshold. The paper writes the cumulative distribution function, or CDF, with a strict inequality.

CDF(x) = p(X < x)

Here X denotes the random quantity, x is the threshold, and p(X < x) is the probability of a value below that threshold. CDF(x) names the cumulative distribution function evaluated there. The strict inequality specifies which side includes a value exactly at the threshold, a relevant convention for integer data.

The complementary cumulative distribution function, or CCDF, uses the other side of the same division.

CCDF(x) = p(X ≥ x)

CCDF(x) is the survival probability at x. The symbol ≥ includes observations equal to the threshold as well as those greater than it. The quantity X and probability notation p have the same meanings as in the CDF. For a heavy tail, this display directly shows how much observed or fitted probability remains as the threshold moves to larger values.

Neither cumulative representation requires constructing histogram bins. Their accumulation of probability is helpful when the analyst wants to see the overall decay. It can also smooth over a local peak that is easier to recognize in a density display. The power-law CCDF ordinarily has a shallower log-log slope than the density, as the paper illustrates. Its decay exponent in the power-law scaling relation discussed there is given by the following expression.

α − 1

Here α is the exponent of the density’s power-law form and 1 is the amount subtracted to obtain the cumulative decay exponent. This relationship helps explain the difference in visual slope. A finite upper endpoint changes the shape of the cumulative curve near that endpoint.

The software can return the numerical values behind the displays. A Fit object can furnish the bin edges and empirical density values, or the sorted values and cumulative probabilities. A constituent Distribution can evaluate its theoretical probabilities at supplied values or over the fitted data when no values are supplied. This allows the empirical and fitted curves to share axes and makes it possible to inspect specific parts of their agreement. By default the empirical plots attached to a fit use its admitted range. An option also makes the original observations available for display, so the region the software fit can be seen in the context of the whole dataset.

Search for the start of scaling

The default lower-bound procedure considers candidate values among the distinct observations. For a given candidate, it retains the values at or above that point, subject to any specified upper bound. It estimates the power law on those values and measures the discrepancy between the fitted and empirical cumulative distributions. The process is repeated across the candidates. Repeated observations matter in the fit, while identical values provide the same proposed boundary and need only be considered once as a starting point.

The default discrepancy is the Kolmogorov–Smirnov distance, denoted D. At each threshold it compares the cumulative probability implied by the fitted distribution with the cumulative proportion in the observations. The largest absolute gap is the distance for that fit. The search chooses the candidate with the smallest distance. Its result specifies both the exponent and the range over which the distance and exponent describe the data.

A fixed lower boundary removes this search. The analyst can also restrict the search to an interval, leaving the choice within that interval to the distance criterion. These options encode different kinds of evidence. A given boundary expresses a decision about when the fitted description should begin. A restricted interval specifies where possible starts are admissible. A search across the observed range uses empirical agreement as the default criterion, subject to the other fit settings.

The distinction between estimating the exponent and locating the boundary becomes important when the configuration changes. By default the exponent at a given boundary is found by maximum likelihood. The distance then ranks the resulting fits across boundaries. The package also offers a minimum-distance method for estimating parameters and other distances for ranking starting points. An analysis can therefore change the parameter-fitting objective, the boundary-selection criterion, or both. The fact that the default uses distance to choose a boundary does not mean that distance was used to estimate every candidate exponent.

The package retains the candidate starts, distances, exponents, and standard errors from the search. That record helps when the distance has more than one low region. Nearby values within one region can give a picture of how stable the fit is around a chosen start. A low region farther away can represent a substantially different account of the tail. The default objective can choose between them, while the retained values show what the decision cost in terms of other properties, such as uncertainty in the exponent.

Treat an upper boundary as information about observation

An upper boundary can come from the physics of the quantity or the design of the observation. The paper illustrates the physical case with a bound on speeds. It illustrates the observational case with a recording from a patch of cortex. An event larger than the patch could occur in the larger system without appearing at that size in the measurements from the patch. In that situation, the upper boundary describes what the observation could capture.

Powerlaw takes an upper boundary from the user and leaves higher observations out of the fit. The distributions attached to that fit are defined within the specified range. A theoretical evaluation within a narrower part of the range is possible when the relevant values are passed to the distribution. This distinguishes the admitted fitting range from both the original data and the portion of a curve a particular plot may show.

A declared upper endpoint affects the representations differently. As the threshold approaches that endpoint, the survival curve loses the probability that would otherwise lie farther out and bends down on logarithmic axes. The density of the power law can remain straight on those axes through the bounded range. The word-frequency figure with and without an upper limit illustrates this difference in cumulative appearance. In a system where the bound comes from the observation window, the authors suggest varying the window experimentally and examining whether the scaling persists under the changed boundary.

Fit the appropriate form for counts or continuous values

For a fixed lower boundary, the continuous power-law exponent can be estimated analytically by maximum likelihood. The likelihood expresses how much probability density the proposed distribution gives the observed values. Choosing the parameters that maximize it is the default parameter-fitting operation. The paper reports the fitted exponent as alpha and its standard error as sigma. The latter describes uncertainty in the exponent estimate and can be used in deciding which fits to admit.

For integer observations, the distribution assigns probability mass to individual integers, and the normalization is over those allowed values. The package treats data as continuous unless the discrete setting is selected. The authors emphasize using the discrete form where the observations call for it. In this case the exact maximum-likelihood calculation for the power law requires numerical optimization. Since an automatic range search may repeat that operation many times, the software offers a faster analytic approximation to the exponent.

For fitting the discrete exponent without an upper limit, the authors report from earlier work that the approximation can be accurate to about 1% or better under the following condition.

x_min ≥ 6

x_min is the lower endpoint of the discrete fit, and ≥ includes a boundary equal to 6. This is a condition for the exponent approximation described in the paper. The approximation is available as the default estimation option for discrete power laws, with numerical optimization available when it is turned off.

Other discrete families present a different computational question. For the lognormal and the stretched exponential, the paper describes constructing an approximation to discrete probability mass from the continuous form. One procedure evaluates the continuous form at each integer from the lower limit through a finite upper limit, and divides the resulting values by their sum. The analyst can specify the upper limit for that normalization or use the upper bound associated with the fit. The choice determines the interval whose weights contribute to the sum.

The alternative procedure takes the probability of all continuous outcomes that would round to a given integer. The interval can be written as follows.

x − 0.5 ≤ t ≤ x + 0.5

x is the integer whose mass is being assigned, and t represents a value under the continuous distribution. Subtracting and adding 0.5 gives the endpoints of the rounding interval. The paired inequalities put t between those endpoints. The mass for x comes from the continuous probability across that interval. The paper gives rounding as the default because it is faster than evaluating and normalizing the weights over a long finite series of integers.

Set admissibility conditions and check the returned state

The distribution families have built-in parameter restrictions. The power-law and exponential examples illustrate restrictions on the exponent and the rate, respectively.

α > 1

α denotes the power-law exponent, and the greater-than sign expresses the default restriction described for the power-law family. The 1 is the lower boundary of that parameter restriction. It applies to the exponent, rather than to the observed values.

λ > 0

λ denotes the exponential rate parameter, and 0 is the boundary below which or at which the package’s default restriction excludes that rate. The condition is on the exponential’s parameters. A bound on the observations, in contrast, specifies which values the distribution is fitted to.

The analyst can supply additional restrictions in several ways. A threshold on the standard error screens the lower-bound candidates by the precision of their corresponding exponent estimates. A parameter range restricts which parameter values can be considered for a particular boundary. The package can also evaluate a function supplied by the analyst, which allows the criterion to depend on a relationship between parameters. The paper’s example uses relative uncertainty.

σ / α < .05

Here σ is the standard error of the exponent α, and the slash denotes division. The inequality admits a fit only if that relative standard error falls below .05. When such a power-law restriction is relevant to the lower-bound search, it is included when the Fit object is initialized. Restrictions on another constituent distribution can be applied when fitting that candidate.

A return value must be read with its status. When none of the possible boundaries meets a specified standard-error threshold, the behavior illustrated in the paper is to return the best boundary without the threshold and set noise_flag. Numerical searches for other constrained distributions can fail for a different reason. If the starting parameters are too far from the feasible region, the search may return its initial guess and set the flag. The paper shows how starting from supplied parameters in the permitted region can allow the constrained search to succeed.

Compare candidates on the same observations

Once the fitting range is set, the researcher can compare the power law with other fitted families. The exponential gives a basic comparison because its tail falls off exponentially. The paper also discusses the lognormal, the stretched exponential or Weibull, and the exponentially truncated power law. The truncated form can follow power-law scaling over some range and then taper more steeply. This gradual taper is a property of the candidate distribution itself. A user-supplied upper limit instead defines the extent of the fitted range.

The log-likelihood ratio compares the likelihood of the first fitted distribution with that of the second. Its sign gives the direction of the comparison. A positive value favors the first candidate in the call, while a negative value favors the second. Reversing the order would reverse what a positive sign means. The accompanying significance value, p, addresses the strength of the evidence for the direction. An estimate can tilt toward one candidate while the evidence leaves the comparison open.

The authors give an optional normalization of the ratio in the following form.

R / (σ√n)

R denotes the raw log-likelihood ratio, n is the count of observations in the comparison, and √n is its square root. In this calculation, σ is the standard deviation of the individual log-likelihood differences used to scale the ratio. This use of σ is distinct from the power-law exponent’s standard error and from the parameter called sigma in a lognormal fit. The normalized quantity is the statistic used in obtaining the significance value in the comparison described by the authors.

Some pairs require a different significance calculation because one family is contained within the other. The paper calls these nested distributions. For example, the truncated power law provides the extra freedom of a taper, and the power law is the corresponding simpler case. The authors also give the exponential and stretched exponential as a nested pair. Powerlaw can recognize nesting using the candidate names or accept a declaration from the analyst. The correction concerns how the likelihood improvement is interpreted when the broader family can express the simpler one.

The paper connects candidate choice to hypotheses about how the data arose. In the neuronal case, preferential attachment would allow already highly connected neurons to acquire connections more readily. That gives the power law a possible rationale. The organism’s finite network gives a rationale for considering a taper as well. A lognormal can be motivated when positive quantities accumulate through multiplication. Such arguments identify comparisons worth making. The output of a comparison describes the fitted distributions, while the proposed mechanisms give those comparisons their scientific purpose.

Generate data when the generating distribution is known

A distribution can also be used to draw synthetic observations. It can come from an empirical fit or be created with chosen parameters. In the latter case the researcher knows the parameters that produced the sample, fits the generated observations, and checks what the procedure recovers. The paper uses this method to examine recovery of the exponent and the lower boundary for both continuous and discrete power laws.

Drawing from a discrete power law presents its own speed and accuracy tradeoff. The software offers a fast approximate generator and a slower exact search. By default it can inherit the estimation choice associated with the generating distribution, and the generation call can override it. The shared option name links the controls in the interface, while the numerical accuracy of sampling and the numerical accuracy of exponent estimation have separate conditions. For the other discrete families discussed in the paper, random generation uses the slower exact-search approach.

The authors make the source available and identify the particular version used for the article’s examples in the supporting file Code S1. They also provide the figure code in Code S2 and in notebook form in Code S3. The distribution implementations are subclasses of a common Distribution class, allowing an added family to take part in the same general workflow. The paper identifies NumPy, SciPy, and matplotlib among the dependencies, and describes a specific use of mpmath for gamma-function evaluations needed by certain distributions.

Experiments and results

The examples answer different statistical questions

The paper illustrates the workflow with word frequencies from Herman Melville’s Moby Dick, numbers of connections per neuron in C. elegans, and populations affected by United States electricity blackouts between 1984 and 2002. The authors introduce the datasets in this order as examples of strong, intermediate, and weak apparent agreement with a power law. That ordering frames the illustrations. The actual tests concern particular alternatives and can remain inconclusive even in the dataset that looks most like a power law.

The empirical demonstrations fit observed values over selected ranges. The package is being examined as an analysis procedure, with reference points supplied by different boundary choices, competing distribution families, and alternative numerical calculations. The main quantitative outputs are the Kolmogorov–Smirnov distance, the exponent and its standard error, and the log-likelihood ratio with its associated significance value. The simulation study has a different reference point: the parameters chosen to generate the observations.

The opening figure shows density displays using equal-width and logarithmically spaced bins, power-law curves over different ranges, and exponential comparisons over the range selected for the power law. The blackout data bring out the visual effect of pooling over wider intervals in a sparse portion of the distribution. The wider bins make a tail pattern easier to inspect. The quantitative case for that pattern still comes from fitting the observations and comparing candidate distributions on the relevant range.

Blackouts show how the chosen range changes the fit

For the blackout observations, the default search chooses a lower boundary of 230.000. The power-law exponent is 2.273, its standard error is 0.167, and the Kolmogorov–Smirnov distance is 0.061. With the boundary fixed at 1.0, the estimated exponent is 1.220 and the distance is 0.376. As the exponent changes, so does the implied rate at which probability decays over the range addressed by each fit.

Kolmogorov–Smirnov distance for power-law fits to blackout sizes by lower-bound setting

The searched boundary yields closer cumulative agreement over the tail it retains.

Kolmogorov–Smirnov distance for power-law fits to blackout sizes by lower-bound settingFixed lower boundary: 0.376Fixed lower boundary0.376Automatically selected lower boundary (this paper): 0.061Automatically selected lower boundary(this paper)0.061
The numbers
System or settingKolmogorov–Smirnov distance D
Fixed lower boundary0.376
Automatically selected lower boundary (this paper)0.061

The distance in each row is evaluated on the observations admitted by that row’s boundary. Thus the chart shows the effect of allowing the procedure to target a tail. A comparison of the curves over all blackout sizes would pose a different question. The fit beginning at the larger boundary has a smaller maximum cumulative discrepancy over its narrower range, and the fitted curve applies to that range.

The paper also restricts the blackout boundary search to 250.0 through 300.0. Within that interval the program selects 272.0. The output demonstrates how the optimum depends on which starts are allowed. The unrestricted fit and the interval-constrained fit both minimize the distance among the candidates they can consider, but their search spaces differ. The paper uses this example to illustrate the option without presenting the restricted fit as a stronger empirical account.

The comparison against the exponential is more reserved than the distance reduction might suggest. For the blackout data the raw log-likelihood ratio, with the power law first, is 12.755, and p is 0.152. The normalized version of the same contrast gives a ratio of 1.431 with p still 0.152. The direction favors the power law. The authors judge the comparison insufficient to make a convincing case for heavy-tailedness against this basic rival. The improved tail fit and the inconclusive comparison can coexist because the distance and the ratio address different questions.

Neuronal connectivity gives evidence against the exponential

For the C. elegans connection counts, the power law comes first in the comparison with the exponential. The log-likelihood ratio is 16.384 and the significance value is 0.024. The authors interpret this as evidence that the power law fits better than the exponential. The finding concerns the contrast between those families for the observed neuronal connectivity. Preferential attachment motivates the comparison, but its operation is a separate empirical question.

The comparison with the exponentially truncated power law gives a log-likelihood ratio of −0.081 and a significance value of 0.687. Here the truncated candidate is second, so the sign leans toward truncation. The test accounts for the fact that the candidates are nested. The paper treats the result as unresolved, leaving open gradual tapering at large connection counts. The two comparisons thus give different kinds of information. The ordinary exponential is less successful in this analysis, while the observations are compatible with competing accounts of how the power-law part of the curve ends.

A finite organism supplies a concrete reason for that distinction. Even if more connected neurons tend to acquire additional connections, the available set of other neurons is limited. The finite size motivates evaluating a form that can change its behavior at high counts. The likelihood comparison asks whether the available measurements detect such a change through the extra freedom of the truncated form. The answer in this example is weaker than the evidence in the comparison against the ordinary exponential.

Word frequencies leave a plausible alternative unresolved

The best-looking power-law illustration is the distribution of word frequencies in Moby Dick. When the authors overlay the empirical survival curve and the fitted power-law and lognormal curves, both candidates offer plausible visual descriptions. The log-likelihood ratio for the power law against the lognormal is 0.928, with p equal to 0.426. The direction of the ratio favors the power law, but the test leaves the choice open.

This example addresses a different difficulty from the blackout case. The comparison is between candidates that can both produce a heavy tail. The question is whether the shape contains enough information to tell them apart, even in a familiar example of scaling. In the paper’s analysis it does not. The absence of a clear distinction does not supply a measure of how different the generating processes are. It describes what the selected observations can resolve about the candidate curves.

The word-frequency results also include an illustration of the effect of an upper limit on the empirical and fitted survival plots. The cumulative power-law curve bends as it approaches a declared ceiling. The point of that display is to identify a feature produced by the support of the fit itself. Judging the curve by whether it stays straight near the endpoint would confuse the expected behavior of a bounded cumulative distribution with the separate question of whether a power law fits over the admitted interval.

Numerical examples compare different calculations

On the blackout data with discrete fitting enabled, the analytic estimate of the power-law exponent is 2.26912. Turning off that estimate and using numerical optimization gives 2.26914. The example holds the discrete treatment in place while changing how the exponent is obtained. It illustrates close agreement for this calculation. The approximation conditions discussed in the paper govern how far that result can be generalized.

For the discrete lognormal, the paper varies how the probabilities are obtained from the continuous form. With the lower boundary fixed at 230.0, and a declared upper boundary of 9000 used as the normalization limit, the estimated lognormal parameter μ is −44.19. With the same lower boundary and a finite discretization limit of 100,000, the estimate is 0.28. With rounding and the same lower boundary, it is 0.40. μ is one of the lognormal’s parameters, and these values are estimates for the blackout examples under the stated settings. The examples change the normalization or upper-bound conditions as well as how masses are constructed, so the parameter values cannot be attributed to an isolated change in approximation alone.

The paper gives separate accuracy figures for the fast generation of discrete power-law data, based on the earlier method it implements. At a generating lower boundary of 1, the reported approximation error is over 8%. At a boundary of 5 it is less than 1%, and at a boundary of 10 it is less than .2%. These figures describe the approximate sampler. They do not measure error in the blackout exponent, whose approximation was assessed by the separate comparison with numerical optimization.

Simulations test recovery where the answer is known

In the worked simulation, the authors set the generating lower boundary to 5.0 and the exponent to 2.5. They draw 10,000 observations and fit them using the package. The resulting estimates are 5.30 for the lower boundary and 2.50 for the exponent. The comparison is between a known specification of the data generator and the fitted parameters. The exponent is recovered closely at the displayed precision, while the estimated lower boundary lies above the value used to generate the sample.

The supplementary validation varies the generating exponent and the lower boundary in the discrete and continuous cases. Each displayed fit averages results from 10 simulated datasets of 10,000 observations each. The shading gives the standard deviation across the 10 simulations. This shows some of the sampling variation behind the central results. It also checks the estimator across different settings of the generating parameters instead of using the worked example as its sole test.

The authors explain why the simulated lower-bound estimates cannot fall below the generating boundary in these runs. The generator supplies no observations below that point, and the search takes its proposed starting points from observed values. When an estimated boundary differs from the true boundary because of a fluctuation in this setup, the fluctuation must put it higher. The figure therefore checks recovery from data that already start in the scaling range. The paper points to earlier work for results when observations outside that range are present below the true boundary.

What the ablations show

The paper has no conventional component-removal ablation study, but it does examine sensitivity to fitting boundaries, parameter restrictions, numerical approximations, and optimizer initialization.

The best distance and the most precise exponent can point to different ranges

The blackout example goes beyond the comparison between a fixed low boundary and an automatically chosen tail. The authors plot the distance for the different candidate starts and find separate local minima. At a lower boundary of 50 the distance is .1 and the fitted exponent is 1.78. At 230 the distance is .06 and the exponent is 2.27. The second boundary yields the better agreement by the default criterion. The first is a coherent alternative in the sense that it occupies its own low point among nearby candidates.

At the same time, the standard error generally rises as the candidate lower boundary rises in this example. The fit with the smaller cumulative discrepancy thus comes with a less precise exponent estimate. One explanation lies in what the search does to the data. Moving the boundary higher can remove observations whose behavior disagrees with the power-law curve, while leaving fewer observations with which to estimate its slope. The paper uses this example to make the sensitivity visible through the outputs retained at each boundary, rather than reporting only the selected optimum.

The unrestricted blackout fit is shown in this part of the paper with an exponent of 2.27, a standard error of 0.17, and a lower boundary of 230.00. When the analyst caps the standard error at .1, the chosen fit has an exponent of 1.78, a standard error of 0.06, and a boundary of 50.00. The constraint changes which candidate ranges qualify before the discrepancy is minimized among them. This is a comparison between different admissibility rules, with the uncertainty of the exponent now affecting the outcome explicitly.

Other rules change the result in other ways. The example with a lower limit of 2.3 on the exponent and an upper limit of .2 on its standard error yields an exponent of 2.30, a standard error of 0.17, and a boundary of 234.00. The code example limiting relative standard error to .05 returns an exponent of 1.88, a standard error of 0.09, and a boundary of 124.00. These results illustrate that a requirement about absolute uncertainty, a restriction on the exponent itself, and a relative uncertainty requirement specify distinct searches. They need not select the same range or imply the same decay within it.

The authors tighten the blackout standard-error threshold to .001 and find no candidate that satisfies it. The output still includes an exponent of 2.27, a standard error of 0.17, and a boundary of 230.00 because the program falls back to the best boundary without the requirement. The flag is set in that output. Without the flag and the warning, the returned fields on their own would give the impression that the requested constrained calculation had succeeded. What the example tests is how the software exposes a mismatch between the requested criterion and the values it can supply.

The lognormal example changes the starting conditions for a different kind of constrained calculation. Before the new restriction, the displayed estimates for μ and σ are 0.15 and 2.30. With a lower limit of 11.0 on μ, the first search returns μ of 6.22 and σ of 0.72 with the flag set. The returned μ itself makes the failure visible because it lies below the required range. The authors then supply starting values of 12 for μ and .7 for σ. The search returns μ of 11.00 and σ of 5.72 with the flag clear.

This intervention concerns the numerical search. Beginning closer to the allowed region changes whether that region is reached. The subsequent result shows that the first failure did not by itself establish the absence of a feasible fit. Feasibility in turn says only that the numerical procedure obtained parameters within the required range. The comparison of those parameters with other descriptions of the observations remains a separate operation.

The numerical and graphical comparisons isolate different effects

Switching off the analytic approximation for the discrete blackout exponent gives a direct check because both calculations target the exponent under the discrete power-law setting. The close estimates show that the shortcut is effective in that example. The discrete lognormal demonstrations give a broader sensitivity check because the range used in the calculation varies with the approximation. Their widely separated estimates give reason to attend to both choices, without establishing how much variation either choice would produce by itself.

The visualization comparisons change the representation while leaving the underlying observations in place. Changing bin spacing affects the density plot, with the largest visual impact where observations are sparse. In the upper-limit illustration, the cumulative display changes shape near the bound even though the density’s scaling can extend to that same bound. These comparisons show how properties of the display can be distinguished from evidence about the fitted family. They do not require treating a particular histogram or cumulative curve as the definition of a good fit.

The paper also describes alternatives to the default Kolmogorov–Smirnov distance for selecting the start of the tail. It calls the Kuiper distance V and the Anderson–Darling distance A². Based on the earlier analyses it cites, the former offers little practical improvement for this task, while the latter can select a range so short that the remaining data are insufficient for a satisfactory fit. The authors leave open the possibility that a large dataset with many tail observations can support the more demanding criterion. They demonstrate the availability of the settings without reporting a new numerical comparison of all the distances across the empirical examples.

Limitations

Limits identified by the authors

The paper explicitly assumes independent observations for maximum-likelihood fitting and the log-likelihood ratio comparisons. It illustrates the problem with elevations. The heights of a mountain and nearby foothills may be related, so a dataset can contain several measurements that reflect a common geographic feature. Dependence of this sort can alter the fit and the interpretation of the significance calculation. Accounting for it inside the likelihood is possible in principle, but the authors note that doing so can greatly increase the computational burden.

Where the dependence has a known structure, the authors discuss thinning the observations. For the geographic example, they imagine retaining measurements with enough separation to remove the correlations associated with nearby peaks. This relies on knowing how dependence varies with distance. Thinning also changes which observations remain. The paper presents minimum-distance fitting as another option for estimating distribution parameters, while stating that a later log-likelihood ratio test still has the same independence requirement. Changing the fitting objective therefore addresses one operation in the workflow.

The software also depends on the analyst for an upper bound and its interpretation. A finite recording window can impose a ceiling on observations from a process whose full range is larger. A physical upper limit concerns the process directly. The package can fit within either declared range, with a similar effect on the appearance of cumulative plots. The reason for the bound comes from the collection design or the science, and the paper proposes varying the observation window when that reason can be tested experimentally.

Discrepancy measures carry their own limits. The default Kolmogorov–Smirnov distance is comparatively insensitive to differences deep in a tail. Large local differences in how the rarest observations behave may have little influence on the boundary selected by this rule. The alternative distances discussed by the authors change the sensitivity of the selection. Greater emphasis on the extremes can also produce a higher start and leave too few observations for the estimate the analyst wants. The choice involves the behavior of the criterion and the amount of information available where it gives emphasis.

The authors also caution against trying a succession of ever more flexible distributions purely to improve likelihood. With an admitted range already fixed, the simple power law has a single exponent to vary, while alternatives such as the truncated form have another fitted parameter. Additional flexibility can help the curve follow the sample even when the extra structure has little scientific meaning. A plausible generating mechanism supplies a reason to add a candidate. It cannot confer evidential support on that mechanism when the comparison remains unresolved.

The approximations and numerical procedures have conditional reliability. The accelerated discrete exponent estimate has the applicability conditions given in the method discussion, and the approximate discrete sampler loses accuracy at small lower boundaries. The package’s ability to fall back or flag a failed search makes these outcomes inspectable, while the analyst still needs to read the returned status before interpreting the estimates. The authors identify a dependency at the level of special-function calculation as well. In the version they describe, accuracy for gamma functions with negative arguments motivates the use of mpmath for fitting the gamma distribution and the discrete exponentially truncated power law.

Limits visible in the study design

The empirical datasets illustrate a workflow across differing tail shapes. They do not form a common evaluation design for every family, approximation, and range option the package offers. The paper does not give a uniform account of sample sizes and preprocessing for all the empirical examples alongside each reported result. The examples can be understood in terms of the variables, comparisons, and settings the authors identify. A systematic judgment about performance across all supported settings would require broader evidence.

The paper’s comparison with earlier software is chiefly a comparison of design and coverage. Its examples show how several operations can share a fitted dataset, how candidate parameters are exposed, and how the analysis can use different ranges and distribution forms. They do not measure user effort under a common protocol or benchmark the running times of the competing packages across all the operations discussed. The case for convenience follows from the interface the authors show, and the numerical examples establish results for particular configurations.

The range-search examples also have a built-in limit as evidence of overall fit. The best distance is found by examining the observed discrepancies over several proposed tails, then choosing the tail that scores best under the criterion. It is an in-sample result on the retained observations. A lower distance obtained by moving the boundary upward says that the retained cumulative distribution can agree more closely with the power law. It does not evaluate how well the same description accounts for the excluded observations, and it gives no separate validation of the chosen range on new data.

The simulation study tests a narrower setting than an empirical analysis in which the start of scaling has to be found amid a mixture of behaviors. Its known generating law makes parameter recovery interpretable, and repeated samples expose variation even in that controlled case. The absence of observations below the true start also gives the search a particular constraint: all candidate points already lie at or above the generating boundary. The study therefore supplies evidence about fitting clean simulated tails. Its design cannot by itself determine how the same search performs when an empirical tail is preceded by a substantial body of observations governed by another process.

The simulations likewise do not supply a causal check on the three empirical examples. A generator using a specified power law is useful because the answer is known in advance. In empirical work, the generating process is the unknown quantity. Similarity to the fitted probability curve can motivate a hypothesis, but it cannot identify preferential attachment in a neuronal network or establish a multiplicative mechanism for word frequencies. The distribution and the mechanism occupy different levels of explanation.

Finally, the empirical comparisons give a comparison-specific meaning to an unresolved result. The word-frequency test leaves the power law and the lognormal difficult to distinguish on those observations. The neuronal test leaves the presence of exponential truncation open. The blackout comparison leaves the basic exponential alternative in contention. In each case the uncertainty is scoped to the candidates and fitting range used in the calculation. It neither establishes that the candidates would agree over a wider range nor evaluates other explanations that were not fitted. The paper’s emphasis on experiments that target the generating processes follows from this remaining uncertainty.

What came after

No later study is identified for this article. The historical account therefore ends with the development directions the authors describe at publication. They report that users had already suggested changes and contributed improvements to individual distributions. The common Distribution class was intended to make this kind of extension easier by allowing each new family to provide its own probability calculations while taking part in the existing fitting and comparison workflow.

The authors also identify work that would depend on advances in numerical methods. More efficient procedures for discrete random generation could be incorporated where suitable ones became available. Improvements in gamma-function evaluation for the relevant arguments could alter the need for the separate numerical dependency used by particular fits. The paper presents these as possibilities for further development. Its documented contribution is the workflow and the behavior demonstrated with the software version accompanying the article.

Cite

Cite as Jeff Alstott, Edward Thomas Bullmore and Dietmar Plenz. 2014. powerlaw: A Python Package for Analysis of Heavy-Tailed Distributions. PLoS ONE.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.1371/journal.pone.0085777 · arXiv 1305.0215

@inproceedings{alstott2014powerlaw,
  title = {{powerlaw: A Python Package for Analysis of Heavy-Tailed Distributions}},
  author = {Jeff Alstott, Edward Thomas Bullmore and Dietmar Plenz},
  booktitle = {PLoS ONE},
  year = {2014},
  doi = {10.1371/journal.pone.0085777},
  eprint = {1305.0215},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.1371/journal.pone.0085777}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/alstott-2014-powerlaw-python-package-analysis-heavy/