A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
sample-rng-plot.py
Go to the documentation of this file.
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
5## @file
6# @ingroup core-examples
7# @ingroup randomvariable
8# Demonstrate use of ns-3 as a random number generator integrated with
9# plotting tools.
10#
11# This is adapted from Gustavo Carneiro's ns-3 tutorial
12
13
14import argparse
15import sys
16
17import matplotlib.pyplot as plt
18import numpy as np
19
20## Import ns-3
21try:
22 from ns import ns
23except ModuleNotFoundError:
24 raise SystemExit(
25 "Error: ns3 Python module not found;"
26 " Python bindings may not be enabled"
27 " or your PYTHONPATH might not be properly configured"
28 )
29
30
31def main():
32 parser = argparse.ArgumentParser("sample-rng-plot")
33 parser.add_argument("--not-blocking", action="store_true", default=False)
34 args = parser.parse_args(sys.argv[1:])
35
36 # mu, var = 100, 225
37
38 ## Random number generator.
39 rng = ns.CreateObject[ns.NormalRandomVariable]()
40 rng.SetAttribute("Mean", ns.DoubleValue(100.0))
41 rng.SetAttribute("Variance", ns.DoubleValue(225.0))
42
43 ## Random number samples.
44 x = [rng.GetValue() for t in range(10000)]
45
46 # the histogram of the data
47
48 ## Make a probability density histogram
49 density = 1
50 ## Plot color
51 facecolor = "g"
52 ## Plot alpha value (transparency)
53 alpha = 0.75
54
55 # We don't really need the plot results, we're just going to show it later.
56 # n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)
57 n, bins, patches = plt.hist(x, 50, density=True, facecolor="g", alpha=0.75)
58
59 plt.title("ns-3 histogram")
60 plt.text(60, 0.025, r"$\mu=100,\ \sigma=15$")
61 plt.axis([40, 160, 0, 0.03])
62 plt.grid(True)
63 plt.show(block=not args.not_blocking)
64
65
66if __name__ == "__main__":
67 main()