entropy.html


001| """Shannon Entropy Study (and Chart)."""
002| ####################################################################################################
003| from sys import argv
004| from os import path
005| from math import log,log2,log10, factorial
006| from random import randint
007| import matplotlib.pyplot as plt
008| from matplotlib.ticker import MultipleLocator, NullFormatter, FormatStrFormatter
009| ####################################################################################################
010| BasePath = r'C:\CJS\prj\Python\blog'
011| ImgsPath = path.join(BasePath,'img')
012| Filename = 'entropy-shannon.png'
013| 
014| ##================================================================================================##
015| ## Miscellaneous Utility Functions
016| ##================================================================================================##
017| def n_choose_k (nb, k):
018|     """nb!/k!(nb-k)!"""
019|     if nb < k: return 0
020|     return int(factorial(nb)/(factorial(k)*factorial(nb-k)))
021| 
022| ##================================================================================================##
023| def normalize (xs):
024|     """Normalize number list to sum to 1.00."""
025|     tot = float(sum(xs))
026|     return [x/tot for x in xs]
027| 
028| ##================================================================================================##
029| def bit_cmp (na, nb):
030|     """Count mismatched bits in NA vs NB."""
031|     xor = na ^ nb
032|     bits = [int(b) for b in bin(xor)[2:]]
033|     return sum(bits)
034| 
035| ##================================================================================================##
036| def bitstr (n, NB=16, zero='0'):
037|     """Create bitstring list NB bits long."""
038|     bs = list(reversed(bin(n)[2:]))
039|     dx = NB-len(bs)
040|     if 0 < dx:
041|         bs.extend(zero*dx)
042|     return list(reversed(bs))
043| 
044| ##================================================================================================##
045| def combine (*args, fill=''):
046|     """Like ZIP but uses longest."""
047|     its = [iter(a) for a in args]
048|     flags = [1]*len(its)
049|     while True:
050|         out = []
051|         for ix,it in enumerate(its):
052|             try:
053|                 v = next(it)
054|             except StopIteration:
055|                 v = fill
056|                 flags[ix] = 0
057|             finally:
058|                 out.append(v)
059|         if sum(flags) == 0:
060|             break
061|         yield tuple(out)
062| 
063| ##================================================================================================##
064| def comp_patt (patt, ref_patt, NB):
065|     """Compare pattern to reference pattern."""
066|     slist = lambda g:''.join(g)
067|     p0 = bitstr(patt, NB=NB)
068|     p1 = bitstr(ref_patt, NB=NB)
069|     ds = [int(a!=b) for a,b in combine(p0,p1)]
070|     ss = [('X' if n else '_') for n in ds]
071|     dt = sum(ds)
072|     df = 1.0 - (float(dt)/float(NB))
073|     #print('[%s] %04x' % (slist(p1), ref_patt))
074|     #print('[%s] %04x' % (slist(p0), patt))
075|     #print('%03x [%s] (%d, %.6f)' % (patt, slist(ss),dt,df))
076|     #print()
077|     return (df, dt, ds)
078| 
079| ##================================================================================================##
080| def demo_comp_patt (NB=5):
081|     r = 0 #randint(1, pow(2,NB)-1)
082|     x = 0
083|     for ix in range(NB+1):
084|         print('%d: %d' % (ix,x))
085|         comp_patt(x, r, NB)
086|         x *= 2
087|         x |= 1
088|     print()
089| 
090| ##================================================================================================##
091| def demo_bit_patterns (NB=5):
092|     """Probability function; take 2."""
093|     NP = pow(2,NB)
094|     r = randint(1, pow(2,NB)-1)
095|     dat = {}
096|     for x in range(NP):
097|         df,dt,_ = comp_patt(x, r, NB)
098|         if dt not in dat: dat[dt] = 0
099|         dat[dt] += 1
100|     #
101|     print()
102|     for dt in sorted(dat):
103|         print('%d: %d' % (dt,dat[dt]))
104|     print()
105|     print('total: %d' % sum(dat.values()))
106|     print()
107|     return dat
108| 
109| ##================================================================================================##
110| ## Shannon Entropy Calculation
111| ##================================================================================================##
112| def max_shannon_entropy (NP, logbase=2):
113|     """Calculate maximum Shannon Entropy."""
114|     # Generate (equal) probabilities...
115|     ps = [1.0/float(NP) for p in range(NP)]
116|     # Calculate entropy...
117|     es = [(p*log(p,logbase)) for p in ps]
118|     ent = -sum(es)
119|     # Print (and return) result...
120|     print(ent)
121|     print(sum(ps))
122|     print()
123|     return ent
124| 
125| ##================================================================================================##
126| def demo_max_shannon_entropy (NP=27, logbase=10):
127|     """Maximum entropy for NP using logbase."""
128|     return max_shannon_entropy(NP, logbase=logbase)
129| 
130| ##================================================================================================##
131| def shannon_entropy (NP, PF, logbase=2):
132|     """Calculate the Shannon Entropy given PF(x)."""
133|     # Generate probabilities...
134|     probs = [PF(x) for x in range(NP)]
135|     tprob = sum(probs) # expected to be 1.000
136|     # Generate list of summation terms...
137|     ents = [p*log(p,logbase) for p in probs]
138|     # Sum the terms...
139|     ent = -sum(ents)
140|     # Return all the generated data...
141|     return (ent, ents, tprob, probs)
142| 
143| ##================================================================================================##
144| def demo_shannon_entropy (NB=5, p_of_x=None):
145|     """Shannon entropy for a specific P(X)."""
146|     NP = pow(2,NB)
147|     PF = (1.0/NP) if p_of_x is None else p_of_x
148|     PX = randint(1, NP-1)
149|     probs = lambda x: PF if x==PX else ((1.0-PF)/(NP-1))
150|     ent,_,tprob,_ = shannon_entropy(NP, probs)
151|     print()
152|     print('NB=%d, NP=%d' % (NB,NP))
153|     print('P(PX)=PF=%.12f' % PF)
154|     print('tot-prob=%.12f' % tprob)
155|     print('entropy=%.12f' % ent)
156|     print()
157|     return ent
158| 
159| ##================================================================================================##
160| def demo_shannon_curve (NB=5):
161|     """Shannon Entropy curve for P(X)."""
162|     extra = [0.999999, 0.9999999]
163|     NP = pow(2,NB)
164|     X = randint(1, NP-1)
165|     print('NB=%d, NP=%d' % (NB,NP))
166|     print('X=%d' % X)
167|     print()
168|     # P(X) goes from 1/NP thru (NP-1)/NP...
169|     ps = [n/NP for n in range(1,NP)]
170|     # Loop over probabilities for P(X)...
171|     for ix,p in enumerate(ps+extra):
172|         PF = lambda x:p if x==X else ((1.0-p)/(NP-1))
173|         ent,_,tp,_ = shannon_entropy(NP, PF)
174|         print('%4d: %.9f = %.12f (%.6f)' % (1+ix, p, ent, tp))
175|     print()
176| 
177| ##================================================================================================##
178| ## BAD (attempt at weighted probability function)
179| ##================================================================================================##
180| def prob_func (patt, ref_patt, NB, hip=0.9, lop=0.5):
181|     """Probability function (NG; not normalized)."""
182|     p0 = bitstr(patt, NB=NB)
183|     p1 = bitstr(ref_patt, NB=NB)
184|     ds = [int(a!=b) for a,b in combine(p0,p1)]
185|     ss = [('X' if n else '_') for n in ds]
186|     dt = sum(ds)
187|     pf = hip - (abs(lop-hip) * (dt/NB))
188|     print('[%s] d=%d, p=%.5f' % (''.join(ss),dt,pf))
189|     return pf
190| 
191| ##================================================================================================##
192| def demo_prob_func (NB=5):
193|     """Probability function; take 1. (NG!)"""
194|     NP = pow(2,NB)
195|     PX = randint(1, NP-1)
196|     PF = lambda x:prob_func(x,PX,NB)
197|     print()
198|     print('NB=%d, NP=%d' % (NB,NP))
199|     print('PX=%d' % PX)
200|     print('P(PX)=PF=%.12f' % PF(PX))
201|     print()
202|     ent,_,tp,_ = shannon_entropy(NP, PF)
203|     print()
204|     print('entropy=%.12f' % ent)
205|     print('tot-prob=%.12f' % tp)
206|     print()
207|     return ent
208| 
209| ##================================================================================================##
210| ## Probability Function Experiment
211| ##================================================================================================##
212| def make_prob_function (NB=5, p_max=1.0, p_pow=2):
213|     """Generate a list of probabilities."""
214|     buf = []
215|     # Build list of [bit#, #patts, probf, $1*$2, norm.probf]...
216|     for n in range(NB+1):
217|         x = n_choose_k(NB,n)
218|         pf = p_max / float(pow(p_pow,n))
219|         buf.append([n,x,pf,x*pf])
220|         #print('%d: %d %e' % (n, x, pf))
221|     # Check all patterns are accounted for...
222|     dt = sum([t[1] for t in buf])
223|     print('found %d patterns (bits:%d)' % (dt,NB))
224|     # Get total probability...
225|     tp = sum([t[3] for t in buf])
226|     print('total-prob: %.5f' % tp)
227|     print()
228|     # Append probability factor to each element...
229|     for t in buf:
230|         t.append(t[2]/tp)
231|         print('%2d %5d %.5e %.4e %.5e' % tuple(t))
232|     print()
233|     return [t[4] for t in buf]
234| 
235| ##================================================================================================##
236| def demo_make_prob_function (NB=5, p_pow=10):
237|     NP = pow(2,NB)
238|     ps = make_prob_function(NB=NB, p_pow=p_pow)
239|     XN = randint(1, NP-1)
240|     XB = bitstr(XN, NB=NB)
241|     def PF (patt):
242|         xa = bitstr(patt, NB=NB)
243|         ds = [int(a!=b) for a,b in zip(xa,XB)]
244|         dt = sum(ds)
245|         return ps[dt]
246|     print('NB=%d, NP=%d' % (NB,NP))
247|     print('XN=%d' % XN)
248|     print('PF(XN)=%.12f' % PF(XN))
249|     print()
250|     ent,_,tp,_ = shannon_entropy(NP,PF)
251|     print('entropy=%.12f' % ent)
252|     print('tot-prob=%.12f' % tp)
253|     print()
254|     return (ent,ps)
255| 
256| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
257| ## Shannon Entropy Calculator class
258| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
259| class entropy (object):
260|     """Shannon Entropy Calculator class."""
261|     def __init__ (self, nbr_of_bits):
262|         """New instance needs number of bits for variable."""
263|         self.nb = nbr_of_bits
264|         self.np = pow(2,self.nb)
265|     def pf (self, x):
266|         """Probability Function. (Override in subclass!)"""
267|         # Base class gives all patterns 100% probability...
268|         return 1.0
269|     def __call__ (self):
270|         """Generate and print results."""
271|         self.ns = [n_choose_k(self.nb,k) for k in range(self.nb+1)]
272|         # Normalized Probability Factors...
273|         self.fs = [self.pf(x) for x in range(self.nb+1)]
274|         self.ts = [n*f for n,f in zip(self.ns,self.fs)]
275|         self.tp = sum(self.ts)
276|         self.ps = [f/self.tp for f in self.fs]
277|         # Calculate Shannon entropy...
278|         self.xs = [self.ps[bit_cmp(0,p)] for p in range(self.np)]
279|         self.es = [x*log2(x) for x in self.xs]
280|         self.ent = -sum(self.es)
281|         self.tpx = sum(self.xs)
282|         # Print results...
283|         print(str(self))
284|         print()
285|         for ix,rcd in enumerate(zip(self.ns,self.fs,self.ts,self.ps)):
286|             print('%2d:%6d %12.4e %12.4e %14.6e' % ((ix,)+rcd))
287|         print()
288|         print('PF(EXP)=%.8f (tp=%.6f)' % (self.ps[0], self.tp))
289|         print('entropy=%.8f (tp=%.6f)' % (self.ent, self.tpx))
290|         print()
291|         return self.ent
292|     def __str__ (self):
293|         return '#bits:%d, #patterns:%d' % (self.nb, self.np)
294| 
295| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
296| class entropy1 (entropy):
297|     """Fixed-Probability Entropy sub-class. (default: 1/NP)"""
298|     def __init__ (self, nbits, divisor=None):
299|         """New instance needs a probability divisor."""
300|         super().__init__(nbits)
301|         # Calculate fixed-probability...
302|         self.prob = 1.0/float(divisor if divisor else self.np)
303|     def pf (self, x):
304|         """Return fixed-probability."""
305|         return self.prob
306| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
307| class entropy2 (entropy):
308|     """Single-Pattern Probability Entropy sub-class."""
309|     def __init__ (self, nbits, divisor=10000):
310|         """New instance needs a probability divisor."""
311|         super().__init__(nbits)
312|         # Calculate non-match probability...
313|         self.prob = 1.0/float(divisor)
314|     def pf (self, x):
315|         """Return probability."""
316|         return (1.0 if x==0 else self.prob)
317| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
318| class entropy3 (entropy):
319|     """Bit Error Powers Entropy sub-class."""
320|     def __init__ (self, nbits, factor):
321|         """New instance needs a factor for factor^X."""
322|         super().__init__(nbits)
323|         self.fact = float(factor)
324|     def pf (self, x):
325|         return (1.0/pow(self.fact,x))
326| 
327| ##================================================================================================##
328| def demo_entropy_class (NB=8):
329|         e0 = entropy(NB)
330|         e1 = entropy1(NB, 5.0)
331|         e2 = entropy2(NB, 1e6)
332|         e3 = entropy3(NB, 250)
333|         e0()
334|         e1()
335|         e2()
336|         e3()
337|         return (e0,e1,e2,e3)
338| 
339| ##================================================================================================##
340| ## The Entropy of the 27 Teas
341| ##================================================================================================##
342| def tea_entropy (probs):
343|     """\
343| Calculate Tea Entropy.
343| ======================
343| Assumes 27 tea types in 3 macro-states:
343|     A - one main tea type
343|     B - three alternate tea types
343|     C - 23 remaining tea types
343| 
343| Function takes list of three relative probabilities
343| to apply to the macro-states A, B, and C.
343| """

