emerg_struc_compl.html


001| '''Emergent Structural Complexity (ESC).
001| 
001| Functions:
001|     scramble_word (word, num_of_chars)
001|     scramble_word_sometimes (word, noise, num_of_chars)
001|     add_noise_to_word (word, noise, distance)
001|     zip_compression_type (n)
001|     determine_ygrid_spacing (datamax)
001| 
001| Classes:
001|     CharStripper -- for translate; strips mask chars
001| 
001| Commands:
001|     a:zip       do_all_ef_charts
001|     c:zip       do_emergence_factor_chart
001|     c:cmp       do_zipfile_compare_chart
001|     c:ss-ef     do_ss_ef_chart
001| 
001|     a:cmd       do_command_loop
001|     tfade       do_text_blank_to_random
001|     xfade       do_image_black_to_random
001|     a:inoise    do_image_add_noise_all
001|     a:dnoise    do_data_add_noise_all
001|     a:tnoise    do_text_add_noise_all
001| 
001|     iscram      do_scramble_image_file
001|     inoise      do_image_add_noise
001|     dnoise      do_data_add_noise
001|     tnoise      do_text_add_noise
001|     txtfile     do_txtfile_scramble
001|     hamlet      do_hamlet_scramble
001| 
001|     rnd:dat     do_random_data_file
001|     rnd:txt     do_random_text_file
001|     rnd:wrd     do_random_words_file
001|     rnd:chr     do_random_chars_file
001|     rnd:lin     do_random_lines_file
001| 
001|     zipfile     do_list_zip_file
001|     test        do_test
001| '''

002| ####################################################################################################
003| from sys import argv, stdout, exc_info
004| from traceback import extract_tb
005| from os import path, listdir
006| from re import fullmatch, IGNORECASE
007| from math import sqrt, log, exp
008| from random import random, randint, shuffle, choice
009| from zipfile import ZipFile
010| from zipfile import ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2, ZIP_LZMA
011| from PIL import Image
012| from matplotlib import pyplot as plt
013| from matplotlib.ticker import NullLocator, FixedLocator, MultipleLocator
014| from matplotlib.ticker import NullFormatter, FixedFormatter, FormatStrFormatter
015| from logger import logger,info,debug,trace, LogFilenameTimestamp
016| from goodies import KWARG, intervals, safediv
017| from files import SPC, EOL, datafile, textfile, linefile, tabfile
018| ####################################################################################################
019| BasePath = r'C:\CJS\prj\Python\blog\substack\ESC'
020| DataPath = path.join(BasePath, 'dat')
021| TextPath = path.join(BasePath, 'txt')
022| ImgsPath = path.join(BasePath, 'img')
023| ZipsPath = path.join(BasePath, 'zip')
024| Log = logger('ESC')
025| 
026| CMND = ''
027| ARGS = {
028|     #'size': '200000', # output file size
029|     #'steps': '10', # percent steps for add-noise sequences
030|     #'nmode': '9', # -1=no post; 0=normal; 1=no NLs or Tab; 2=no SPCs; 7=7-bit; 8=8-bit;
031|     #'noise': '0.50', # 0.0=NOP; 0.00< = percentage of noise
032|     #'blank': '_', # for blanks; char to use (default: SPC)
033|     #'ndist': '13', # how far to alter a character
034|     #'fillc': 'X', # for blanks; char to use (default: SPC)
035|     #'queue': '0', # 0=NOP; 1=REV; 2=MIX; 3=wordx; 4=noise; 5=rndtxt; 9=TOK
036|     #'wordx': '0', # 0=NOP; 1+ = number of chars to alter
037|     #'minlen':200,
038|     #'maxlen':200,
039| 
040|     #'oname': 'post-016714-tnoise.txt',
041|     #'opath': BasePath,
042|     #'iname': 'shake_hamlet.txt',
043|     #'ipath': BasePath,
044| 
045|     #'zname': 'post-016714-tnoise-m9.zip',
046|     #'zpath': DataPath,
047| 
048|     #'oname': 'img_trees_2400.bmp',
049|     #'opath': BasePath,
050|     #'iname': 'img_trees_2400.png',
051|     #'ipath': BasePath,
052| 
053|     #'c': 'a:inoise nmode={0} steps=20',
054|     #'a1': '0,1,2,3,4,5,6,7,8',
055|     #'a2': '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f',
056| 
057|     #'c': 'txtfile queue=4 noise={0}.{1} wordx=2 ndist=8 iname=input.txt oname=output-4-w2-d8-{0}{1}.txt',
058|     #'a1': '0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1',
059|     #'a2': '00,01,02,05,10,20,30,40,50,60,70,80,90,95,98,99,00',
060| 
061|     #'c': 'txtfile queue=5 noise=0.10 ndist={0} iname=input.txt oname=output-5-010-d{1}.txt',
062|     #'a1': '0,1,2,3,4,5,6,13,25,50,75,99',
063|     #'a2': '00,01,02,03,04,05,06,13,25,50,75,99',
064| 
065|     #'tpath': TextPath,
066|     #'fname': 'test.out',
067|     'fpath': BasePath,
068| }
069| 
070| ##------------------------------------------------------------------------------------------------##
071| Zero = ord('0')
072| UCA = ord('A')
073| LCA = ord('a')
074| 
075| Numbers = [chr(Zero+ix) for ix in range(10)]
076| UpperCase = [chr(UCA+ix) for ix in range(26)]
077| LowerCase = [chr(LCA+ix) for ix in range(26)]
078| Punctuation = list(".,;:!?\"\'\\@#$%&+-*/^=()<>[]{}~`|_")
079| 
080| ##------------------------------------------------------------------------------------------------##
081| RandDigit = lambda: str(randint(0,9))
082| RandDigits = lambda n: [RandDigit() for _ in range(n)]
083| RandFraction = lambda n: f'0.{"".join(RandDigits(n))}...'
084| 
085| 
086| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
087| class ESC:
088|     """Emergent Structural Complexity Calculation class."""
089| 
090|     def __init__ (self, name, compression_list):
091|         """New ESC calculation. Needs a list of numbers."""
092|         self.name = name
093|         self.V = compression_list
094|         self.steps = len(self.V)                        # N+1
095|         self.tot = sum(self.V)                          # Sum of V
096|         self.nmin = min(self.V)                         # Expected to be V[N]
097|         self.nmax = max(self.V)                         # Expected to be V[0]
098|         self.diff = self.nmax - self.nmin               # Difference between V[0] and V[N]
099|         self.fac1 = self.steps * self.nmin              # (N+1)*V[N] - area below min
100|         self.fac2 = self.steps * self.nmax              # (N+1)*V[0] - max area block
101|         self.A = self.tot - self.fac1                   # Area Below Curve
102|         self.B = self.fac2 - self.tot                   # Area Above Curve
103| 
104|         # Absolute Complexity (smallest size)...
105|         self.AC = self.nmin
106|         # Structural Spread (ratio of compression)...
107|         self.SS = (self.diff / self.nmax)
108|         # Emergence Factor (ratio of compression curve)...
109|         self.EF = safediv(self.A, self.B)
110| 
111|         # Final score: Emergent Structural Complexity...
112|         self.ESC = self.AC * self.SS * self.EF
113| 
114|     def __repr__ (self):
115|         s1 = f'{int(self.nmax):,}'
116|         s2 = f'{int(self.AC):,}'
117|         s3 = f'{self.SS:.6f}'
118|         s4 = f'{self.EF:.6f}'
119|         s5 = f'{self.ESC:,.2f}'
120|         return f'{self.name:<16s} {s1:>10s} {s2:>10s} {s3:>8s} {s4:>8s} {s5:>12s}'
121| 
122| 
123| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
124| class CharStripper:
125|     """Strip characters in mask from string."""
126| 
127|     def __init__ (self, mask):
128|         """Initialize with mask chars."""
129|         self.m = [ord(char) for char in mask]
130| 
131|     def __getitem__ (self, key):
132|         """Strip chars in mask, allow all others."""
133|         return (SPC if key in self.m else key)
134| 
135| 
136| ##================================================================================================##
137| def determine_ygrid_spacing (datamax:int) -> tuple[int,int]:
138|     # 0 to 10,000...
139|     if datamax < 10_000: return (5_000, 1_000)
140|     # 10,000 to 50,000...
141|     if datamax < 50_000: return (10_000, 5_000)
142|     # 50,000 to 100,000...
143|     if datamax < 100_000: return (50_000, 10_000)
144|     # 100,000 to 500,000...
145|     if datamax < 500_000: return (100_000, 50_000)
146|     # 500,000 to 1,000,000...
147|     if datamax < 1_000_000: return (500_000, 100_000)
148|     # 1,000,000 to 5,000,000...
149|     if datamax < 5_000_000: return (1_000_000, 500_000)
150|     # 5,000,000 to 10,000,000...
151|     if datamax < 10_000_000: return (5_000_000, 1_000_000)
152|     # 10,000,000 to 50,000,000...
153|     if datamax < 50_000_000: return (10_000_000, 5_000_000)
154|     # 50,000,000 or more...
155|     return (50_000_000, 10_000_000)
156| 
157| ##================================================================================================##
158| def get_ylabel (y_val:int) -> str:
159|     if y_val < 1_000: return str(y_val)
160|     if y_val < 1_000_000: return f'{y_val/1e3:.0f} Kb'
161|     if y_val < 1_000_000_000: return f'{y_val/1e6:.0f} Mb'
162|     return f'{y_val/1e9:.0f} Gb'
163| 
164| ##================================================================================================##
165| def zip_compression_type (n:int) -> str:
166|     if n == ZIP_STORED: return 'Stor'
167|     if n == ZIP_DEFLATED: return 'Defl'
168|     if n == ZIP_BZIP2: return 'BZip'
169|     if n == ZIP_LZMA: return 'LZMA'
170|     raise ValueError(f'Unknown compression type: {n}')
171| 
172| ##================================================================================================##
173| def scramble_word (word:str, num_of_chars:int=1) -> str:
174|     '''\
174| Scramble one or more letters in a word. Preserve case and type.
174| Note this function always alters any word passed to it.
174| Unless num_of_chars=0, in which case it never alters the word.
174| 
174| For a given number (1-N) of randomly selected characters of a word,
174| replace the characters with randomly selected different characters
174| of the same character type. The function alters characters until
174| reaching num_of_chars OR using up all available chars in the word.
174| 
174| Lowercase letters are replaced with different lowercase letters,
174| and likewise for uppercase letters, digits, and punctuation symbols.
174| Each of the four types is replaced with a (guaranteed different)
174| character of the same type (randomly selected).
174| 
174| Parameters:
174|     word:str            -word to randomize
174|     num_of_chars:int    -how many characters to randomize
174| 
174| Returns:
174|     randomized word     (guaranteed same length as input word)
174| '''

