/
melancholia.py
1580 lines (1127 loc) · 57.8 KB
/
melancholia.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This module prints NumPy arrays in a human readable way. |br|
*List of functions*:
Functions which should be accessed by user:
A - dumpA: Function prints 1D of 2D numpy array to a text file
B - printA: Function prints 1D or 2D numpy array to a
string variable
Internal functions:
general usage:
- _printHeader: function prints a header before a NumPy
array is printed
- _decodeString: function decodes the string with
printing format
- _decodeStringErr: function prints error message, if
the given format is incorrect
1D array printing:
- _1DarrayVert: function prints 1D numpy array
vertically
- _1DarrayHori: function prints 1D numpy array
horizontally
- _1DgetTechnical: function computes technical parametrers
of 1D array printing
- _1DcreateEqSpaces: function creates printing equalization
spaces for 1D array printing
- _1DgetLineParam: function computes the line printing
parameters for 1D array printing
- _1DprintIndices: function prints in one line indices of
selected entries from a 1D array
- _1DprintEntries: function prints in one line selected
entries from a 1D array
2D array printing:
- _2Darray: function prints 2D numpy array
- _2DgetTechnical: function computes technical parameters
of 2D-array printing
- _2DcreateEqSpaces: function creates printing equalization
spaces for 2D array printing
- _2DgetLineParam: function computes the line printing
parameters for 2D printing
- _2DprintColumns: function prints indices of columns
for 2D array
- _2DprintInxRow: function prints one index of a row of
a 2D array
- _2DprintRow: function prints selected entries from
the current row for a 2D array
Copyright (C) <2014-2016> Jacek Pierzchlewski
pierzchlewski dot jacek [at] gmail.com
*Authors*:
Jacek Pierzchlewski, Aalborg University, Denmark.
pierzchlewski dot jacek [at] gmail.com
*Version*:
1.0-alpha | 9-FEB-2015 : * Alpha version is ready. |br|
1.0-beta | 10-FEB-2015 : * Beta version is ready. |br|
1.0 | 11-FEB-2015 : * 1.0 version is ready. |br|
1.0r1 | 05-SEP-2016 : * pep8 improvements in code |br|
*License*:
BSD 2-Clause
*Platforms*:
Linux
OS X
"""
from __future__ import division
import numpy as np
# %%##########################################################################
def dumpA(arrA, strFile, strMode='w', strArrayName='', strFormat='%f',
iRowBrake=20, strDelimiter=' ', iMaxCols=4096, iMaxEntr=np.inf,
bVert1D=1, bPrintHeader=0, iLineSpaces=1, iRowSpaces=1):
"""
Function prints 1D or 2D numpy array to a text file
This is the function which prints a NumPy array to a text file.
Take a look at files: 'report_1Darray_example'
and 'report_2Darray_example'
for examples of usage.
Input:
- 1 **arrA** (*NumPy array*) Array to be printed
- 2 **strFile** (*string*) Name of the file to save the array
- 3 **strMode** (*string*) File opening mode
[optional, default = 'w']
- 4 **strArrayName** (*string*) Name of the array [optional, default = '']
- 5 **strFormat** (*string*) Format of printing entires of the array
[optional, default = '%f']
Acceptable formats are %d, %f, %.1f, %.2f,
%.3f, %.4f, ...
- 6 **iRowBrake** (*int*) The number of rows before the column
indices are printed again
[optional, default = 20]
- 7 **strDelimiter** (*string*) Delimiter printed between the entries
of the array
[optional, default = ' ' (double space)]
- 8 **iMaxCols** (*int*) The maximum number of text columns used
to print a single row
[optional, default = 4096]
- 9 **iMaxEntr** (*int*) The maximum number of entries printed in
a single line
[optional, default = np.inf <-- only
iMaxCols decides about line wrapping]
- 10 **bVert1D** (*int*) Print a 1-dimensional numpy array
vertically or horizontally?
1 - vertically, 0 - horizontally
[optional, default = 1]
- 11 **bPrintHeader** (*int*) Add header with array name, dimension
and size?
1 - yes add, 0 - do not add
[optional, default = 0]
- 12 **iLineSpaces** (*int*) The number of spaces between printed
lines
[optional, default = 1]
- 13 **iRowSpaces** (*int*) The number of spaces between printed rows
(only for 2D arrays)
[optional, default = 1]
Output: none
"""
hFile = open(strFile, strMode)
strArray = printA(arrA, strArrayName, strFormat, iRowBrake, strDelimiter,
iMaxCols, iMaxEntr, bVert1D, bPrintHeader, iLineSpaces,
iRowSpaces)
hFile.write(strArray)
hFile.close()
# %%##########################################################################
def printA(arrA, strArrayName='', strFormat='%f', iRowBrake=20,
strDelimiter=' ', iMaxCols=4096, iMaxEntr=np.inf, bVert1D=1,
bPrintHeader=0, iLineSpaces=1, iRowSpaces=1):
"""
Function prints 1D or 2D numpy array to a string variable
This is the function which prints a NumPy array to a string variable.
Take a look on files: 'report_1Darray_example'
and 'report_2Darray_example'
for examples of usage.
Input:
- 1 **arrA** (*NumPy array*) Array to be printed
- 2 **strArrayName** (*string*) Name of the array
[optional, default = '']
- 3 **strFormat** (*string*) Format of printing entires of the
array
[optional, default = '%f']
Acceptable formats are %d, %f, %.1f, %.2f,
%.3f, %.4f, ...
- 4 **iRowBrake** (*int*) The number of rows before the column
indices are printed again
[optional, default = 20]
- 5 **strDelimiter** (*string*) Delimiter printed between the entries
of the array
[optional, default = ' ' (double space)]
- 6 **iMaxCols** (*int*) The maximum number of text columns used
to print a single row
[optional, default = 4096]
- 7 **iMaxEntr** (*int*) The maximum number of entries printed in
a single line
[optional, default = np.inf <-- only
iMaxCols decides about line wrapping]
- 8 **bVert1D** (*int*) Print a 1-dimensional numpy array
vertically or horizontally?
1 - vertically, 0 - horizontally
[optional, default = 1]
- 9 **bPrintHeader** (*int*) Add header with array name, dimension
and size?
1 - yes add, 0 - do not add
[optional, default = 0]
- 10 **iLineSpaces** (*int*) The number of spaces between printed
lines
[optional, default = 1]
- 11 **iRowSpaces** (*int*) The number of spaces between printed rows
(only for 2D arrays)
[optional, default = 1]
Output:
- 1 **strArray** (*string*) String with entries of the numpy array
"""
# Check if the input array has 1 or 2 dimensions
if (arrA.ndim == 1):
# For 1 dimensinal array, the array may be printed horizontally
# or vertically
if bVert1D == 1:
strArray = _1DarrayVert(arrA, strArrayName, strFormat, iRowBrake,
bPrintHeader)
else:
strArray = _1DarrayHori(arrA, strArrayName, strFormat, iRowBrake,
strDelimiter, iMaxCols, iMaxEntr,
bPrintHeader, iLineSpaces)
elif (arrA.ndim == 2):
strArray = _2Darray(arrA, strArrayName, strFormat, iRowBrake,
strDelimiter, iMaxCols, iMaxEntr, bPrintHeader,
iLineSpaces, iRowSpaces)
# If the array has neither 1 nor 2 dimensions, it is an error
else:
strErr = 'NumPy array which is to be printed to a file must '
strErr += 'be of 1- or 2-dimensions!'
raise ValueError(strErr)
return strArray
# %%##########################################################################
def _printHeader(arrA, strArrayName, bPrintHeader):
"""
Function prints a header before a NumPy array is printed
Input:
- 1. **arrA** (*NumPy array*) Array to be printed
- 2 **strArrayName** (*string*) Name of the array
- 3 **bPrintHeader** (*int*) Flag which switched on header printing
1 - switch on, 0 - switch off
Output:
- 1 **strArray** (*string*) String with the header, of an empty string
if the header is switched off
"""
# If header printing is switched off, return an empty string
if bPrintHeader == 0:
return ''
# Print name of the array, if requested
if (strArrayName == ''):
strArray = ''
else:
strArray = ' \'%s\' ' % (strArrayName)
# Print dimension, size and type of the array
strType = arrA.dtype.name # Get the name of the array
if arrA.ndim == 2:
(nRows, nCols) = arrA.shape # Get shape of the array
strArray += '2D-array (shape - %d rows x %d cols, type - %s):\n' \
% (nRows, nCols, strType)
else:
iSize = arrA.size # Get the size of the array
strArray += '1D-array (size - %d, type - %s):\n'\
% (iSize, strType)
return strArray
# %%##########################################################################
def _decodeString(strFormat):
"""
Function decodes the string with printing format
Input:
- 1 **strFormat** (*string*) Format of printing entires of the array
Acceptable formats are %d, %f, %.1f,
%.2f, %.3f, %.4f, ...
Output:
- 1 **bIntegerOnly** (*number*) If 1 - only integers are printed
(no mantissa)
- 2 **iNDigitsAfterDot** (*int*) The number of digits printed after
dot
"""
if len(strFormat) == 0: # String cannot be empty
_decodeStringErr(strFormat)
# Check if the first character is '%', otherwise - error
if not (strFormat[0] == '%'):
_decodeStringErr(strFormat)
# -----------------------------------------------------------------------
# Check if the second character is 'd', 'f' or '.':
# -----------------------------------------------------------------------
# It is 'd':
if (strFormat[1] == 'd'):
# It must be the last element in the format string
if len(strFormat) > 2:
_decodeStringErr(strFormat)
bIntegerOnly = 1
iNDigitsAfterDot = 0
# -----------------------------------------------------------------------
# It is 'f':
elif (strFormat[1] == 'f'): # It is 'f'
# It must be the last element in the format string
if len(strFormat) > 2:
_decodeStringErr(strFormat)
bIntegerOnly = 0
iNDigitsAfterDot = 6
# -----------------------------------------------------------------------
# It is '.' (dot):
elif (strFormat[1] == '.'): # It is dot
if len(strFormat) == 2: # Dot can not be the last digit
_decodeStringErr(strFormat)
# There must be a number after the dot
if not ('0' <= strFormat[2] <= '9'):
_decodeStringErr(strFormat)
# Now read all the numbers after dot
iNDigitsAfterDot = 0 # Number after dot
for inxChr in np.arange(2, len(strFormat) - 1): # Loop over all
cChr = strFormat[inxChr]
if not ('0' <= cChr <= '9'):
_decodeStringErr(strFormat)
# Translate from character to the number
iChrNum = ord(cChr) - 48
# Update the number after dot
iNDigitsAfterDot = iNDigitsAfterDot * 10 + iChrNum
bIntegerOnly = 0
# The last letter after the number must be 'f'
if not ((strFormat[len(strFormat) - 1]) == 'f'):
_decodeStringErr(strFormat)
# -----------------------------------------------------------------------
# The second character is neither 'd', 'f' nor '.', which is incorrect
else:
_decodeStringErr(strFormat)
return (bIntegerOnly, iNDigitsAfterDot)
# Print error message, if the given format is incorrect
def _decodeStringErr(strFormat):
"""
Input:
- 1 **strFormat** (*string*) Format of printing entires of the array
Output: none
"""
strErr = ('Wrong string with printing format!')
strErr += ('String > %s < is an incorrect string!') % (strFormat)
strErr += (' Correct strings are: %d, %f, %.1f, %.2f, %.3f, %.4f, ...')
raise ValueError(strErr)
# %%##########################################################################
def _1DarrayVert(arrA, strArrayName, strFormat, iRowBrake, bPrintHeader):
"""
Function prints 1D numpy array vertically
Input:
- 1 **arrA** (*NumPy array*) Array to be printed
- 2 **strArrayName** (*string*) Name of the array
- 3 **strFormat** (*string*) Format of printing entires of
the array [optional, default = '%f']
Acceptable formats are %d, %f, %.1f,
%.2f, %.3f, %.4f, ...
- 4 **iRowBrake** (*int*) The number of rows before the column
indices are printed again
- 5 **bPrintHeader** (*int*) Add header with array name, dimension
and size?
1 - yes add, 0 - do not add
[optional, default = 0]
Output:
- 1 **strArray** (*string*) String with entries of the numpy array
printed vertically
"""
# Get technial parameters of 1D array printing
(nEnt, nD, nMaxChrInd, nMaxChrEnt, nMinChrEnt) \
= _1DgetTechnical(arrA, strFormat, '')
# nEnt - the number of entries in the array
# nD - the number of characters in delimter
# nMaxChrInd - the maximum number of characters in indices of the array
# nMaxChrEnt - the maximum number of characters in entries of the array
# nMinChrEnt - the minimum number of characters in entries of the array
# Get the printing equalization spaces
(lSpacesInd, _, _, _) = \
_1DcreateEqSpaces(nMaxChrInd, nMaxChrEnt, nMinChrEnt)
# lSpacesInd - a list with spaces which should be added
# to indices of an entry
# --------------------------------------------------------------------
# Printing starts here:
# Add a header, if requested
strArray = \
_printHeader(arrA, strArrayName, bPrintHeader)
# Loop over all entries in the array
nDig = 1 # The number of digits in the current index of an entry
iThr = 10 # The next threshold which changes the number of digits
# Create the command which prints a single entrys
strPrintEntry = '\'%s\' %% (arrA[inxEntr])' % (strFormat)
for inxEntr in np.arange(nEnt):
# If the threshold is reached, move forward the number
# of digits in index of an entry
if inxEntr == iThr:
nDig = nDig + 1
iThr = iThr * 10 # Move the threshold forward
# Print index of the current entry and its value:
strArray = strArray + ('%d:%s ') % (inxEntr, lSpacesInd[nDig - 1])
strEntry = eval(strPrintEntry) # Print the entry
# If the number is nan, 0 or positive, add a blank space before
# the number
if (arrA[inxEntr] >= 0) or np.isnan(arrA[inxEntr]):
strBlankMinus = ' '
else:
strBlankMinus = ''
# Print the entry
strArray = strArray + strBlankMinus + strEntry + '\n'
# Add a row brake, if iRowBrake entries where printed without
# printing a row brake
if ((inxEntr + 1) % iRowBrake) == 0:
strArray = strArray + '\n'
strArray = strArray + '\n'
return strArray
# %%##########################################################################
def _1DarrayHori(arrA, strArrayName, strFormat, iRowBrake, strDelimiter,
iMaxCols, iMaxEntr, bPrintHeader, iLineSpaces):
"""
Function prints 1D numpy array horizontally
Input:
- 1 **arrA** (*NumPy array*) Array to be printed
- 2 **strArrayName** (*string*) Name of the array
- 3 **strFormat** (*string*) Format of printing entires of the array
Acceptable formats are %d, %f, %.1f,
%.2f, %.3f, %.4f, ...
- 4 **iRowBrake** (*int*) The number of rows before the column
indices are printed again
- 5 **strDelimiter** (*string*) Delimiter printed between the entries
of the array
- 6 **iMaxCols** (*int*) The maximum number of text columns used
to print a single row
- 7 **iMaxEntr** (*int*) The maximum number of entries printed in
a single line
- 8 **bPrintHeader** (*int*) Add header with array name, dimension
and size?
1 - yes add, 0 - do not add
[optional, default = 0]
- 9 **iLineSpaces** (*int*) The number of spaces between printed
lines
[optional, default = 1]
Output:
- 1 **strArray** (*string*) String with entries of the numpy array
"""
# Get technial parameters of 1D array printing
(nEnt, nD, nMaxChrInd, nMaxChrEnt, nMinChrEnt) \
= _1DgetTechnical(arrA, strFormat, strDelimiter)
# nEnt - the number of entries in the array
# nD - the number of characters in delimter
# nMaxChrInd - the maximum number of characters in indices of the array
# nMaxChrEnt - the maximum number of characters in entries of the array
# nMinChrEnt - the minimum number of characters in entries of the array
# Get the printing equalization spaces
(lSpacesInd, lSpacesEnt, strAddSpaceInd, strAddSpaceEnt) \
= _1DcreateEqSpaces(nMaxChrInd, nMaxChrEnt, nMinChrEnt)
# lSpacesInd - a list with spaces which should be added to indices of
# an entry
#
# lSpacesEnt - a list with spaces which should be added to entries
#
# strAddSpaceInd - string with an additional space added to indices
# of entries
#
# strAddSpaceEnt - string with an additional space added to entries
# Get the line printing parameters: the number of lines and number of
# entries in one line
(nLines, nEntrypLine, nEntrypLastLine) \
= _1DgetLineParam(iMaxCols, iMaxEntr, nEnt, nD, nMaxChrEnt,
strAddSpaceEnt)
# nLines - the number of lines used to print all the entries from
# the array
# nEntrypLine - the number of entries in one line
# nEntrypLastLine - the number of entries in the last line
# --------------------------------------------------------------------
# Printing starts here
# Add a header, if requested
strArray = _printHeader(arrA, strArrayName, bPrintHeader)
# Loop over all lines to be printed
iStartEntry = 0 # Starting index of the current entry
for inxLine in np.arange(nLines):
# If it is the last line, the number of entries is different
if inxLine == (nLines - 1):
nEntrypLine = nEntrypLastLine
strArray += 4 * ' ' # Print the margin
# Print indices of entries
strArray += _1DprintIndices(arrA, iStartEntry, nEntrypLine,
lSpacesInd, strAddSpaceInd, nD) + '\n'
# Print the margin
strArray += 4 * ' '
strArray += _1DprintEntries(arrA, iStartEntry, nEntrypLine,
strAddSpaceEnt, lSpacesEnt,
strDelimiter, strFormat,
nMaxChrEnt) + '\n'
strArray += iLineSpaces * '\n' # Add spaces between lines
iStartEntry += nEntrypLine # Move forward the start entry
# Add new line at the end of the output string
strArray += '\n\n'
return strArray
# %%#########################################################################
def _1DgetTechnical(arrA, strFormat, strDelimiter):
"""
Function computes technical parametrers of 1D array printing
Input:
- 1 **arrA** (*NumPy array*) Array to be printed
- 2 **strFormat** (*string*) Format of printing entires of the array
- 3 **strDelimiter** (*string*) Delimiter printed between
the entries of the array
Output:
- 1 **nEnt** (*int*) The number of entries in the array
- 2 **nD** (*int*) The number of characters in the delimter
- 3 **nMaxChrInd** (*int*) The maximum number of characters in indices
of the array
- 4 **nMaxChrEnt** (*int*) The maximum number of characters in entries
of the array
- 5 **nMinChrEnt** (*int*) The minimum number of characters in entries
of the array
"""
# --------------------------------------------------------------------
# Count how many +inf, -inf and nan are in the array.
# Change inf, -inf and nan into 0
arrA_nan = np.isnan(arrA) # Positions of nan values in A
arrA[arrA_nan] = 0 # Change nans into 0
nNan = (arrA_nan[arrA_nan == True]).size # The number of nan values in A
arrA_pinf = np.isinf(arrA) * (arrA >= 0) # Positions of +inf vals in A
arrA[arrA_pinf] = 0 # Change +infs into 0
nPInf = (arrA_pinf[arrA_pinf == True]).size # The number of +inf vals in A
arrA_ninf = np.isinf(arrA) * (arrA < 0) # Positions of -inf vals in A
arrA[arrA_ninf] = 0 # Change -infs into 0
nNInf = (arrA_ninf[arrA_ninf == True]).size # The number of -inf vals in A
# --------------------------------------------------------------------
# --------------------------------------------------------------------
# Get the higest number of characters in...
# Decode the string with printing format
(bInt, nM) = _decodeString(strFormat)
# Get the higest number of characters in integer part of entries
# of the array
iMaxAbsInt = np.floor(np.max(np.abs(arrA)))
nX = np.ceil(np.log10(iMaxAbsInt + 1)).astype(int) #
if (nX == 0): #
nX = 1 #
# Get the higest number of characters in entries of the array
nMaxChrEnt = nX + nM
if bInt == 0: # Add 1 because of . in float numbers
nMaxChrEnt = nMaxChrEnt + 1 # ^
if (arrA[arrA < 0].size) > 0: # Add 1 because of '-' in negat. numbers
nMaxChrEnt = nMaxChrEnt + 1 # ^
# If there is nan in the array, the minumum value of
# the max number of characters in entries is 3
if (nNan > 0) and (nMaxChrEnt < 3):
nMaxChrEnt = 3
# If there is inf in the array, the minumum value of the max number
# of characters in entries is 3
if (nPInf > 0) and (nMaxChrEnt < 3):
nMaxChrEnt = 3
# If there is -inf in the array, the minumum value of the max number
# of characters in entries is 4
if (nNInf > 0) and (nMaxChrEnt < 4):
nMaxChrEnt = 4
# -------
nEnt = arrA.size # Get the number of entries in 1D array
nC = np.ceil(np.log10(nEnt)).astype(int) # ...size of the array
if (nC == 0):
nC = 1
nMaxChrInd = nC + 1 # ... indices of the array (1 because of :)
nD = len(strDelimiter) # ...delimiter
# --------------------------------------------------------------------
# Get the lowest number of characters in...
# ...integer part of entries of the array
iMinAbsInt = np.floor(np.min(np.abs(arrA)))
nXl = np.ceil(np.log10(iMinAbsInt + 1)).astype(int)
if nXl == 0:
nXl = 1
nMinChrEnt = nXl + nM # ... entries of the array
if bInt == 0: # Add 1 due to . in float numbers
nMinChrEnt = nMinChrEnt + 1 # ^
if (arrA[arrA >= 0].size) == 0: # Add 1 due to '-' in all neg. numbers
nMinChrEnt = nMinChrEnt + 1 # ^
# If there is nan in the array, the maximum value of
# the min number of characters in entries is 3
if (nNan > 0) and (nMinChrEnt > 3):
nMinChrEnt = 3
# If there is inf in the array, the maximum value of
# the min number of characters in entries is 3
if (nPInf > 0) and (nMinChrEnt > 3):
nMinChrEnt = 3
# If there is -inf in the array, the maximum value of
# the min number of characters in entries is 4
if (nNInf > 0) and (nMinChrEnt > 4):
nMinChrEnt = 4
# --------------------------------------------------------------------
# Restore correct positions of +inf, -inf and nan in the array
if nNan > 0:
arrA[arrA_nan] = np.nan
if nPInf > 0:
arrA[arrA_pinf] = np.inf
if nNInf > 0:
arrA[arrA_ninf] = -np.inf
# --------------------------------------------------------------------
return (nEnt, nD, nMaxChrInd, nMaxChrEnt, nMinChrEnt)
# %%#########################################################################
def _1DcreateEqSpaces(nMaxChrInd, nMaxChrEnt, nMinChrEnt):
"""
Function creates printing equalization spaces for 1D array printing
Input:
- 1 **nMaxChrInd** (*int*) The maximum number of characters in indices
of the array
- 2 **nMaxChrEnt** (*int*) The maximum number of characters in entries
of the array
- 3 **nMinChrEnt** (*int*) The minimum number of characters in entries
of the array
Output:
- 1 **lSpacesInd** (*list*) A list with spaces which should be added
to indices of an entry
- 2 **lSpacesEnt** (*list*) A list with spaces which should be added
to entries
- 3 **strAddSpaceInd** (*string*) A string with an additional space
added to indices of entries
- 4 **strAddSpaceEnt** (*string*) A string with an additional space
added to entries
"""
# Create additional spaces for indices of entries and the entries
# These spaces are used to equalize indices of entries with the entries
if (nMaxChrInd >= nMaxChrEnt):
strAddSpaceEnt = (nMaxChrInd - nMaxChrEnt) * ' '
strAddSpaceInd = ''
else:
strAddSpaceEnt = ''
strAddSpaceInd = (nMaxChrEnt - nMaxChrInd) * ' '
# --------------------------------------------------------------------
# Create a list with spaces which should be added to indices of an entry
# These spaces are used to equalize the number of characters in indices of
# entries with the number of characters in the longest index of an entry
# The longest space to be added to indices of entries
nLongSpace = nMaxChrInd - 2
# Start a list with blank spaces
lSpacesInd = []
# Create a list with blank space
for iSpaceSize in np.arange(nLongSpace, -1, -1):
lSpacesInd.append(iSpaceSize * ' ')
# Create a list with spaces which should be added to entries
# These spaces are used to equalize the number of characters in entries
# with the number of characters in the longest entry
# The longest space to be added to entries
nLongSpace = nMaxChrEnt - nMinChrEnt
# Start a list with blank spaces
lSpacesEnt = []
# Create a list with blank spaces
for iSpaceSize in np.arange(nLongSpace + 1):
lSpacesEnt.append(iSpaceSize * ' ')
return (lSpacesInd, lSpacesEnt, strAddSpaceInd, strAddSpaceEnt)
# %%#########################################################################
def _1DgetLineParam(iMaxCols, iMaxEntr, nEnt, nD, nMaxChrEnt, strAddSpaceEnt):
"""
Function computes the line printing parameters for 1D array printing
Input:
- 1 **iMaxCols** (*int*) The maximum number of text columns used
to print a single row
- 2 **iMaxEntr** (*int*) The maximum number of entries printed in
a single line
- 3 **nEnt** (*int*) The number of entries in the array
- 4 **nD** (*int*) The number of characters in the delimter
- 5 **nMaxChrEnt** (*int*) The maximum number of characters in
entries of the array
- 6 **strAddSpaceEnt** (*int*) A string with an additional space added
to entries
Output:
- 1 **nLines** (*int*) The number of lines used to print all
the entries from the array
- 2 **nEntrypLine** (*int*) The number of entries in one line
- 3 **nEntrypLastLine** (*int*) The number of entries in the last line
"""
# Calculate the maximum number of characters needed to print one entry
# Entry additional space + entry + delimiter
nChr1Entry = len(strAddSpaceEnt) + nMaxChrEnt + nD
# Compute the number of entries in one line
nEntrypLine = np.floor((iMaxCols - 4 - 1) / nChr1Entry).astype(int)
if (nEntrypLine > iMaxEntr):
nEntrypLine = iMaxEntr
# Check if it is possible to print at least one entry?
if (nEntrypLine == 0):
strErr = 'The requested line is to short to print a single entry'
raise ValueError(strErr)
# Into how many lines do we have to break the printing?
nLines = np.ceil(nEnt / nEntrypLine)
# Compute the number of entries in the last line
nEntrypLastLine = nEnt - nEntrypLine * (nLines - 1)
return (nLines, nEntrypLine, nEntrypLastLine)
# %%#########################################################################
def _1DprintIndices(arrA, iStartEntry, nEntries, lSpacesInd,
strAddSpaceInd, nD):
"""
Function prints in one line indices of selected entries from a 1D array
Input:
- 1 **arrA** (*NumPy array*) Array to be printed
- 2 **iStartEntry** (*int*) Index of the first entry to be printed
- 3 **nEntries** (*int*) The number of entries to be printed
- 4 **lSpacesInd** (*list*) A list with spaces which should be
added to indices of an entry
- 5 **strAddSpaceEnt** (*string*) Blank spaces before every entry to
equalize length of printed entries
with printed indices of column
- 6 **nD** (*integer*) The number of characters in delimiter
Output:
- 1 **strArray** (*string*) String with indices of entries
"""
# Get the lowest number of digits in indices of entries
if (iStartEntry >= 2):
nIndDigL = np.ceil(np.log10(iStartEntry)).astype(int)
else:
nIndDigL = 1
strArray = ''
nDigs = nIndDigL # The current number of digits
iThr = 10 ** nDigs # Next threshold which changes the number of digits
# Loop over all entries
for inxEntry in np.arange(iStartEntry, iStartEntry + nEntries):
if inxEntry == iThr: # Threshold is reached
nDigs = nDigs + 1 # The number of digits
iThr = iThr * 10 # Threshold
# Print the entry
strArray += ('%s%s%d:%s') \
% (strAddSpaceInd, lSpacesInd[nDigs - 1], inxEntry, nD * ' ')
return strArray
# %%#########################################################################
def _1DprintEntries(arrA, iStartEntry, nEntries, strAddSpaceEnt, lSpaces,
strDelimiter, strFormat, nMaxChrEnt):
"""
Function prints in one line selected entries from a 1D array
Input:
- 1 **arrA** (*NumPy array*) Array to be printed
- 2 **iStartEntry** (*int*) Index of the first entry to be printed
- 3 **nEntries** (*int*) The number of entries to be printed
- 4 **strAddSpaceEnt** (*string*) Blank spaces before every entry to
equalize length of printed entries
with printed indices of column
- 5 **lSpaces** (*list*) List with blank spaces used to
equalize length of printed entries
- 6 **strDelimiter** (*string*) Delimiter printed between the entries
- 7 **strFormat** (*string*) Format of printing entires of the array
Acceptable formats are %d, %f, %.1f,
%.2f, %.3f, %.4f, ...
- 8 **nMaxChrEnt** (*integer*) The maximum possible number of
characters used to print one entry
from the array
Output:
- 1. **strArray** (*string*) String with selected entries of
the numpy array
"""
# Create a command which prints a single entry
strPrintEntry = '\'%s\' %% (arrA[inxEntr])' % (strFormat)
strArray = ''
# Loop over all entries
for inxEntr in np.arange(iStartEntry, iStartEntry + nEntries):
strEntry = eval(strPrintEntry) # Create the current entry
# The number of characters in the current entryv
nChrEntry = len(strEntry)
# The lenght of a space which must be added
nSpace = nMaxChrEnt - nChrEntry
# Print the entry
strArray += ('%s%s%s%s') \
% (strAddSpaceEnt, lSpaces[nSpace], strEntry, strDelimiter)
return strArray
# %%#########################################################################
def _2Darray(arrA, strArrayName, strFormat, iRowBrake, strDelimiter, iMaxCols,
iMaxEntr, bPrintHeader, iLineSpaces, iRowSpaces):
"""
Function prints 2D numpy array
Input:
- 1 **arrA** (*NumPy array*) Array to be printed
- 2 **strArrayName** (*string*) Name of the array
- 3 **strFormat** (*string*) Format of printing entires of the array