344|     n_patterns = 27
345|     # Macro-state population sizes...
346|     sizes = [1, 3, 23]
347|     # Total (relative) probability...
348|     tots = [n*p for n,p in zip(sizes,probs)]
349|     tprob = sum(tots)
350|     # Normalized probability factors...
351|     pfs = [p/tprob for p in probs]
352|     # Define a Probability Function...
353|     def PF (x):
354|         if x == 0: return pfs[0]
355|         if x in [1,2,3]: return pfs[1]
356|         return pfs[2]
357|     # Probabilities for each tea type...
358|     ps = [PF(p) for p in range(n_patterns)]
359|     # Individual entropies for tea types...
360|     ents = [p*log(p,2) for p in ps]
361|     # Results...
362|     ent = -sum(ents)
363|     print('%.8f (%.6f)' % (ent,sum(ps)))
364|     print(pfs)
365|     print('%s %s' % (tots, tprob))
366|     print()
367|     return ent
368| 
369| ##================================================================================================##
370| def demo_tea_entropy ():
371|     """Calculate different probability lists."""
372|     tea_entropy([1.0, 1.00, 1.0000])
373|     tea_entropy([1.0, 0.50, 0.1000])
374|     tea_entropy([1.0, 0.25, 0.0100])
375|     tea_entropy([1.0, 0.10, 0.0001])
376| 
377| ##================================================================================================##
378| def individual_probabilities (NP=64, p_pow=10, verbose=False):
379|     """Entropy with individual P(x) probabilities."""
380|     NB = log2(NP)
381|     ps = [(1.0/pow(p_pow,x)) for x in range(NP)]
382|     ms = normalize(ps)
383|     if verbose:
384|         for ix,t in enumerate(zip(ps,ms)):
385|             print('%2d: %.5e %.5e' % (ix,t[0], t[1]))
386|         print()
387|     else:
388|         for ix,t in enumerate(zip(ps[:3],ms[:3])):
389|             print('%2d: %.5e %.5e' % (ix,t[0], t[1]))
390|         print('...')
391|         for ix,t in enumerate(zip(ps[-3:],ms[-3:])):
392|             print('%2d: %.5e %.5e' % ((NP-3)+ix,t[0], t[1]))
393|         print()
394|     print()
395|     def PF (x):
396|         return ms[x]
397|     ent,_,tprob,_ = shannon_entropy(NP, PF)
398|     print('entropy=%.12f (@ %.3f bits)' % (ent,NB))
399|     return ent
400| 
401| ##================================================================================================##
402| ## Shannon Entropy Chart
403| ##================================================================================================##
404| def shannon_entropy_chart ():
405|     """Create a chart of Shannon Entropy curves for different bit sizes."""
406| 
407|     def generate_curve (NB=8):
408|         """Generate the Shannon Entropy curve for NB bits."""
409|         NP = pow(2,NB)
410|         PX = randint(1, NP-1)
411| 
412|         def shannon_entropy_curve (xs, P):
413|             """Curve generator."""
414|             ps = [P(x) for x in xs]
415|             es = [p*log2(p) for p in ps]
416|             return (-sum(es), es, sum(ps), ps)
417| 
418|         # Loop over probabilities for PX...
419|         xs = []
420|         ys = []
421|         for ix,PF in enumerate([n/NP for n in range(1,NP)]):
422|             probs = lambda x: PF if x==PX else ((1.0-PF)/(NP-1))
423|             ent,_,tp,_ = shannon_entropy_curve(range(NP), probs)
424|             xs.append(ix)
425|             ys.append(ent)
426|             print('%4d: %.9f = %.12f (%.6f)' % (1+ix, PF, ent, tp))
427|         print()
428|         return (xs, ys)
429| 
430|     xs5,ys5 = generate_curve(NB=5)
431|     xs6,ys6 = generate_curve(NB=6)
432|     xs7,ys7 = generate_curve(NB=7)
433|     xs8,ys8 = generate_curve(NB=8)
434|     xs9,ys9 = generate_curve(NB=9)
435| 
436|     xmin,xmax = 0, +256
437|     ymin,ymax = 0.0, +10.0
438| 
439|     fig, ax = plt.subplots()
440|     fig.suptitle('Shannon Entropy', fontweight='bold')
441|     fig.set_figwidth(8.0)
442|     fig.set_figheight(6.0)
443|     fig.subplots_adjust(left=0.11, right=0.98, bottom=0.10, top=0.93)
444| 
445|     ax.set_xlabel(r'Probability $[p(X)={x}/{NP}]$')
446|     ax.set_xlim(xmin,xmax)
447|     #ax.set_xticks(xts0, minor=False)
448|     #ax.set_xticks(xts1, minor=True)
449|     #ax.set_xticklabels(xss0)
450|     ax.xaxis.set_major_locator(MultipleLocator(32))
451|     ax.xaxis.set_minor_locator(MultipleLocator(8))
452|     ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
453|     ax.xaxis.set_minor_formatter(NullFormatter())
454| 
455|     for tick in ax.xaxis.get_major_ticks():
456|         tick.label1.set_rotation('vertical')
457|         tick.label1.set_size(9)
458| 
459|     ax.set_ylabel(r'Entropy $[-\sum\;p(x)\;\log_2\;p(x)]$')
460|     ax.set_ylim(ymin,ymax)
461|     ax.yaxis.set_major_locator(MultipleLocator(5.0))
462|     ax.yaxis.set_minor_locator(MultipleLocator(1.00))
463|     ax.yaxis.set_major_formatter(FormatStrFormatter('%+.1f'))
464|     ax.yaxis.set_minor_formatter(NullFormatter())
465| 
466|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
467|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
468|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
469|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
470| 
471|     ax.plot(xs9,ys9, c='#990099', lw=2.0, label=r'9 bits', zorder=19)
472|     ax.plot(xs8,ys8, c='#ff0000', lw=2.0, label=r'8 bits', zorder=18)
473|     ax.plot(xs7,ys7, c='#0000ff', lw=2.0, label=r'7 bits', zorder=17)
474|     ax.plot(xs6,ys6, c='#cc6600', lw=2.0, label=r'6 bits', zorder=16)
475|     ax.plot(xs5,ys5, c='#009900', lw=2.0, label=r'5 bits', zorder=15)
476|     ax.legend(loc='upper right', shadow=True)
477| 
478|     fn = path.join(ImgsPath, Filename)
479|     fig.savefig(fn)
480|     print('wrote: %s' % fn)
481|     print()
482| 
483| ##================================================================================================##
484| def main ():
485|     #demo_comp_patt(NB=6)
486|     #d = demo_bit_patterns(NB=4)
487|     #demo_max_shannon_entropy()
488| 
489|     #demo_shannon_entropy(p_of_x=0.999999)
490|     #demo_shannon_entropy(NB=10)
491|     #demo_shannon_entropy(NB=10, p_of_x=0.99)
492| 
493|     #demo_shannon_curve()
494|     #demo_shannon_curve(NB=8)
495|     #demo_shannon_curve(NB=10)
496| 
497|     #demo_prob_func(NB=5)
498| 
499|     #ps = make_prob_function(NB=8, p_max=1.0, p_pow=10)
500|     #ds = [a/b for a,b in zip(ps[1:],ps)]
501| 
502|     #ent,ps = demo_make_prob_function(NB=8, p_pow=100)
503| 
504|     #es=demo_entropy_class()
505| 
506|     demo_tea_entropy()
507| 
508|     #individual_probabilities()
509|     #individual_probabilities(NP=27, p_pow=1.111, verbose=True)
510|     #individual_probabilities(NP=27, p_pow=8, verbose=True)
511| 
512| ####################################################################################################
513| if __name__ == '__main__':
514|     print(argv[0])
515|     print()
516|     main()
517|     print()
518| ####################################################################################################
519| '''eof'''
520|