probability-curve.html
001|
002| from sys import argv
003| from os import path, environ
004| from random import randint
005| from matplotlib import pyplot as plt
006| from matplotlib.ticker import MultipleLocator
007| from goodies import KWARG, typename
008|
009| BasePath = r'C:\CJS\prj\Python\ws\xbar'
010|
011|
012|
013| def increasing_probability (span:int=100, factor:float=1.0, N:int=1_000_000) -> list:
014| '''Generate increasing probability (of timeout) curve (and chart).
014|
014| With each tick, the probability of exiting becomes higher up to 100%.
014|
014| tick r (r < tick) #t/#F %
014| ----- ---------- ----------------------- ------- ----
014| 0 [0, top-1] F0,F1,F2,F3, ... Ftop-1 0/100 0%
014| 1 " T0,F1,F2,F3, ... Ftop-1 1/100 1%
014| 2 " T0,T1,F2,F3, ... Ftop-1 2/200 2%
014| 3 " T0,T1,T2,F3, ... Ftop-1 3/100 3%
014| : : : : : : : :
014| top-1 " T0,T1,T2,T3, ... Ftop-1 99/100 99%
014| top " T0,T1,T2,T3, ... Ttop-1 100/100 100%
014| ----- ---------- ----------------------- ------- ----
014| '''
015|
016| def test (top:int=100):
017| for tick in range(top+1):
018| r = randint(0, top-1)
019| if r < tick:
020| return tick
021| return -1
022|
023| hist = [0]*(span+1)
024|
025| for _ in range(N):
026| val = test(int(span * factor))
027| if 0 <= val < len(hist):
028| hist[val] += 1
029| else:
030| print(f'test()={val}')
031|
032| xtop = 0
033| for ix,t in enumerate(hist):
034| if 0 < t:
035| xtop = min(ix, span)
036| print(f'Highest Value: {xtop}')
037| print()
038|
039| xs = list(range(len(hist)))
040| ys = [val for val in hist]
041|
042| xmax = len(xs)
043| ymax = max(ys)
044|
045| fig, ax = plt.subplots()
046| fig.set_figwidth(6.0)
047| fig.set_figheight(3.0)
048| fig.subplots_adjust(left=0.130, right=0.99, bottom=0.15, top=0.91)
049| fig.suptitle(f'Probability Curve ({N=:,}, f={factor:.1f})', fontsize=12, fontweight='bold')
050| ax.set_xlabel('Tick Timeout', fontsize=10)
051| ax.set_ylabel('Occurances', fontsize=10)
052| ax.set_xlim(0, xmax)
053| ax.set_ylim(0, ymax)
054| ax.xaxis.set_major_locator(MultipleLocator(10))
055| ax.grid(which='major', axis='both', color='#7f7f7f', lw=0.7,ls='-', alpha=1.0, zorder=1)
056| ax.axvline(xtop, lw=3.3, c='blue', alpha=0.90, zorder=11)
057| ax.fill_between(xs,0,ys, lw=1.8, fc='#cc6633', alpha=0.70, zorder=21)
058| ax.plot(xs,ys, lw=1.8, c='red', alpha=0.85, zorder=31)
059|
060| fn = path.join(BasePath,'probability.png')
061| plt.savefig(fn)
062| plt.close(fig)
063| print(f'wrote: {fn}')
064|
065| return hist
066|
067|
068|
069| if __name__ == '__main__':
070| print(argv[0])
071| print()
072|
073| hist = increasing_probability()
074|
075| print()
076|
077| '''eof'''
078|