175| 
176|     # Break word into characters...
177|     word_list = list(word)
178|     # Create a list of character indexes...
179|     index_list = list(range(len(word)))
180|     # Shuffle the index list...
181|     shuffle(index_list)
182| 
183|     # Alter characters...
184|     for _ in range(num_of_chars):
185|         # Get a (random) character index...
186|         word_ix = index_list.pop()
187|         # Get the character...
188|         ch = word_list[word_ix]
189| 
190|         # Lower Case Character...
191|         if ch in LowerCase:
192|             # Get character's LC index...
193|             ch_ix = LowerCase.index(ch)
194|             rand_ix = ch_ix
195|             # Pick a random LC character different from current one...
196|             while rand_ix == ch_ix:
197|                 rand_ix = randint(0, len(LowerCase)-1)
198|             word_list[word_ix] = LowerCase[rand_ix]
199| 
200|         # Upper Case Character...
201|         elif ch in UpperCase:
202|             # Get character's UC index...
203|             ch_ix = UpperCase.index(ch)
204|             rand_ix = ch_ix
205|             # Pick a random UC character different from current one...
206|             while rand_ix == ch_ix:
207|                 rand_ix = randint(0, len(UpperCase)-1)
208|             word_list[word_ix] = UpperCase[rand_ix]
209| 
210|         # Digits...
211|         elif ch in Numbers:
212|             # Get character's Digit index...
213|             ch_ix = Numbers.index(ch)
214|             rand_ix = ch_ix
215|             # Pick a random Digit character different from current one...
216|             while rand_ix == ch_ix:
217|                 rand_ix = randint(0, len(Numbers)-1)
218|             word_list[word_ix] = Numbers[rand_ix]
219| 
220|         # Punctuation...
221|         elif ch in Punctuation:
222|             # Get character's Punctuation index...
223|             ch_ix = Punctuation.index(ch)
224|             rand_ix = ch_ix
225|             # Pick a random Punctuation character different from current one...
226|             while rand_ix == ch_ix:
227|                 rand_ix = randint(0, len(Punctuation)-1)
228|             word_list[word_ix] = Punctuation[rand_ix]
229| 
230|         # Unexpected character type...
231|         else:
232|             raise RuntimeError(f'Unexpected character: "{ch}"!')
233| 
234|         # If we consumed all the indexes, we're done...
235|         if len(index_list) == 0:
236|             break
237| 
238|     # Return altered word...
239|     return ''.join(word_list)
240| 
241| ##================================================================================================##
242| def scramble_word_sometimes (word:str, noise:float, num_of_chars:int=1) -> str:
243|     '''Scramble word, but only sometimes depending on noise factor.'''
244|     return scramble_word(word,num_of_chars) if random() < noise else word
245| 
246| ##================================================================================================##
247| def add_noise_to_word (word_in:str, noise:float, limit:int=1) -> str:
248|     ''' Randomize character by character.'''
249|     rand_diff = lambda: (-limit + randint(0, limit*2))
250| 
251|     def add_noise (c):
252|         '''Add noise to a character (maybe).'''
253|         if noise < random():
254|             # No noise for this character...
255|             return c
256| 
257|         # Calculate an offset...
258|         cx = ord(c) + rand_diff()
259|         Log.trace(f'# cx={cx:02x}')
260|         # If we went too high, mod us to 7 bits...
261|         if 0x7e < cx:
262|             cx %= 0x80
263|             Log.trace(f'% cx={cx:02x}')
264|         # If we went too low (control chars), shift us to UC alphas...
265|         if cx < ord(SPC):
266|             cx += ord('@')
267|             Log.trace(f'+ cx={cx:02x}')
268|         # Return altered character...
269|         return chr(cx)
270| 
271|     # Add random noise...
272|     word_out = map(add_noise, word_in)
273| 
274|     # Combine chars and return word...
275|     return ''.join(word_out)
276| 
277| 
278| ##================================================================================================##
279| def do_random_data_file (**kwargs):
280|     """CMND: Generate a data file of random bytes.
280| 
280| Parameters:
280|     oname   -output file name incl. path if opath='' ["random-data.txt"]
280|     opath   -output file path or '' [TextPath]
280|     size    -output file size in bytes [100,000]
280|     zero    -minimum random byte value [0]
280| """

281|     opath = KWARG('opath', TextPath, str, kwargs)
282|     oname = KWARG('oname', 'random-data.out', str, kwargs)
283|     size  = KWARG('size', 100000, int, kwargs)
284|     zero  = KWARG('zero', 0, int, kwargs)
285|     Log.info('make-noise-file:: %s' % str(list(kwargs.keys())))
286|     Log.debug(f'{opath=}')
287|     Log.debug(f'{oname=}')
288|     Log.debug(f'{size=}')
289|     Log.debug(f'{zero=}')
290|     Log.info()
291| 
292|     # Generate random characters...
293|     rtxt = [randint(zero,255) for ix in range(size)]
294| 
295|     # Start an output file...
296|     fn = path.join(opath,oname) if opath else oname
297|     fo = datafile(fn)
298| 
299|     # Generate random output...
300|     fo.data = bytes(rtxt)
301| 
302|     # Save output file...
303|     fo.save()
304| 
305|     Log.info()
306|     return 'Done'
307| 
308| ##================================================================================================##
309| def do_random_text_file (**kwargs):
310|     """CMND: Generate a file of random text (using RandomText).
310| 
310| Generated text has paragraph and sentence structure but characters
310| (and digits and punctuation) are chosen randomly.
310| 
310| Parameters:
310|     oname   -output file name incl. path if opath='' ["random-text.txt"]
310|     opath   -output file path or '' [TextPath]
310|     size    -output file size in bytes [100,000]
310|     paras   -number of paragraphs [50]
310|     minpar  -minimum sentences per paragraph [1]
310|     maxpar  -maximum sentences per paragraph [20]
310|     minlin  -minimum words per sentence [2]
310|     maxlin  -maximum words per sentence [17]
310|     minwrd  -minimum characters per word [2]
310|     maxwrd  -maximum characters per word [9]
310| """

311|     opath = KWARG('opath', TextPath, str, kwargs)
312|     oname = KWARG('oname', 'random-text.txt', str, kwargs)
313|     size  = KWARG('size', 100000, int, kwargs)
314|     paras = KWARG('paras', 10, int, kwargs)
315|     minpar = KWARG('minpar',  1, int, kwargs)
316|     maxpar = KWARG('maxpar', 20, int, kwargs)
317|     minlin = KWARG('minlin',  2, int, kwargs)
318|     maxlin = KWARG('maxlin', 17, int, kwargs)
319|     minwrd = KWARG('minwrd',  2, int, kwargs)
320|     maxwrd = KWARG('maxwrd',  9, int, kwargs)
321|     Log.info('make-random-text-file:: %s' % str(list(kwargs.keys())))
322|     Log.debug(f'{opath=}')
323|     Log.debug(f'{oname=}')
324|     Log.debug(f'{paras=}')
325|     Log.debug(f'{minpar=}')
326|     Log.debug(f'{maxpar=}')
327|     Log.debug(f'{minlin=}')
328|     Log.debug(f'{maxlin=}')
329|     Log.debug(f'{minwrd=}')
330|     Log.debug(f'{maxwrd=}')
331|     Log.info()
332|     from randtext import RandomText
333| 
334|     props = dict(
335|         paragraphs=paras,
336|         para_min=minpar, para_max=maxpar,
337|         sent_min=minlin, sent_max=maxlin,
338|         word_min=minwrd, word_max=maxwrd,
339|     )
340|     rt = RandomText(**props)
341| 
342|     content = ['A Long Story\n',EOL]
343|     content_length = 0
344| 
345|     while content_length < size:
346|         sect = rt()
347|         content_length += len(sect)
348|         content.append(sect)
349|         content.append('\n\xa7\n\n')
350|         Log.debug(f'section: {len(sect):,}, count: {len(content)}, total: {content_length:,}')
351| 
352|     content.append('The End')
353|     Log.debug()
354| 
355|     # Save random text file...
356|     fn = path.join(opath,oname) if opath else oname
357|     fo = textfile(fn)
358|     fo.data = ''.join(content)
359|     fo.save()
360| 
361|     Log.info()
362|     return 'Done'
363| 
364| ##================================================================================================##
365| def do_random_words_file (**kwargs):
366|     """CMND: Generate a file of random text (using a word list).
366| 
366| Parameters:
366|     oname   -output file name incl. path if opath='' ["random-words.txt"]
366|     opath   -output file path or '' [TextPath]
366|     size    -output file size in bytes [100,000]
366|     minsec  -minimum paragraphs per section [8]
366|     maxsec  -maximum paragraphs per section [8]
366|     minpar  -minimum sentences per paragraph [3]
366|     maxpar  -maximum sentences per paragraph [12]
366|     minlin  -minimum words per sentence [2]
366|     maxlin  -maximum words per sentence [20]
366| """

367|     opath = KWARG('opath', TextPath, str, kwargs)
368|     oname = KWARG('oname', 'random-words.txt', str, kwargs)
369|     size  = KWARG('size', 100000, int, kwargs)
370|     minsec = KWARG('minsec',  8, int, kwargs)
371|     maxsec = KWARG('maxsec',  8, int, kwargs)
372|     minpar = KWARG('minpar',  3, int, kwargs)
373|     maxpar = KWARG('maxpar', 12, int, kwargs)
374|     minlin = KWARG('minlin',  2, int, kwargs)
375|     maxlin = KWARG('maxlin', 20, int, kwargs)
376|     Log.info('make-random-words-file:: %s' % str(list(kwargs.keys())))
377|     Log.debug(f'{opath=}')
378|     Log.debug(f'{oname=}')
379|     Log.debug(f'{minsec=}')
380|     Log.debug(f'{maxsec=}')
381|     Log.debug(f'{minpar=}')
382|     Log.debug(f'{maxpar=}')
383|     Log.debug(f'{minlin=}')
384|     Log.debug(f'{maxlin=}')
385|     Log.info()
386|     randpunct = lambda: ('.' if 0.05 < random() else ('!' if 0.5 < random() else '?'))
387|     randcount = lambda a,b: int(a + ((b-a) * random()))
388|     plural = lambda n: ('' if n==1 else 's')
389| 
390|     class WordList (list):
391|         '''Load a list of words from a text file.'''
392|         filename = r'C:\CJS\prj\Python\app\dat\words.list'
393| 
394|         def __init__ (self):
395|             fo = linefile(WordList.filename)
396|             fo.load()
397|             self.extend(fo.data)
398|             Log.info(f'loaded: {len(self)} word{plural(len(self))}')
399| 
400|     Words = WordList()
401| 
402|     def get_word (word_index=1) -> str:
403|         '''Return a random word.'''
404|         for _ in range(10):
405|             w = choice(Words)
406|             if word_index or not w.isnumeric():
407|                 break
408|         return w
409| 
410|     def get_sentence () -> str:
411|         '''Return a sentence of random words.'''
412|         nw = randcount(minlin, maxlin)
413|         ws = [get_word(ix) for ix in range(nw)]
414|         ws[0] = f'{ws[0][0].upper()}{ws[0][1:]}'
415|         ws[-1] = f'{ws[-1]}{randpunct()}'
416|         return SPC.join(ws)
417| 
418|     def get_paragraph () -> str:
419|         '''Return a paragraph of random sentences.'''
420|         ns = randcount(minpar, maxpar)
421|         ss = [get_sentence() for ix in range(ns)]
422|         ss[-1] = f'{ss[-1]}\n'
423|         return SPC.join(ss)
424| 
425|     def get_section () -> str:
426|         '''Return a section of random paragraphs.'''
427|         np = randcount(minsec, maxsec)
428|         ps = [get_paragraph() for ix in range(np)]
429|         ps[-1] = f'{ps[-1]}\n\xa7\n\n'
430|         return EOL.join(ps)
431| 
432|     content = ['A Long Story\n',EOL]
433|     content_length = 0
434| 
435|     while content_length < size:
436|         sect = get_section()
437|         content_length += len(sect)
438|         content.append(sect)
439|         Log.debug(f'section: {len(sect):,}, count: {len(content)}, total: {content_length:,}')
440|     content.append('The End')
441|     Log.debug()
442| 
443|     # Save random words text file...
444|     fn = path.join(opath, oname) if opath else oname
445|     fo = textfile(fn)
446|     fo.data = ''.join(content)
447|     fo.save()
448| 
449|     Log.info()
450|     return 'Done'
451| 
452| ##================================================================================================##
453| def do_random_chars_file (**kwargs):
454|     """CMND: Generate a file of random characters from a character set.
454| 
454| Parameters:
454|     oname   -output file name incl. path if opath='' ["random-bits.txt"]
454|     opath   -output file path or '' [TextPath]
454|     size    -output file size in bytes [100,000]
454|     fillc   -character(s) to use randomly as "bits" ["01"]
454|     minlen  -minimum line length [100]
454|     maxlen  -maximum line length [100]
454| """

