Skip to content

How do I fit input distributions from data?

In short

  • You build: a script that fits candidate distributions to 200 handling times, picks the winner, and shows what the fit changes in a queue.
  • You need: Python 3.11 or later, pip install nagasim, and the one-queue model from step 1 of the learning path.
  • Time: about ten minutes.

A model is only as good as its input distributions, and an exponential is a poor default for most real service times. By the end you run a distribution fit, read its AIC and KS test, and put the winner into a model as a distribution.

This page has three parts: Step by step, Check yourself and If stuck. The last section lists the reference pages for the elements used.

Step by step

  1. Save this script as goal-fit.py. The 200 handling times are drawn from a seeded lognormal, so the page can print the same numbers every time. This is a stand-in for your own data. To use a file, replace the line with inputfit.load_column("times.csv").values.
import numpy as np
from nagasim import build as nb, inputfit

# 200 handling times in minutes. Here they are drawn from a seeded lognormal; in a study they come from
# a column of your own data: `inputfit.load_column("times.csv").values`.
times = np.random.default_rng(7).lognormal(mean=-0.4, sigma=0.5, size=200)

fits = inputfit.fit_candidates(times)
for fit in fits[:3]:
    params = {name: round(float(value), 3) for name, value in fit.dist_params.items()}
    print(f"{fit.distribution:<15} AIC {fit.aic:6.1f}  KS p-value {fit.ks_pvalue:.2f}  {params}")

best = inputfit.best_fit(times)
print("winner:", best.distribution)


def mean_wait(service):
    m = nb.Model(time_limit=480, warmup=0)
    m.add_resource(name="Server")
    arrive = m.create(distribution=nb.Exponential(rate=1.0))
    arrive >> m.process(resource_name="Server", distribution=service) >> m.dispose()
    return m.run(replications=20, seed=1).kpi("resource/Server/Time in Queue Avg")


# The same queue with the fitted distribution, and with an exponential of the same mean.
print(f"fitted {best.distribution}: mean wait {mean_wait(nb.Distribution(best.distribution, best.dist_params)):.2f} minutes")
print(f"exponential, same mean: mean wait {mean_wait(nb.Exponential(rate=1 / times.mean())):.2f} minutes")
  1. Run it.
python goal-fit.py

You should see this. The script seeds itself, so the numbers are the same on your machine.

InverseGaussian AIC   53.1  KS p-value 0.77  {'mu': 0.69, 'lambda': 3.302}
Lognormal       AIC   53.3  KS p-value 0.76  {'mu': -0.466, 'sigma': 0.436}
Erlang          AIC   56.7  KS p-value 0.23  {'k': 5.0, 'rate': 7.25}
winner: InverseGaussian
fitted InverseGaussian: mean wait 0.89 minutes
exponential, same mean: mean wait 1.43 minutes
  1. Read the first three lines. fit_candidates fits every family that suits the data and ranks them by AIC. A lower AIC is a better fit after the penalty for extra parameters. The parameters are in the engine's own naming, so you can paste them into a model.

  2. Compare the first two lines. The top two families differ by less than one AIC point, which is no real difference. Pick the one you can explain to your reader. The lognormal is the usual choice for handling times, and the data were drawn from one.

  3. Read the KS p-value. A high value means the sample does not contradict the fit. It is optimistic here, because the parameters were estimated from the same sample, so use it to reject a poor fit and not to prove a good one.

  4. Read the last two lines. best_fit returns the winner, and nb.Distribution(name, params) turns it into a distribution the builder accepts. The same queue with an exponential of the same mean waits longer, because an exponential has more spread than these data. Matching the mean is not enough.

Check yourself

  • Predict, then run: if you pass candidates=["Exponential", "Normal"] to fit_candidates, which family wins and what happens to the AIC? Try it.
  • Explain it back: why is a high KS p-value not proof that the fit is right?

Done when

  • [ ] The script prints three ranked fits, the winner and two mean waits.
  • [ ] You can say why two fits within one AIC point are a tie.
  • [ ] You can say why matching only the mean of an input can mislead a result.

If stuck

What happens Likely cause Fix
best_fit returns None No family can be fit to the data, for instance when all values are equal Look at the data with inputfit.describe(values). Use an empirical distribution if no family fits.
A fit of one or two values returns a strange family There is too little data to tell families apart. One value gave Geometric with p equal to 1.0 Collect more data. Under 30 observations, treat the choice as rough.
The winner is a family you cannot explain AIC ranks fit and not meaning Choose from the top few the one that matches the process, and say so.
KeyError: column 'x' not found The column name is not in the file The message lists the available columns. Pick one of them.

Elements this page uses

Next: Run with input uncertainty.