455|     opath = KWARG('opath', TextPath, str, kwargs)
456|     oname = KWARG('oname', 'random-bits.txt', str, kwargs)
457|     size  = KWARG('size', 100000, int, kwargs)
458|     fillc = KWARG('fillc', '01', str, kwargs)
459|     minlen = KWARG('minlen', 100, int, kwargs)
460|     maxlen = KWARG('maxlen', 100, int, kwargs)
461|     Log.info('make-lines-of-bits-file:: %s' % str(list(kwargs.keys())))
462|     Log.debug(f'{opath=}')
463|     Log.debug(f'{oname=}')
464|     Log.debug(f'{size=}')
465|     Log.debug(f'{fillc=}')
466|     Log.debug(f'{minlen=}')
467|     Log.debug(f'{maxlen=}')
468|     Log.info()
469|     total_chars = size
470| 
471|     # Start an output file...
472|     fn = path.join(opath,oname) if opath else oname
473|     fo = linefile(fn)
474| 
475|     while 0 < total_chars:
476|         # Pick a random length for the line...
477|         line_length = randint(minlen, maxlen)
478| 
479|         # Generate a line with that many chars...
480|         line_content = [choice(fillc) for _ in range(line_length)]
481| 
482|         # Deduct the length of this line (incl NL)...
483|         total_chars -= (line_length + 1)
484| 
485|         # Add this line to the output...
486|         fo.add(''.join(line_content))
487| 
488|     # Output has a blank line at bottom...
489|     fo.add()
490| 
491|     # Save output file...
492|     fo.save()
493| 
494|     Log.info()
495|     return 'Done'
496| 
497| ##================================================================================================##
498| def do_random_lines_file (**kwargs):
499|     """CMND: Generate a file of random-length blank lines (w/ definable blank).
499| 
499| Parameters:
499|     oname   -output file name incl. path if opath='' ["blank-lines.txt"]
499|     opath   -output file path or '' [TextPath]
499|     size    -output file size in bytes [100,000]
499|     fillc   -character(s) to use as "blanks" [" "]
499|     minlen  -minimum line length [45]
499|     maxlen  -maximum line length [90]
499| """

500|     opath = KWARG('opath', TextPath, str, kwargs)
501|     oname = KWARG('oname', 'blank-lines.txt', str, kwargs)
502|     size  = KWARG('size', 100000, int, kwargs)
503|     fillc = KWARG('fillc', SPC, str, kwargs)
504|     minlen = KWARG('minlen', 45, int, kwargs)
505|     maxlen = KWARG('maxlen', 90, int, kwargs)
506|     Log.info('make-blank-lines-file:: %s' % str(list(kwargs.keys())))
507|     Log.debug(f'{opath=}')
508|     Log.debug(f'{oname=}')
509|     Log.debug(f'{size=}')
510|     Log.debug(f'{fillc=}')
511|     Log.debug(f'{minlen=}')
512|     Log.debug(f'{maxlen=}')
513|     Log.info()
514|     total_chars = size
515| 
516|     # Start an output file...
517|     fn = path.join(opath,oname) if opath else oname
518|     fo = linefile(fn)
519| 
520|     while 0 < total_chars:
521|         # Pick a random length for the line...
522|         line_length = randint(minlen, maxlen)
523| 
524|         # Generate a line with that many chars...
525|         line_content = fillc * line_length
526| 
527|         # Deduct the length of this line (incl NL)...
528|         total_chars -= (len(line_content) + 1)
529| 
530|         # Add this line to the output...
531|         fo.add(line_content)
532| 
533|     # Output has a blank line at bottom...
534|     fo.add()
535| 
536|     # Save output file...
537|     fo.save()
538| 
539|     Log.info()
540|     return 'Done'
541| 
542| ##================================================================================================##
543| def do_hamlet_scramble (**kwargs):
544|     """CMND: Scan Hamlet and create a randomized-by-word version.
544| 
544| Parameters:
544|     iname   -input file name incl. path if opath='' ["shake_hamlet.txt"]
544|     oname   -output file name incl. path if opath='' ["shake_hamlet-out.txt"]
544|     ipath   -input file path or '' [DataPath]
544|     opath   -output file path or '' [TextPath]
544|     tpath   -template file path or '' [DataPath]
544|     queue   -word queue modes [0]
544|     wordx   -characters to alter in modes 3 and 4 [0]
544|     noise   -percentage of noise for modes 4 and 5 [0.10]
544|     ndist   -noise shift distance for mode 5 [1]
544| 
544| queue Modes:
544|     0       -NOP: (do nothing to queues)
544|     1       -REV: reverse the word queues
544|     2       -shuffle the word queues
544|     3       -randomize words (all words; wordx=nbr_of_chars)
544|     4       -randomize words (only some words per noise)
544|     5       -add noise on a character-by-character basis
544|     9       -TOK: use only WORD (and NAME) tokens
544| """

545|     ipath = KWARG('ipath', DataPath, str, kwargs)
546|     opath = KWARG('opath', TextPath, str, kwargs)
547|     tpath = KWARG('tpath', DataPath, str, kwargs)
548|     iname = KWARG('iname', 'shake_hamlet.txt', str, kwargs)
549|     oname = KWARG('oname', 'shake_hamlet-out.txt', str, kwargs)
550|     queue = KWARG('queue', 0, int, kwargs)
551|     wordx = KWARG('wordx', 0, int, kwargs)
552|     noise = KWARG('noise', 0.10, float, kwargs)
553|     ndist = KWARG('ndist', 1, int, kwargs)
554|     Log.info('scramble-hamlet:: %s' % str(list(kwargs.keys())))
555|     Log.debug(f'{ipath=}')
556|     Log.debug(f'{opath=}')
557|     Log.debug(f'{tpath=}')
558|     Log.debug(f'{iname=}')
559|     Log.debug(f'{oname=}')
560|     Log.debug(f'{queue=}')
561|     Log.debug(f'{wordx=}')
562|     Log.debug(f'{noise=}')
563|     Log.debug(f'{ndist=}')
564|     Log.info()
565| 
566|     temptext = ''           # output buffer
567|     marker_word = '{*}'     # word marker
568|     marker_name = '{@}'     # name marker
569|     words = []              # list of found words
570|     names = []              # list of found names
571|     word = ''               # buffer for building a word/name
572|     state = 0               # 0=not in a word; 1=in a word/name
573| 
574|     # Open and load the source file...
575|     fni = path.join(ipath,iname) if ipath else iname
576|     fi = textfile(fni)
577|     fi.load()
578|     Log.info()
579| 
580|     # Scan source text for names and words...
581|     for ch in fi.data:
582| 
583|         # State: either in or not in a word/name...
584|         match state:
585|             # Not in a word...
586|             case 0:
587|                 if ch.isalnum() or (ch == "'"):
588|                     # Start word...
589|                     word = ch
590|                     state = 1
591|                 else:
592|                     # Add char to the output...
593|                     temptext += ch
594| 
595|             # In a word...
596|             case 1:
597|                 if ch.isalnum() or (ch == "'"):
598|                     # Still in a word...
599|                     word += ch
600|                 else:
601|                     # Out of word...
602|                     if word.isupper() and (1 < len(word)):
603|                         # Word is a name...
604|                         names.append(word)
605|                         temptext += marker_name
606|                     else:
607|                         # Ordinary word...
608|                         words.append(word)
609|                         temptext += marker_word
610| 
611|                     # Add the non-word character to output...
612|                     temptext += ch
613|                     state = 0
614| 
615|     Log.info(f'names: {len(names)}')
616|     Log.info(f'words: {len(words)}')
617|     Log.info(f'longest-name: {max(len(w) for w in names)} chars')
618|     Log.info(f'longest-word: {max(len(w) for w in words)} chars')
619|     Log.info()
620| 
621|     # Save the template file...
622|     name_ext = path.splitext(path.split(fni)[1])
623|     tname = f'{name_ext[0]}-tmplt.out'
624|     fnt = path.join(tpath,tname) if tpath else path.join(ipath,tname)
625|     ft = textfile(fnt)
626|     ft.data = temptext
627|     ft.save()
628|     Log.info()
629| 
630|     # Save the words file...
631|     wname = f'{name_ext[0]}-words.out'
632|     fnw = path.join(tpath,wname) if tpath else path.join(ipath,wname)
633|     fw = linefile(fnw)
634|     fw.data = list(sorted({n for n in names}))
635|     fw.data.append('')
636|     fw.data.extend(sorted({w for w in words}))
637|     fw.save()
638| 
639|     # Modify the word and name queues...
640|     match queue:
641|         # (0|else: Leave words in order.)
642|         case 1:
643|             # Reverse words and names...
644|             names.reverse()
645|             words.reverse()
646|         case 2:
647|             # Shuffle words and names...
648|             shuffle(names)
649|             shuffle(words)
650|         case 3:
651|             # Apply wordx scrambling (to all words and names!)...
652|             names = [scramble_word(name,wordx) for name in names]
653|             words = [scramble_word(word,wordx) for word in words]
654|         case 4:
655|             # Apply wordx scrambling controlled by noise...
656|             xword = 1 if wordx == 0 else wordx
657|             names = [scramble_word_sometimes(name,noise,xword) for name in names]
658|             words = [scramble_word_sometimes(word,noise,xword) for word in words]
659|         case 5:
660|             # Apply noise (with random differential) on character basis...
661|             names = [add_noise_to_word(name,noise,ndist) for name in names]
662|             words = [add_noise_to_word(word,noise,ndist) for word in words]
663|         case 9:
664|             # Replace words and names with tokens...
665|             names = ['NAME' for _ in names]
666|             words = ['word' for _ in words]
667| 
668|     # Create an output file...
669|     fnr = path.join(opath,oname) if opath else oname
670|     fr = textfile(fnr)
671| 
672|     # Build the output by replacing markers with random words/names...
673|     ix = 0
674|     while ix < len(temptext):
675|         # Name or Word marker...
676|         if temptext[ix] == '{':
677| 
678|             # Name marker...
679|             if temptext[ix:ix+3] == marker_name:
680|                 fr.data += names.pop(0)
681|                 ix += 3
682|                 continue
683| 
684|             # Word marker...
685|             if temptext[ix:ix+3] == marker_word:
686|                 fr.data += words.pop(0)
687|                 ix += 3
688|                 continue
689| 
690|             # Unable to identify marker type...
691|             raise RuntimeError('Unexpected marker!')
692| 
693|         # Not a word or name...
694|         fr.data += temptext[ix]
695|         ix += 1
696| 
697|     # Save the output file...
698|     fr.save()
699|     Log.info()
700| 
701|     # Both lists should be empty now...
702|     Log.info(f'names: {len(names)} (should be zero!)')
703|     Log.info(f'words: {len(words)} (ditto)')
704| 
705|     Log.info()
706|     return 'Done'
707| 
708| ##================================================================================================##
709| def do_txtfile_scramble (**kwargs):
710|     """CMND: Scan text file and create a randomized-by-word version.
710| 
710| Parameters:
710|     iname   -input file name incl. path if opath='') ["command.txt"]
710|     oname   -output file name incl. path if opath='' ["command-out.txt"]
710|     ipath   -input file path or '' [DataPath]
710|     opath   -output file path or '' [TextPath]
710|     tpath   -template file path or '' [DataPath]
710|     queue   -word queue modes [0]
710|     wordx   -characters to alter in modes 3 and 4 [0]
710|     noise   -percentage of noise for modes 4 and 5 [0.10]
710|     ndist   -noise shift distance for mode 5 [1]
710| 
710| queue codes:
710|     0       -NOP: (do nothing to queue)
710|     1       -REV: reverse the word queue
710|     2       -shuffle the word queue
710|     3       -randomize words (all words; wordx=nbr_of_chars)
710|     4       -randomize words (only some words per noise)
710|     5       -add noise on a character-by-character basis
710|     9       -TOK: use only WORD (and NAME) tokens
710| """

711|     ipath = KWARG('ipath', DataPath, str, kwargs)
712|     opath = KWARG('opath', TextPath, str, kwargs)
713|     tpath = KWARG('tpath', DataPath, str, kwargs)
714|     iname = KWARG('iname', 'command.txt', str, kwargs)
715|     oname = KWARG('oname', 'command-out.txt', str, kwargs)
716|     queue = KWARG('queue', 0, int, kwargs)
717|     wordx = KWARG('wordx', 0, int, kwargs)
718|     noise = KWARG('noise', 0.10, float, kwargs)
719|     ndist = KWARG('ndist', 1, int, kwargs)
720|     Log.info('scramble-textfile:: %s' % str(list(kwargs.keys())))
721|     Log.debug(f'{ipath=}')
722|     Log.debug(f'{opath=}')
723|     Log.debug(f'{tpath=}')
724|     Log.debug(f'{iname=}')
725|     Log.debug(f'{oname=}')
726|     Log.debug(f'{queue=}')
727|     Log.debug(f'{wordx=}')
728|     Log.debug(f'{noise=}')
729|     Log.debug(f'{ndist=}')
730|     Log.info()
731| 
732|     temptext = ''           # output buffer
733|     marker = '{*}'          # word marker
734|     words = []              # list of found words
735|     word = ''               # buffer for building a word/name
736|     state = 0               # 0=not in a word; 1=in a word/name
737| 
738|     # Open and load the source file...
739|     fni = path.join(ipath,iname) if ipath else iname
740|     fi = textfile(fni)
741|     fi.load()
742|     Log.info()
743| 
744|     # Scan source text for words...
745|     for ch in fi.data:
746| 
747|         # State: either in or not in a word...
748|         match state:
749|             # Not in a word...
750|             case 0:
751|                 if ch.isalnum() or (ch == "'"):
752|                     # Start word...
753|                     word = ch
754|                     state = 1
755|                 else:
756|                     # Add char to the template...
757|                     temptext += ch
758| 
759|             # In a word...
760|             case 1:
761|                 if ch.isalnum() or (ch == "'"):
762|                     # Still in a word...
763|                     word += ch
764|                 else:
765|                     # Out of word...
766|                     words.append(word)
767|                     temptext += marker
768|                     # Add the non-word character to output...
769|                     temptext += ch
770|                     state = 0
771| 
772|     Log.info(f'words: {len(words)}')
773|     Log.info(f'longest-word: {max(len(w) for w in words)} chars')
774|     Log.info()
775| 
776|     # Save the template file...
777|     name_ext = path.splitext(path.split(fni)[1])
778|     tname = f'{name_ext[0]}-tmplt.out'
779|     fnt = path.join(tpath,tname) if tpath else path.join(ipath,tname)
780|     ft = textfile(fnt)
781|     ft.data = temptext
782|     ft.save()
783| 
784|     # Save the words file...
785|     wname = f'{name_ext[0]}-words.out'
786|     fnw = path.join(tpath,wname) if tpath else path.join(ipath,wname)
787|     fw = linefile(fnw)
788|     fw.data = list(sorted({w for w in words}))
789|     fw.save()
790| 
791|     # Modify the words queue...
792|     match queue:
793|         # (0|else: Leave words in order.)
794|         case 1:
795|             # Reverse words...
796|             words.reverse()
797|         case 2:
798|             # Shuffle words...
799|             shuffle(words)
800|         case 3:
801|             # Apply wordx scrambling (to all words!)...
802|             words = [scramble_word(word,wordx) for word in words]
803|         case 4:
804|             # Apply wordx scrambling controlled by noise...
805|             xword = 1 if wordx == 0 else wordx
806|             words = [scramble_word_sometimes(word,noise,xword) for word in words]
807|         case 5:
808|             # Apply noise (with random differential) on character basis...
809|             words = [add_noise_to_word(word,noise,ndist) for word in words]
810|         case 9:
811|             # Replace words with tokens...
812|             words = ['word' for _ in words]
813| 
814|     # Create an output file...
815|     fnr = path.join(opath,oname) if opath else oname
816|     fr = textfile(fnr)
817| 
818|     # Build the output by replacing markers with random words...
819|     ix = 0
820|     while ix < len(temptext):
821|         # Name or Word marker...
822|         if (temptext[ix] == '{') and (temptext[ix:ix+3] == marker):
823|             fr.data += words.pop(0)
824|             ix += 3
825|             continue
826| 
827|         # Not a word...
828|         fr.data += temptext[ix]
829|         ix += 1
830| 
831|     # Save the output file...
832|     fr.save()
833|     Log.info()
834| 
835|     # Word list should be empty now...
836|     Log.info(f'words: {len(words)} (should be zero!)')
837|     Log.info()
838| 
839|     Log.info()
840|     return 'Done'
841| 
842| ##================================================================================================##
843| def do_text_add_noise (**kwargs):
844|     """\
844| CMND: Add noise to a text file. (TNOISE)
844| 
844| Parameters:
844|     iname   -input file name incl. path if opath=''
844|     oname   -output file name incl. path if opath=''
844|     ipath   -input file path or '' [DataPath]
844|     opath   -output file path or '' [TextPath]
844|     nmode   -noise modes (see below) [0]
844|     noise   -percentage of noise [0.10]
844|     ndist   -noise shift distance [13]
844| 
844| nmode codes:
844|    -1 - scramble all characters
844|     0 - scramble all characters (with safety processing)
844|    +1 - (ditto) except NLs and Tabs
844|    +2 - (ditto) and spaces
844|    +7 - scramble all: return random 7-bit characters
844|    +8 - scramble all: return random 8-bit characters
844|    +9 - return blank characters for non-WS
844| """

845|     ipath = KWARG('ipath', DataPath, str, kwargs)
846|     opath = KWARG('opath', TextPath, str, kwargs)
847|     iname = KWARG('iname', 'input.txt', str, kwargs)
848|     oname = KWARG('oname', 'output.txt', str, kwargs)
849|     nmode = KWARG('nmode', 0, int, kwargs)
850|     noise = KWARG('noise', 0.10, float, kwargs)
851|     ndist = KWARG('ndist', 13, int, kwargs)
852|     blank = KWARG('blank', SPC, str, kwargs)
853|     Log.info('add-noise-to-text:: %s' % str(list(kwargs.keys())))
854|     Log.debug(f'{ipath=}')
855|     Log.debug(f'{opath=}')
856|     Log.debug(f'{iname=}')
857|     Log.debug(f'{oname=}')
858|     Log.debug(f'{nmode=}')
859|     Log.debug(f'{noise=}')
860|     Log.debug(f'{ndist=}')
861|     Log.debug(f'{blank=}')
862|     Log.info()
863|     rand_diff = lambda: (-ndist + randint(0, ndist*2))
864|     ws_test = lambda ch: (ch in '\r\n\f\t')
865|     CCB = ord('@') # Control Character Base
866| 
867|     def add_noise (char):
868|         '''Add random noise to a character (sometimes).'''
869|         if noise < random(): return char
870| 
871|         # Mode 7: Return any 7-bit random character...
872|         if nmode == 7: return chr(randint(0,127))
873| 
874|         # Mode 8: Return any 8-bit random character...
875|         if nmode == 8: return chr(randint(0,255))
876| 
877|         # Mode 9: Return blanks (spaces by default)...
878|         if nmode == 9: return (char if ws_test(char) else blank)
879| 
880|         # Mode 1+: Don't alter certain control characters...
881|         if (1 <= nmode) and ws_test(char): return char
882|         # Mode 2+: Also don't alter spaces...
883|         if (2 <= nmode) and char.isspace(): return char
884| 
885|         # Generate a scrambled character (with a given possible delta)...
886|         cx = abs(ord(char) + rand_diff())
887|         if nmode < 0: return chr(cx)
888|         # If we went up into Unicode territory, back off...
889|         if 0x7f < cx: cx &= 0x7f
890|         # If we went down into control-code territory, convert to alpha...
891|         if cx < ord(SPC): cx += CCB
892|         # Return scrambled character...
893|         return chr(cx)
894| 
895|     # Open and load input text file...
896|     fni = path.join(ipath,iname) if ipath else iname
897|     fi = textfile(fni)
898|     fi.load()
899|     Log.info()
900| 
901|     # Feed input text through noise to output text (list of chars)...
902|     chs = list(map(add_noise, fi.data))
903| 
904|     # Open and save output text file...
905|     fno = path.join(opath,oname) if opath else oname
906|     fo = textfile(fno)
907|     fo.data = ''.join(chs)
908|     fo.save()
909|     Log.info()
910| 
911|     Log.info()
912|     return 'Done'
913| 
914| ##================================================================================================##
915| def do_data_add_noise (**kwargs):
916|     """CMND: Add noise to a data (8-bit byte) file. (DNOISE)
916| 
916| Parameters:
916|     iname   -input file name incl. path if opath=''
916|     oname   -output file name incl. path if opath=''
916|     ipath   -input file path or '' [DataPath]
916|     opath   -output file path or '' [TextPath]
916|     nmode   -noise modes [0]
916|     noise   -percentage of noise [0.10]
916| 
916| nmode codes:
916|     0 - scramble all characters
916|    +1 - (ditto) except NLs and Tabs
916|    +2 - (ditto) and spaces
916|    +9 - return blanks (blank; zero by default)
916| """

917|     ipath = KWARG('ipath', DataPath, str, kwargs)
918|     opath = KWARG('opath', TextPath, str, kwargs)
919|     iname = KWARG('iname', 'input.dat', str, kwargs)
920|     oname = KWARG('oname', 'output.dat', str, kwargs)
921|     nmode = KWARG('nmode', 0, int, kwargs)
922|     noise = KWARG('noise', 0.10, float, kwargs)
923|     blank = KWARG('blank', 0, int, kwargs)
924|     Log.info('add-noise-to-datafile:: %s' % str(list(kwargs.keys())))
925|     Log.debug(f'{ipath=}')
926|     Log.debug(f'{opath=}')
927|     Log.debug(f'{iname=}')
928|     Log.debug(f'{oname=}')
929|     Log.debug(f'{nmode=}')
930|     Log.debug(f'{noise=}')
931|     Log.debug(f'{blank=:x}')
932|     Log.info()
933| 
934|     def add_noise (datum):
935|         '''Add random noise to a data byte (sometimes).'''
936|         if noise < random(): return datum
937| 
938|         # Mode 9: Return blanks (0 by default)...
939|         if nmode == 9: return blank
940| 
941|         # Mode 1+: Don't alter certain control characters...
942|         if (1 <= nmode) and (datum in [9,10,11,12,13]): return datum
943|         # Mode 2+: Also don't alter spaces...
944|         if (2 <= nmode) and (datum == ord(SPC)): return datum
945| 
946|         # Return random byte...
947|         return randint(0,255)
948| 
949|     # Open and load input text file...
950|     fni = path.join(ipath,iname) if ipath else iname
951|     fi = datafile(fni)
952|     fi.load()
953| 
954|     # Open output text file...
955|     fno = path.join(opath,oname) if opath else oname
956|     fo = datafile(fno)
957| 
958|     # Feed input text through noise to output text (list of chars)...
959|     fo.data = bytes(map(add_noise, fi.data))
960| 
961|     # Save output file...
962|     fo.save()
963| 
964|     Log.info()
965|     return 'Done'
966| 
967| ##================================================================================================##
968| def do_image_add_noise (**kwargs):
969|     """CMND: Add noise to an image.
969| 
969| Parameters:
969|     iname   -input file name incl. path if opath=''
969|     oname   -output file name incl. path if opath=''
969|     ipath   -input file path or '' [DataPath]
969|     opath   -output file path or '' [ImgsPath]
969|     nmode   -noise modes [0]
969|     noise   -percentage of noise [0.50]
969| 
969| nmode codes; randomly change pixels to:
969|     0       -random color pixels (default)
969|     1       -random grayscale pixels
969|     2       -black pixels
969|     3       -gray pixels
969|     4       -white pixels
969|     5       -fade pixels to black
969|     6       -fade pixels to gray
969|     7       -fade pixels to white
969|     8       -random perturbing
969| """

970|     ipath = KWARG('ipath', DataPath, str, kwargs)
971|     opath = KWARG('opath', ImgsPath, str, kwargs)
972|     iname = KWARG('iname', 'image.png', str, kwargs)
973|     oname = KWARG('oname', '', str, kwargs)
974|     nmode = KWARG('nmode', 0, int, kwargs)
975|     noise = KWARG('noise', 0.50, float, kwargs)
976|     Log.info('make-one-randomized-image:: %s' % str(list(kwargs.keys())))
977|     Log.debug(f'{ipath=}')
978|     Log.debug(f'{opath=}')
979|     Log.debug(f'{iname=}')
980|     Log.debug(f'{oname=}')
981|     Log.debug(f'{nmode=}')
982|     Log.debug(f'{noise=}')
983|     Log.info()
984|     rand_color_pixel = lambda: (randint(0,255), randint(0,255), randint(0,255))
985|     rand_gray_pixel = lambda: (randint(0,255),)*3
986| 
987|     def noise_mode_8 (pixel):
988|         """Randomize pixels proportionately."""
989|         randpix = rand_color_pixel()
990|         r = int((pixel[0] * (1.0-noise)) + (randpix[0] * noise))
991|         g = int((pixel[1] * (1.0-noise)) + (randpix[1] * noise))
992|         b = int((pixel[2] * (1.0-noise)) + (randpix[2] * noise))
993|         return (r, g, b)
994| 
995|     noise_functions = [
996|         lambda pixel: rand_color_pixel() if random() < noise else pixel,
997|         lambda pixel: rand_gray_pixel() if random() < noise else pixel,
998|         lambda pixel: (0,0,0) if random() < noise else pixel,
999|         lambda pixel: (127,127,127) if random() < noise else pixel,
1000|         lambda pixel: (255,255,255) if random() < noise else pixel,
1001|         lambda pixel: tuple(c+int((  0-c)*noise) for c in pixel),
1002|         lambda pixel: tuple(c+int((127-c)*noise) for c in pixel),
1003|         lambda pixel: tuple(c+int((255-c)*noise) for c in pixel),
1004|         noise_mode_8,
1005|     ]
1006| 
1007|     fn,ext = path.splitext(oname if oname else iname)
1008|     spct = f'{noise:.2f}'.replace('.','')
1009|     oname = f'{fn}_m{nmode}-n{spct}{ext}'
1010|     Log.trace(f'{oname=}')
1011|     Log.trace()
1012| 
1013|     fn0 = path.join(ipath,iname) if ipath else iname
1014|     fn1 = path.join(opath,oname) if opath else oname
1015|     Log.trace(f'{fn0=}')
1016|     Log.trace(f'{fn1=}')
1017|     Log.trace()
1018| 
1019|     # Open the source image...
1020|     img0 = Image.open(fn0)
1021|     dat0 = img0.getdata()
1022|     Log.info(fn0)
1023|     Log.info(img0.mode)
1024|     Log.info(img0.size)
1025|     Log.info()
1026| 
1027|     # Add Noise to Image. Replace random pixels with random values...
1028|     func = noise_functions[nmode]
1029|     dat1 = [func(pixel) for pixel in dat0]
1030| 
1031|     # Create and save the destination image...
1032|     img1 = Image.new(img0.mode, img0.size)
1033|     img1.putdata(dat1)
1034|     img1.save(fn1)
1035|     Log.info(fn1)
1036|     Log.info(img1.mode)
1037|     Log.info(img1.size)
1038|     Log.info()
1039| 
1040|     # Get the image file sizes...
1041|     size0 = path.getsize(fn0)
1042|     size1 = path.getsize(fn1)
1043| 
1044|     Log.info(f'Src Image Filesize: {size0:9d}')
1045|     Log.info(f'Dst Image Filesize: {size1:9d}')
1046|     Log.info(f'Dst/Src Ratio: {(size1/size0):.6f}')
1047|     Log.info()
1048|     return 'Done'
1049| 
1050| ##================================================================================================##
1051| def scramble_image (image, xmin,xmax, ymin,ymax, depth=0, level=0):
1052|     '''Recursive image scrambler. (min="0", max="size")'''
1053|     if 0 < depth <= level:
1054|         return
1055|     xsize = xmax - xmin
1056|     ysize = ymax - ymin
1057|     xhalf = xsize // 2
1058|     yhalf = ysize // 2
1059|     Log.debug(f'scramble_image({xmin},{xmax}, {ymin},{ymax}, {depth}, {level})')
1060|     Log.debug(f'{xsize=}, {ysize=}')
1061|     Log.debug(f'{xhalf=}, {yhalf=}')
1062| 
1063|     if xsize < 2:
1064|         # Less than two X dimensions...
1065|         return
1066| 
1067|     if ysize < 2:
1068|         # Less than two Y dimensions...
1069|         return
1070| 
1071|     # First, swap coordinates in quadrants...
1072|     for xx in range(xhalf):
1073|         for yy in range(ysize):
1074|             # Current pixel...
1075|             px = xmin + xx
1076|             py = ymin + yy
1077| 
1078|             # Pixel from other quadrant...
1079|             tx = xmin + ((xx+xhalf) if xx < xhalf else (xx-xhalf))
1080|             ty = ymin + ((yy+yhalf) if yy < yhalf else (yy-yhalf))
1081| 
1082|             # Swap cell with opposing diagonal...
1083|             Log.trace(f'Swap: [{px}][{py}] <=> [{tx}][{ty}]')
1084|             temp = image[px][py]
1085|             image[px][py] = image[tx][ty]
1086|             image[tx][ty] = temp
1087| 
1088|     # Second, recurse on each quadrant...
1089|     # Upper left...
1090|     scramble_image(image, xmin      , xmin+xhalf, ymin      , ymin+yhalf, depth=depth, level=level+1)
1091|     # Upper right...
1092|     scramble_image(image, xmin+xhalf, xmin+xsize, ymin      , ymin+yhalf, depth=depth, level=level+1)
1093|     # Lower left...
1094|     scramble_image(image, xmin      , xmin+xhalf, ymin+yhalf, ymin+ysize, depth=depth, level=level+1)
1095|     # Lower right...
1096|     scramble_image(image, xmin+xhalf, xmin+xsize, ymin+yhalf, ymin+ysize, depth=depth, level=level+1)
1097| 
1098|     return
1099| 
1100| ##================================================================================================##
1101| def do_scramble_image_file (**kwargs):
1102|     """CMND: Scramble the pixels in an image file."""
1103|     ipath = KWARG('ipath', DataPath, str, kwargs)
1104|     opath = KWARG('opath', ImgsPath, str, kwargs)
1105|     iname = KWARG('iname', 'image.png', str, kwargs)
1106|     oname = KWARG('oname', '', str, kwargs)
1107|     depth = KWARG('steps', 0, int, kwargs)
1108|     Log.info('scramble-image:: %s' % str(list(kwargs.keys())))
1109|     Log.debug(f'{ipath=}')
1110|     Log.debug(f'{opath=}')
1111|     Log.debug(f'{iname=}')
1112|     Log.debug(f'{oname=}')
1113|     Log.debug(f'{depth=}')
1114|     Log.info()
1115| 
1116|     fn,ext = path.splitext(oname if oname else iname)
1117|     oname = f'{fn}-c{depth}.bmp'
1118|     Log.trace(f'{oname=}')
1119|     Log.trace()
1120| 
1121|     fn0 = path.join(ipath,iname) if ipath else iname
1122|     fn1 = path.join(opath,oname) if opath else oname
1123|     Log.trace(f'{fn0=}')
1124|     Log.trace(f'{fn1=}')
1125|     Log.trace()
1126| 
1127|     # Open the source image...
1128|     img0 = Image.open(fn0)
1129|     dat0 = img0.getdata()
1130|     Log.info(fn0)
1131|     Log.info(img0.mode)
1132|     Log.info(img0.size)
1133|     Log.info(len(dat0))
1134|     Log.info()
1135| 
1136|     pixels = iter(dat0)
1137|     matrix = [
1138|         [next(pixels) for _ in range(img0.size[0])]
1139|         for _ in range(img0.size[1])
1140|     ]
1141|     scramble_image(matrix, 0,img0.size[1], 0,img0.size[0], depth=depth)
1142| 
1143|     dat1 = []
1144|     for ix in range(img0.size[1]):
1145|         row = [matrix[ix][iy] for iy in range(img0.size[0])]
1146|         dat1.extend(row)
1147|     Log.info(len(dat1))
1148| 
1149|     # Create and save the destination image...
1150|     img1 = Image.new(img0.mode, img0.size)
1151|     img1.putdata(dat1)
1152|     img1.save(fn1)
1153|     Log.info(fn1)
1154|     Log.info(img1.mode)
1155|     Log.info(img1.size)
1156|     Log.info()
1157| 
1158|     # Get the image file sizes...
1159|     size0 = path.getsize(fn0)
1160|     size1 = path.getsize(fn1)
1161| 
1162|     Log.info(f'Src Image Filesize: {size0:9d}')
1163|     Log.info(f'Dst Image Filesize: {size1:9d}')
1164|     Log.info(f'Dst/Src Ratio: {(size1/size0):.6f}')
1165|     Log.info()
1166|     return 'Done'
1167| 
1168| ##================================================================================================##
1169| def do_list_zip_file (**kwargs):
1170|     """CMND: List a ZIP file information to a TAB file.
1170| 
1170| Parameters:
1170|     zname   -ZIP file name incl. path if zpath=''
1170|     zpath   -ZIP file path or '' [ZipsPath]
1170|     opath   -output file path or '' [""]
1170| """

1171|     zpath = KWARG('zpath', ZipsPath, str, kwargs)
1172|     opath = KWARG('opath', '', str, kwargs)
1173|     zname = KWARG('zname', 'test.zip', str, kwargs)
1174|     Log.info('list-zip-file:: %s' % str(list(kwargs.keys())))
1175|     Log.debug(f'{zpath=}')
1176|     Log.debug(f'{opath=}')
1177|     Log.debug(f'{zname=}')
1178|     Log.info()
1179| 
1180|     # Open the ZIP file...
1181|     fnz = path.join(zpath,zname) if zpath else zname
1182|     zf = ZipFile(fnz)
1183|     Log.info(f'opened: {fnz}')
1184|     Log.info()
1185| 
1186|     # List the filenames...
1187|     for ix,name in enumerate(zf.namelist(), start=1):
1188|         Log.trace(f'{ix:2d}: {name}')
1189|     Log.trace()
1190| 
1191|     # List the details...
1192|     for ix,zi in enumerate(zf.infolist(), start=1):
1193|         sfs = f'{zi.file_size:,}'
1194|         scs = f'{zi.compress_size:,}'
1195|         pct = 100.0 * (zi.compress_size / zi.file_size)
1196|         sct = zip_compression_type(zi.compress_type)
1197|         Log.info(f'{ix:2d}: {sfs:>10s} {scs:>10} {pct:6.3f}% [{sct}] {zi.filename}')
1198|     Log.info()
1199| 
1200|     # Create a TAB-delimited output file...
1201|     zpn_zfn = path.split(fnz)
1202|     zname_ext = path.splitext(zpn_zfn[1])
1203|     oname = f'{zname_ext[0]}-zip.tab'
1204|     fno = path.join(opath,oname) if opath else path.join(zpath,oname)
1205|     fo = tabfile(fno)
1206|     fo.hdrs = ['filename', 'filesize', 'compressedsize', 'percentage', 'compressiontype']
1207| 
1208|     for zi in zf.infolist():
1209|         fld0 = zi.filename
1210|         fld1 = zi.file_size
1211|         fld2 = zi.compress_size
1212|         fld3 = 100.0 * (zi.compress_size / zi.file_size)
1213|         fld4 = zip_compression_type(zi.compress_type)
1214|         fo.add([fld0, fld1, fld2, fld3, fld4])
1215|     fo.add()
1216| 
1217|     # save output file...
1218|     fo.save()
1219| 
1220|     Log.info()
1221|     return 'done'
1222| 
1223| ##================================================================================================##
1224| def do_emergence_factor_chart (**kwargs):
1225|     """cmnd: make a chart displaying a zip file compression.
1225| 
1225| parameters:
1225|     zname   -zip file name incl. path if zpath=''
1225|     zpath   -zip file path or '' [ZipsPath]
1225|     opath   -output file path or '' [ImgsPath]
1225|     tpath   -output file path or '' [ImgsPath]
1225| """

1226|     zpath = KWARG('zpath', ZipsPath, str, kwargs)
1227|     opath = KWARG('opath', ImgsPath, str, kwargs)
1228|     tpath = KWARG('tpath', ImgsPath, str, kwargs)
1229|     zname = KWARG('zname', 'test.zip', str, kwargs)
1230|     Log.info('emergence-factor-chart:: %s' % str(list(kwargs.keys())))
1231|     Log.debug(f'{zpath=}')
1232|     Log.debug(f'{opath=}')
1233|     Log.debug(f'{tpath=}')
1234|     Log.debug(f'{zname=}')
1235|     Log.info()
1236| 
1237|     # Open the ZIP file...
1238|     zipfilename = path.join(zpath,zname) if zpath else zname
1239|     zf = ZipFile(zipfilename)
1240|     Log.info(f'opened: {zipfilename}')
1241|     Log.info()
1242| 
1243|     data = []
1244|     # List the details...
1245|     for ix,zi in enumerate(sorted(zf.infolist(), key=lambda x:x.filename), start=1):
1246|         nam = zi.filename
1247|         sfs = f'{zi.file_size:,}'
1248|         scs = f'{zi.compress_size:,}'
1249|         pct = 100.0 * (zi.compress_size / zi.file_size)
1250|         typ = zip_compression_type(zi.compress_type)
1251|         Log.info(f'{ix:2d}: {sfs:>10s} {scs:>10} {pct:6.3f}% [{typ}] {nam}')
1252| 
1253|         datum = (nam, zi.file_size, zi.compress_size)
1254|         data.append(datum)
1255|     Log.info()
1256| 
1257|     # Calculate...
1258|     nums = list(reversed([d[2] for d in data]))
1259|     obj = ESC(zname, nums)
1260| 
1261|     # Create output filename and save plot...
1262|     tpath_tname = path.split(zipfilename)
1263|     tname_ext = path.splitext(tpath_tname[1])
1264|     tname = f'{tname_ext[0]}-ESC.out'
1265|     outfilename = path.join(tpath,tname) if tpath else path.join(zpath,tname)
1266|     outfile = linefile(outfilename)
1267| 
1268|     outfile.add(f'File: {zipfilename}')
1269|     outfile.add(f'{obj!s}')
1270|     outfile.add()
1271|     outfile.add(f'Number-of-Datums: {obj.steps}')
1272|     outfile.add(f'Max-size: {obj.nmax:,}')
1273|     outfile.add(f'Min-size: {obj.nmin:,}')
1274|     outfile.add(f'Total: {obj.tot:,}')
1275|     outfile.add()
1276|     outfile.add(f'AC = {obj.AC:,}')
1277|     outfile.add(f'SS = {obj.SS}')
1278|     outfile.add(f'EF = {obj.EF}')
1279|     outfile.add(f'ESC = {obj.ESC:,}')
1280|     outfile.add()
1281|     outfile.add(f'{obj.AC:,} x {obj.SS:.3f} x {obj.EF:.3f} = {obj.ESC:,.1f}')
1282|     outfile.add()
1283|     outfile.add(f'V[N] = {obj.V[-1]:,}')
1284|     outfile.add(f'V[0] = {obj.V[0]:,}')
1285|     outfile.add()
1286|     outfile.add(f'Fac1: (N+1)*V[N] = {obj.fac1:,}')
1287|     outfile.add(f'Fac2: (N+1)*V[0] = {obj.fac2:,}')
1288|     outfile.add()
1289|     outfile.add('Summation Values:')
1290|     for ix,val in enumerate(obj.V):
1291|         vstr = f'{val:,}'
1292|         outfile.add(f'V[{ix:2d}] = {vstr:>9} ({val/obj.nmax:.3f})')
1293|     # Sum the compression values...
1294|     outfile.add()
1295|     outfile.save()
1296| 
1297|     # Generate a graph...
1298|     dmax = max(d[1] for d in data)
1299|     ygrid = determine_ygrid_spacing(dmax)
1300|     xmax = len(data)
1301|     ymax = (((dmax // ygrid[0]) + 1) * ygrid[0])
1302|     Log.debug(f'{ygrid=}')
1303|     Log.debug(f'{ymax=}')
1304| 
1305|     yticks = [y for y in range(0,ymax+1,ygrid[0])]
1306|     Log.debug(f'{yticks=}')
1307| 
1308|     ylabels = [get_ylabel(y) for y in yticks]
1309|     Log.debug(f'{ylabels=}')
1310| 
1311|     xs = list(range(1,xmax+1))
1312|     ys1a = [d[1] for d in data]
1313|     ys1b = [d[2] for d in data]
1314|     ys2  = [(d[1]-d[2])/d[1] for d in data]
1315| 
1316|     fig, ax1 = plt.subplots()
1317|     fig.set_figwidth(6.0)
1318|     fig.set_figheight(3.0)
1319|     fig.subplots_adjust(left=0.150, right=0.915, bottom=0.165, top=0.91)
1320|     fig.suptitle(f'ZIP Compression - {zname}', fontsize='12', fontweight='bold')
1321| 
1322|     ax1.set_xlabel('File', fontweight='bold')
1323|     ax1.set_xlim(0.5, xmax+0.5)
1324|     ax1.xaxis.set_major_locator(MultipleLocator(1))
1325|     ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
1326|     ax1.xaxis.set_minor_locator(NullLocator())
1327|     ax1.xaxis.set_minor_formatter(NullFormatter())
1328| 
1329|     ax1.set_ylabel('Number of Bytes', color='#3300cc', fontweight='bold')
1330|     ax1.set_ylim(0.0, ymax)
1331|     ax1.yaxis.set_major_locator(FixedLocator(yticks))
1332|     ax1.yaxis.set_major_formatter(FixedFormatter(ylabels))
1333|     ax1.yaxis.set_minor_locator(NullLocator())
1334|     ax1.yaxis.set_minor_formatter(NullFormatter())
1335| 
1336|     ax1.grid(which='major', axis='both', color='#cfcfcf', lw=1.4,ls='-',zorder=1, alpha=1.0)
1337|     ax1.grid(which='minor', axis='both', color='#cfcfcf', lw=0.5,ls='-',zorder=0, alpha=1.0)
1338|     ax1.tick_params(which='major', axis='both', direction='out', color='#000000')
1339|     ax1.tick_params(which='minor', axis='both', direction='out', color='#000000')
1340| 
1341|     ax2 = ax1.twinx()
1342|     ax2.set_ylabel('Structural Spread', color='#007f00', fontweight='bold')
1343|     ax2.set_ylim(0.0, 1.0)
1344|     ax2.yaxis.set_major_locator(MultipleLocator(0.50))
1345|     ax2.yaxis.set_minor_locator(MultipleLocator(0.25))
1346|     ax2.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
1347| 
1348|     ax2.grid(which='major', axis='both', color='#3f7f3f', lw=1.0,ls='-',zorder=1, alpha=1.0)
1349|     ax2.grid(which='minor', axis='both', color='#3f7f3f', lw=0.5,ls='-',zorder=0, alpha=1.0)
1350|     ax2.tick_params(which='major', axis='both', direction='out', color='#000000')
1351|     ax2.tick_params(which='minor', axis='both', direction='out', color='#000000')
1352| 
1353|     p1a = ax1.plot(xs, ys1a, label='orig', color='#0000ff', lw=2.0, alpha=0.85, zorder=11)
1354|     p1b = ax1.plot(xs, ys1b, label='comp', color='#ff0000', lw=2.0, alpha=0.85, zorder=12)
1355|     p2  = ax2.plot(xs, ys2 , label='S.S.'  , color='#007f00', lw=2.5, alpha=0.85, zorder=13)
1356| 
1357|     fig.legend(bbox_to_anchor=(-0.008,-0.015), loc='lower left', fontsize=8, facecolor='#f7f7f7', framealpha=0.5)
1358| 
1359|     # Create output filename and save plot...
1360|     zpath_zname = path.split(zipfilename)
1361|     zname_ext = path.splitext(zpath_zname[1])
1362|     oname = f'{zname_ext[0]}-zip.png'
1363|     imgfilename = path.join(opath,oname) if opath else path.join(zpath,oname)
1364| 
1365|     plt.savefig(imgfilename)
1366|     plt.close(fig)
1367|     Log.info(f'wrote: {imgfilename}')
1368| 
1369|     Log.info()
1370|     return 'done'
1371| 
1372| ##================================================================================================##
1373| def do_zipfile_compare_chart (**kwargs):
1374|     """cmnd: make a chart comparing compression from two zip files.
1374| 
1374| parameters:
1374|     zname   -zip file name (assumes {zname}-[bmp|png].zip)
1374|     zpath   -zip file path [ZipsPath]
1374|     opath   -output file path [ImgsPath]
1374| """

1375|     zpath = KWARG('zpath', ZipsPath, str, kwargs)
1376|     opath = KWARG('opath', ImgsPath, str, kwargs)
1377|     zname = KWARG('zname', 'test', str, kwargs)
1378|     Log.info('zip-file-compare-chart:: %s' % str(list(kwargs.keys())))
1379|     Log.debug(f'{zpath=}')
1380|     Log.debug(f'{opath=}')
1381|     Log.debug(f'{zname=}')
1382|     Log.info()
1383|     sbfn = lambda x:x.filename
1384| 
1385|     # Open the first ZIP file...
1386|     zfn1 = path.join(zpath, f'{zname}-bmp.zip')
1387|     zf1 = ZipFile(zfn1)
1388|     Log.info(f'opened: {zfn1}')
1389|     Log.info()
1390|     dat1 = [(zi.file_size,zi.compress_size) for zi in sorted(zf1.infolist(), key=sbfn)]
1391| 
1392|     # Open the second ZIP file...
1393|     zfn2 = path.join(zpath, f'{zname}-png.zip')
1394|     zf2 = ZipFile(zfn2)
1395|     Log.info(f'opened: {zfn2}')
1396|     Log.info()
1397|     dat2 = [(zi.file_size,zi.compress_size) for zi in sorted(zf2.infolist(), key=sbfn)]
1398| 
1399|     assert len(dat1)==len(dat2), RuntimeError(f'The ZIP files have different file list lengths.')
1400| 
1401|     # Generate a graph...
1402|     xmax = len(dat1)
1403|     dmax1 = max(t[0] for t in dat1)
1404|     dmax2 = max(t[0] for t in dat2)
1405|     dmax = max(dmax1, dmax2)
1406|     ygrid = determine_ygrid_spacing(dmax)
1407|     ymax = (((dmax // ygrid[0]) + 1) * ygrid[0])
1408|     yticks = [y for y in range(0,ymax+1,ygrid[0])]
1409|     ylabels = [get_ylabel(y) for y in yticks]
1410| 
1411|     fig, ax1 = plt.subplots()
1412|     fig.set_figwidth(6.0)
1413|     fig.set_figheight(3.0)
1414|     fig.subplots_adjust(left=0.140, right=0.99, bottom=0.165, top=0.90)
1415|     fig.suptitle(f'ZIP Compression - {zname}', fontsize='12', fontweight='bold')
1416| 
1417|     ax1.set_xlabel('File', fontweight='bold')
1418|     ax1.set_xlim(0.5, xmax+0.5)
1419|     ax1.xaxis.set_major_locator(MultipleLocator(1))
1420|     ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
1421|     ax1.xaxis.set_minor_locator(NullLocator())
1422|     ax1.xaxis.set_minor_formatter(NullFormatter())
1423| 
1424|     ax1.set_ylabel('Number of Bytes', color='#3300cc', fontweight='bold')
1425|     ax1.set_ylim(0.0, ymax)
1426|     ax1.yaxis.set_major_locator(FixedLocator(yticks))
1427|     ax1.yaxis.set_major_formatter(FixedFormatter(ylabels))
1428|     ax1.yaxis.set_minor_locator(NullLocator())
1429|     ax1.yaxis.set_minor_formatter(NullFormatter())
1430| 
1431|     ax1.grid(which='major', axis='both', color='#cfcfcf', lw=1.4,ls='-',zorder=1, alpha=1.0)
1432|     ax1.grid(which='minor', axis='both', color='#cfcfcf', lw=0.5,ls='-',zorder=0, alpha=1.0)
1433|     ax1.tick_params(which='major', axis='both', direction='out', color='#000000')
1434|     ax1.tick_params(which='minor', axis='both', direction='out', color='#000000')
1435| 
1436|     xs = list(range(1,xmax+1))
1437|     ys1a = [t[0] for t in dat1]
1438|     ys1b = [t[1] for t in dat1]
1439|     ys2a = [t[0] for t in dat2]
1440|     ys2b = [t[1] for t in dat2]
1441| 
1442|     ax1.plot(xs, ys1a, label='1 BMP', color='#0000ff', lw=2.0, alpha=1.00, zorder=11)
1443|     ax1.plot(xs, ys1b, label='1 BMP', color='#ff0000', lw=2.0, alpha=1.00, zorder=13)
1444|     ax1.plot(xs, ys2a, label='2 PNG', color='#000000', lw=2.0, alpha=1.00, zorder=12)
1445|     ax1.plot(xs, ys2b, label='2 PNG', color='#00ff00', lw=2.0, alpha=0.70, zorder=14)
1446| 
1447|     fig.legend(bbox_to_anchor=(-0.008,-0.015), loc='lower left', fontsize=8, facecolor='#f7f7f7', framealpha=0.5)
1448| 
1449|     # Create output filename and save plot...
1450|     oname = f'{zname}_bmp-png.png'
1451|     imgfilename = path.join(opath,oname) if opath else path.join(zpath,oname)
1452| 
1453|     plt.savefig(imgfilename)
1454|     plt.close(fig)
1455|     Log.info(f'wrote: {imgfilename}')
1456| 
1457|     Log.info()
1458|     return 'Done'
1459| 
1460| ##================================================================================================##
1461| def do_text_blank_to_random (**kwargs):
1462|     """CMND: For a text file: start with blanks; fade in text; noise to random."""
1463|     iname = KWARG('iname', 'text.text', str, kwargs)
1464|     steps = KWARG('steps', 10, int, kwargs)
1465|     schar = KWARG('schar', ' ', str, kwargs)
1466|     Log.info('image-noise-series:: %s' % str(list(kwargs.keys())))
1467|     Log.debug(f'{iname=}')
1468|     Log.debug(f'{steps=}')
1469|     Log.debug(f'{schar=}')
1470|     Log.info()
1471|     fn,ext = path.splitext(iname)
1472| 
1473|     # Generate list of steps+1 percentages (from 0% to 100%)...
1474|     percents = [ix/steps for ix in range(steps+1)]
1475| 
1476|     # For each percentage in the list, convert chars to spaces...
1477|     # Percentages are reversed to we go from spaces to text...
1478|     kwargs['nmode'] = str(9)
1479|     for ix,pct in enumerate(reversed(percents[1:])):
1480|         # Set filename and noise percentage...
1481|         kwargs['oname'] = f'{fn}_{ix:02d}.txt'
1482|         kwargs['noise'] = str(pct)
1483| 
1484|         # Call Text Noise executive...
1485|         print(f'{ix:2d}: [{pct:.3f}] {kwargs["oname"]}')
1486|         do_text_add_noise(**kwargs)
1487| 
1488|     # For each percentage in the list, generate an image
1489|     kwargs['nmode'] = str(2)
1490|     for ix,pct in enumerate(percents, start=steps):
1491|         # Set noise percentage...
1492|         kwargs['oname'] = f'{fn}_{ix:02d}.txt'
1493|         kwargs['noise'] = str(pct)
1494| 
1495|         # Call Image Noise executive...
1496|         print(f'{ix:2d}: [{pct:.3f}] {kwargs["oname"]}')
1497|         do_text_add_noise(**kwargs)
1498| 
1499|     Log.info()
1500|     Log.info()
1501|     return 'Done'
1502| 
1503| ##================================================================================================##
1504| def do_image_black_to_random (**kwargs):
1505|     """CMND: For an image file: start black; noise to image; noise to random."""
1506|     iname = KWARG('iname', 'image.png', str, kwargs)
1507|     steps = KWARG('steps', 10, int, kwargs)
1508|     nmode = KWARG('nmode', 2, int, kwargs) # nmode for first series; second uses nmode=0
1509|     Log.info('image-noise-series:: %s' % str(list(kwargs.keys())))
1510|     Log.debug(f'{iname=}')
1511|     Log.debug(f'{steps=}')
1512|     Log.debug(f'{nmode=}')
1513|     Log.info()
1514|     fn,ext = path.splitext(iname)
1515| 
1516|     # Generate list of steps+1 percentages (from 0% to 100%)...
1517|     percents = [ix/steps for ix in range(steps+1)]
1518| 
1519|     # For each percentage in the list, add black pixels..
1520|     # Percentages are reversed to we go from black to the image...
1521|     for ix,pct in enumerate(reversed(percents[1:])):
1522|         # Set filename and noise percentage...
1523|         kwargs['oname'] = f'{fn}_{ix:02d}.bmp'
1524|         kwargs['noise'] = str(pct)
1525| 
1526|         # Call Image Noise executive...
1527|         print(f'{ix:2d}: [{pct:.3f}] {kwargs["oname"]}')
1528|         do_image_add_noise(**kwargs)
1529| 
1530|     # For each percentage in the list, generate an image
1531|     kwargs['nmode'] = str(0)
1532|     for ix,pct in enumerate(percents, start=steps):
1533|         # Set noise percentage...
1534|         kwargs['oname'] = f'{fn}_{ix:02d}.bmp'
1535|         kwargs['noise'] = str(pct)
1536| 
1537|         # Call Image Noise executive...
1538|         print(f'{ix:2d}: [{pct:.3f}] {kwargs["oname"]}')
1539|         do_image_add_noise(**kwargs)
1540| 
1541|     Log.info()
1542|     Log.info()
1543|     return 'Done'
1544| 
1545| ##================================================================================================##
1546| def do_image_add_noise_all (**kwargs):
1547|     """CMND: Add a series of noise levels to an image file."""
1548|     steps = KWARG('steps', 10, int, kwargs)
1549|     slist = KWARG('slist', '', str, kwargs)
1550|     Log.info('image-noise-series:: %s' % str(list(kwargs.keys())))
1551|     Log.debug(f'{steps=}')
1552|     Log.debug(f'{slist=}')
1553|     Log.info()
1554| 
1555|     # Generate list of steps+1 percentages (from 0% to 100%)...
1556|     if 0 < len(slist):
1557|         percents = [float(s) for s in slist.split(',')]
1558|     else:
1559|         percents = [ix/steps for ix in range(steps+1)]
1560| 
1561|     # For each percentage in the list, generate an image
1562|     for ix,pct in enumerate(percents):
1563|         # Set noise percentage...
1564|         kwargs['noise'] = str(pct)
1565| 
1566|         # Call Image Noise executive...
1567|         print(f'{ix:2d}: [{pct:.3f}] {kwargs["iname"]} {kwargs["oname"]}')
1568|         do_image_add_noise(**kwargs)
1569| 
1570|     Log.info()
1571|     Log.info()
1572|     return 'Done'
1573| 
1574| ##================================================================================================##
1575| def do_data_add_noise_all (**kwargs):
1576|     """CMND: Add a series of noise levels to a data file."""
1577|     iname = KWARG('iname', 'input.txt', str, kwargs)
1578|     oname = KWARG('oname', '', str, kwargs)
1579|     steps = KWARG('steps', 10, int, kwargs)
1580|     Log.info('datafile-noise-series:: %s' % str(list(kwargs.keys())))
1581|     Log.debug(f'{iname=}')
1582|     Log.debug(f'{oname=}')
1583|     Log.debug(f'{steps=}')
1584|     Log.info()
1585| 
1586|     # Generate list of steps+1 percentages (from 0% to 100%)...
1587|     #TODO: Add steps list input parameter.
1588|     percents = [ix/steps for ix in range(steps+1)]
1589| 
1590|     # Split the filename and extension...
1591|     fn,ext = path.splitext(iname)
1592| 
1593|     # For each percentage in the list, generate an image
1594|     for ix,pct in enumerate(percents):
1595|         # Generate output filename...
1596|         #TODO: Move output naming to add-noise function.
1597|         spct = f'{pct:.2f}'.replace('.','')
1598|         oname = f'{fn}-dnoise-{spct}{ext}'
1599|         print(f'{ix}: {pct} {oname}')
1600| 
1601|         # Randomize textfile...
1602|         kwargs['oname'] = oname
1603|         kwargs['noise'] = pct
1604|         do_data_add_noise(**kwargs)
1605| 
1606|     Log.info()
1607|     return 'Done'
1608| 
1609| ##================================================================================================##
1610| def do_text_add_noise_all (**kwargs):
1611|     """CMND: Add a series of noise levels to a text file."""
1612|     iname = KWARG('iname', 'input.txt', str, kwargs)
1613|     oname = KWARG('oname', '', str, kwargs)
1614|     steps = KWARG('steps', 10, int, kwargs)
1615|     Log.info('textfile-noise-series:: %s' % str(list(kwargs.keys())))
1616|     Log.debug(f'{iname=}')
1617|     Log.debug(f'{oname=}')
1618|     Log.debug(f'{steps=}')
1619|     Log.info()
1620| 
1621|     # Generate list of steps+1 percentages (from 0% to 100%)...
1622|     #TODO: Add steps list input parameter.
1623|     percents = [ix/steps for ix in range(steps+1)]
1624| 
1625|     # Split the filename and extension...
1626|     fn,ext = path.splitext(iname)
1627| 
1628|     # For each percentage in the list, generate an image
1629|     for ix,pct in enumerate(percents):
1630|         #TODO: Move output naming to add-noise function.
1631|         # Generate output filename...
1632|         spct = f'{pct:.2f}'.replace('.','')
1633|         oname = f'{fn}-tnoise-{spct}{ext}'
1634|         print(f'{ix}: {pct} {oname}')
1635| 
1636|         # Randomize textfile...
1637|         kwargs['oname'] = oname
1638|         kwargs['noise'] = pct
1639|         do_text_add_noise(**kwargs)
1640| 
1641|     Log.info()
1642|     return 'Done'
1643| 
1644| ##================================================================================================##
1645| def do_all_ef_charts (**kwargs):
1646|     """CMND: Loop through the ZIP directory and chart each file found."""
1647|     zpath = KWARG('zpath', ZipsPath, str, kwargs)
1648|     zspec = KWARG('zspec', '', str, kwargs)
1649|     Log.info('generate-all-ef-charts:: %s' % str(list(kwargs.keys())))
1650|     Log.debug(f'{zpath=}')
1651|     Log.debug(f'{zspec=}')
1652|     Log.info()
1653| 
1654|     # Get a list of filename in the ZIP folder...
1655|     znames = listdir(zpath)
1656| 
1657|     # For each file found...
1658|     for zname in znames:
1659|         if not zname.endswith('.zip'):
1660|             Log.debug(f'Not a ZIP file: {zname}')
1661|             continue
1662|         if zspec:
1663|             fn,ext = path.splitext(zname)
1664|             m = fullmatch(zspec, fn, IGNORECASE)
1665|             if m is None:
1666|                 Log.debug(f'Not a pattern match: {zname}')
1667|                 continue
1668|         print(zname)
1669|         Log.info(zname)
1670| 
1671|         # Generate the chart for this ZIP file...
1672|         kwargs['zname'] = zname
1673|         do_emergence_factor_chart(**kwargs)
1674| 
1675|     Log.info()
1676|     return 'Done'
1677| 
1678| ##================================================================================================##
1679| def do_command_loop (**kwargs):
1680|     """CMND: Do a command repeatedly with different parameters."""
1681|     cmd   = KWARG('c', '', str, kwargs)
1682|     args1 = KWARG('a1', '0,1,2,3,4,5,6,7,8,9', str, kwargs)
1683|     args2 = KWARG('a2', '', str, kwargs)
1684|     args3 = KWARG('a3', '', str, kwargs)
1685|     args4 = KWARG('a4', '', str, kwargs)
1686|     Log.info('all-loop:: %s' % str(list(kwargs.keys())))
1687|     Log.debug(f'{cmd=}')
1688|     Log.debug(f'{args1=}')
1689|     Log.debug(f'{args2=}')
1690|     Log.debug(f'{args3=}')
1691|     Log.debug(f'{args4=}')
1692|     Log.info()
1693|     a1 = args1.split(',')
1694|     a2 = args2.split(',')
1695|     a3 = args3.split(',')
1696|     a4 = args4.split(',')
1697| 
1698|     # Prepare argument list...
1699|     args_list = []
1700|     if 0 < len(args1): args_list.append(a1)
1701|     if 0 < len(args2): args_list.append(a2)
1702|     if 0 < len(args3): args_list.append(a3)
1703|     if 0 < len(args4): args_list.append(a4)
1704| 
1705|     # Iterate over command versions...
1706|     for args in zip(*args_list):
1707|         command = cmd.format(*args)
1708|         parts = command.split()
1709|         for p in parts[1:]:
1710|             nam,val = p.split('=')
1711|             kwargs[nam] = val
1712| 
1713|         print(command)
1714|         Log.info(command)
1715|         rv = dispatch(parts[0], **kwargs)
1716|         print(rv)
1717|         Log.info(f'{rv=}')
1718|         Log.info()
1719| 
1720|     Log.info()
1721|     return 'Done'
1722| 
1723| ##================================================================================================##
1724| def do_ss_ef_chart (**kwargs):
1725|     """CMND: Do selected SS-EF chart."""
1726|     fpath = KWARG('fpath', BasePath, str, kwargs)
1727|     fname = KWARG('fname', 'chart-ss-ef.png', str, kwargs)
1728|     Log.info('selected-ss-ef-chart:: %s' % str(list(kwargs.keys())))
1729|     Log.debug(f'{fpath=}')
1730|     Log.debug(f'{fname=}')
1731|     Log.info()
1732| 
1733|     data = [
1734|         ['tree_0400'        , 0.392144, 1.693803,  '#339966'],
1735|         ['clouds_0400'      , 0.442500, 1.725139,  '#339966'],
1736|         ['mock-apples_0400' , 0.267499, 1.771582,  '#339966'],
1737|         ['bentley_0400'     , 0.263983, 1.818803,  '#339966'],
1738|         ['oranges_0400'     , 0.177876, 2.177151,  '#339966'],
1739|         ['trees_0400'       , 0.077816, 2.551323,  '#339966'],
1740| 
1741|         ['tree_1200'        , 0.459641, 1.604392,  '#3366cc'],
1742|         ['clouds_1200'      , 0.536446, 1.601625,  '#3366cc'],
1743|         ['mock-apples_1200' , 0.292192, 1.662383,  '#3366cc'],
1744|         ['bentley_1200'     , 0.363548, 1.738861,  '#3366cc'],
1745|         ['oranges_1200'     , 0.281719, 1.979505,  '#3366cc'],
1746|         ['trees_1200'       , 0.061294, 2.556542,  '#3366cc'],
1747| 
1748|         ['tree_2400'        , 0.495350, 1.577351,  '#339966'],
1749|         ['clouds_2400'      , 0.571971, 1.560748,  '#339966'],
1750|         ['mock-apples_2400' , 0.309121, 1.636265,  '#339966'],
1751|         ['bentley_2400'     , 0.429622, 1.708146,  '#339966'],
1752|         ['oranges_2400'     , 0.355108, 1.877243,  '#339966'],
1753|         ['trees_2400'       , 0.062774, 2.449934,  '#339966'],
1754| 
1755|         ['tree_4032'        , 0.539428, 1.564040,  '#3366cc'],
1756|         ['clouds_4032'      , 0.616545, 1.545294,  '#3366cc'],
1757|         ['mock-apples_4032' , 0.353501, 1.632883,  '#3366cc'],
1758|         ['bentley_4032'     , 0.501230, 1.692117,  '#3366cc'],
1759|         ['oranges_4032'     , 0.475470, 1.768127,  '#3366cc'],
1760|         ['trees_4032'       , 0.095900, 2.250219,  '#3366cc'],
1761| 
1762|         ['flag_Norway'      , 0.997893, 1.404463,  '#339966'],
1763|         ['flag_UK'          , 0.994973, 1.398657,  '#339966'],
1764|         ['flag_USA'         , 0.989882, 1.393611,  '#339966'],
1765| 
1766|         ['blank-lines_A'    , 0.965765, 1.494215,  '#cc6600'],
1767|         ['blank-lines_AB'   , 0.968513, 1.693707,  '#cc6600'],
1768|         ['blank-lines_ABC'  , 0.971559, 1.787866,  '#cc6600'],
1769|         ['blank-lines_ABCDE', 0.974602, 1.907269,  '#cc6600'],
1770| 
1771|         ['random-bits'      , 0.851074, 1.519717,  '#993399'],
1772|         ['random-chars'     , 0.636185, 1.631854,  '#993399'],
1773|         ['random-text'      , 0.428931, 1.728881,  '#993399'],
1774|         ['random-words'     , 0.641666, 2.353270,  '#993399'],
1775| 
1776|         ['post-016714'      , 0.600185, 2.292918,  '#cc6600'],
1777|         ['post-010482'      , 0.598010, 2.343888,  '#cc6600'],
1778|         ['post-010486'      , 0.630837, 2.351419,  '#cc6600'],
1779| 
1780|         ['command'          , 0.635502, 2.322504,  '#993399'],
1781|         ['romeo-juliet'     , 0.630474, 2.427791,  '#993399'],
1782|         ['macbeth'          , 0.625082, 2.431328,  '#993399'],
1783|         ['hamlet'           , 0.629988, 2.431601,  '#993399'],
1784|     ]
1785|     #del data[22:]
1786| 
1787|     ys = list(range(1, len(data)+1))
1788|     ynames = [d[0] for d in data]
1789|     xs1 = [d[1] for d in data]
1790|     xs2 = [d[2] for d in data]
1791|     cs  = [d[3] for d in data]
1792|     Log.trace(f'[{len(ys)}] {ys}')
1793|     Log.trace(f'[{len(ynames)}] {ynames}')
1794|     Log.trace(f'[{len(xs1)}] {xs1}')
1795|     Log.trace(f'[{len(xs2)}] {xs2}')
1796|     Log.trace(f'[{len(cs)}] {cs}')
1797|     Log.trace()
1798| 
1799|     fig, ax = plt.subplots()
1800|     fig.set_figwidth(6.0)
1801|     fig.set_figheight(9.0)
1802|     fig.subplots_adjust(left=0.250, right=0.98, bottom=0.060, top=0.95)
1803|     fig.suptitle('Emergence Factor & Structural Spread', fontsize='12', fontweight='bold')
1804| 
1805|     ax.set_xlabel('EF (large colored bars) & SS (small gray bars)', fontweight='bold')
1806|     ax.set_xlim(0.0, 3.0)
1807|     ax.xaxis.set_major_locator(MultipleLocator(1))
1808|     ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
1809|     ax.xaxis.set_minor_locator(MultipleLocator(0.1))
1810|     ax.xaxis.set_minor_formatter(NullFormatter())
1811| 
1812|     #ax.set_ylabel('File', color='#000000', fontweight='bold')
1813|     ax.set_ylim(0, ys[-1]+1)
1814|     ax.invert_yaxis()
1815|     ax.yaxis.set_major_locator(FixedLocator(ys))
1816|     ax.yaxis.set_major_formatter(FixedFormatter(ynames))
1817|     ax.yaxis.set_minor_locator(NullLocator())
1818|     ax.yaxis.set_minor_formatter(NullFormatter())
1819| 
1820|     ax.grid(which='major', axis='both', color='#cfcfcf', lw=1.4,ls='-',zorder=1, alpha=1.0)
1821|     ax.grid(which='minor', axis='both', color='#cfcfcf', lw=0.5,ls='-',zorder=0, alpha=1.0)
1822|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
1823|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
1824| 
1825|     ax.barh(ys, xs2, height=0.7, color=cs       , edgecolor='#000000', linewidth=0.5, zorder=11)
1826|     ax.barh(ys, xs1, height=0.3, color='#bfbfbf', edgecolor='#000000', linewidth=0.4, zorder=12)
1827| 
1828|     fn = path.join(fpath,fname) if fpath else fname
1829|     plt.savefig(fn)
1830|     plt.close(fig)
1831|     Log.info(f'wrote: {fn}')
1832| 
1833|     Log.info()
1834|     return 'Done'
1835| 
1836| ##================================================================================================##
1837| def do_test (**kwargs):
1838|     """CMND: Do a test."""
1839|     fpath = KWARG('fpath', BasePath, str, kwargs)
1840|     ipath = KWARG('ipath', DataPath, str, kwargs)
1841|     opath = KWARG('opath', TextPath, str, kwargs)
1842|     zpath = KWARG('zpath', ZipsPath, str, kwargs)
1843|     fname = KWARG('fname', 'test.png', str, kwargs)
1844|     iname = KWARG('iname', 'test.txt', str, kwargs)
1845|     oname = KWARG('oname', 'test.out', str, kwargs)
1846|     zname = KWARG('zname', 'test.zip', str, kwargs)
1847|     Log.info('test:: %s' % str(list(kwargs.keys())))
1848|     Log.debug(f'{fpath=}')
1849|     Log.debug(f'{ipath=}')
1850|     Log.debug(f'{opath=}')
1851|     Log.debug(f'{zpath=}')
1852|     Log.debug(f'{fname=}')
1853|     Log.debug(f'{iname=}')
1854|     Log.debug(f'{oname=}')
1855|     Log.debug(f'{zname=}')
1856|     Log.info()
1857|     #
1858|     # Open and load the source file...
1859|     fni = path.join(ipath,iname) if ipath else iname
1860|     fi = linefile(fni)
1861|     fi.load()
1862|     Log.info(f'loaded: {len(fi)} lines.')
1863|     Log.info()
1864| 
1865|     longest = max([len(line) for line in fi])
1866|     Log.info(f'longest line: {longest} chars')
1867|     Log.info()
1868|     #
1869|     Log.info()
1870|     return 'Done'
1871| ####################################################################################################
1872| def dispatch (cmd, **kwargs):
1873|     """Dispatch to a module function based on CMD."""
1874|     Log.info(f'CMD: {cmd}')
1875|     for kw in kwargs:
1876|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
1877|     Log.info()
1878|     if cmd == 'c:zip':      return do_emergence_factor_chart(**kwargs)
1879|     if cmd == 'a:zip':      return do_all_ef_charts(**kwargs)
1880|     if cmd == 'c:cmp':      return do_zipfile_compare_chart(**kwargs)
1881|     if cmd == 'tfade':      return do_text_blank_to_random(**kwargs)
1882|     if cmd == 'xfade':      return do_image_black_to_random(**kwargs)
1883|     if cmd == 'a:inoise':   return do_image_add_noise_all(**kwargs)
1884|     if cmd == 'a:dnoise':   return do_data_add_noise_all(**kwargs)
1885|     if cmd == 'a:tnoise':   return do_text_add_noise_all(**kwargs)
1886|     if cmd == 'zipfile':    return do_list_zip_file(**kwargs)
1887|     if cmd == 'iscram':     return do_scramble_image_file(**kwargs)
1888|     if cmd == 'inoise':     return do_image_add_noise(**kwargs)
1889|     if cmd == 'dnoise':     return do_data_add_noise(**kwargs)
1890|     if cmd == 'tnoise':     return do_text_add_noise(**kwargs)
1891|     if cmd == 'txtfile':    return do_txtfile_scramble(**kwargs)
1892|     if cmd == 'hamlet':     return do_hamlet_scramble(**kwargs)
1893|     if cmd == 'rnd:dat':    return do_random_data_file(**kwargs)
1894|     if cmd == 'rnd:txt':    return do_random_text_file(**kwargs)
1895|     if cmd == 'rnd:wrd':    return do_random_words_file(**kwargs)
1896|     if cmd == 'rnd:chr':    return do_random_chars_file(**kwargs)
1897|     if cmd == 'rnd.lin':    return do_random_lines_file(**kwargs)
1898|     if cmd == 'a:cmd':      return do_command_loop(**kwargs)
1899|     if cmd == 'c:ss-ef':    return do_ss_ef_chart(**kwargs)
1900|     if cmd == 'test':       return do_test(**kwargs)
1901|     return 'Nothing to do!'
1902| ####################################################################################################
1903| if __name__ == '__main__':
1904|     print('autorun: %s' % argv[0])
1905|     #Log.start(path.join(BasePath,'emerg_struc_compl.log'))
1906|     Log.start(path.join(BasePath,'log',LogFilenameTimestamp('esc_%s.log')))
1907|     Log.level(debug())
1908|     Log.info(argv[0])
1909|     Log.info()
1910|     cmd = argv[1] if 1 < len(argv) else CMND
1911|     kwargs = ARGS
1912|     for a in argv[2:]:
1913|         nv = a.split('=', 1)
1914|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
1915|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
1916|     try:
1917|         print(f'CMD: {cmd}')
1918|         print()
1919|         obj = dispatch(cmd, **kwargs)
1920|         print()
1921|         print(obj)
1922|         Log.info()
1923|         Log.info(obj)
1924|     except:
1925|         etype, evalue, tb = exc_info()
1926|         ts = extract_tb(tb)
1927|         Log.error()
1928|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
1929|         Log.error()
1930|         for t in ts[-5:]:
1931|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
1932|             Log.error(' %s' % t[3])
1933|             Log.error()
1934|         raise
1935|     finally:
1936|         Log.end()
1937| ####################################################################################################
1938| '''eof'''
1939|