forked from myrlund/salabim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
salabim.py
13637 lines (11457 loc) · 507 KB
/
salabim.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
'''
salabim discrete event simulation
see www.salabim.org for more information, the documentation, updates and license information.
'''
from __future__ import print_function # compatibility with Python 2.x
from __future__ import division # compatibility with Python 2.x
__version__ = '2.3.0'
import heapq
import random
import time
import math
import array
import collections
import glob
import os
import inspect
import platform
import sys
import itertools
import string
import io
import pickle
import logging
Pythonista = (sys.platform == 'ios')
Windows = (sys.platform.startswith('win'))
class SalabimError(Exception):
pass
class g():
pass
if Pythonista:
import scene
import ui
import objc_util
inf = float('inf')
nan = float('nan')
class ItemFile(object):
'''
define an item file to be used with read_item, read_item_int, read_item_float and read_item_bool
Parameters
----------
filename : str
file to be used for subsequent read_item, read_item_int, read_item_float and read_item_bool calls |n|
or |n|
content to be interpreted used in subsequent read_item calls. The content should have at least one linefeed
character and will be usually triple quoted.
Note
----
It is advised to use ItemFile with a context manager, like ::
with sim.ItemFile('experiment0.txt') as f:
run_length = f.read_item_float() |n|
run_name = f.read_item() |n|
Alternatively, the file can be opened and closed explicitely, like ::
f = sim.ItemFile('experiment0.txt')
run_length = f.read_item_float()
run_name = f.read_item()
f.close()
Item files consists of individual items separated by whitespace |n|
If a blank is required in an item, use single or double quotes |n|
All text following # on a line is ignored |n|
All texts on a line within curly brackets {} is ignored and considered white space.
Example ::
Item1
'Item 2'
Item3 Item4 # comment
Item5 {five} Item6 {six}
'Double quote" in item'
"Single quote' in item"
True
'''
def __init__(self, filename):
self.iter = self._nextread()
if '\n' in filename:
self.open_file = io.StringIO(filename)
else:
self.open_file = open(filename, 'r')
def __enter__(self):
return self
def __exit__(self, *args):
self.open_file.close()
def close(self):
self.open_file.close()
def read_item_int(self):
'''
read next field from the ItemFile as int.
if the end of file is reached, EOFError is raised
'''
return int(self.read_item().replace(',', '.'))
def read_item_float(self):
'''
read next item from the ItemFile as float
if the end of file is reached, EOFError is raised
'''
return float(self.read_item().replace(',', '.'))
def read_item_bool(self):
'''
read next item from the ItemFile as bool
A value of False (not case sensitive) will return False |n|
A value of 0 will return False |n|
The null string will return False |n|
Any other value will return True
if the end of file is reached, EOFError is raised
'''
result = self.read_item().strip().lower()
if result == 'false':
return False
try:
if float(result) == 0:
return False
except:
pass
if result == '':
return False
return True
def read_item(self):
'''
read next item from the ItemFile
if the end of file is reached, EOFError is raised
'''
try:
return next(self.iter)
except StopIteration:
raise EOFError
def _nextread(self):
remove = string.whitespace.replace(' ', '')
quotes = '\'"'
for line in self.open_file:
mode = '.'
result = ''
for c in line:
if c not in remove:
if mode in quotes:
if c == mode:
mode = '.'
yield result # even return the null string
result = ''
else:
result += c
elif mode == '{':
if c == '}':
mode = '.'
else:
if c == '#':
break
if c in quotes:
if result:
yield result
result = ''
mode = c
elif c == '{':
if result:
yield result
result = ''
mode = c
elif c == ' ':
if result:
yield result
result = ''
else:
result += c
if result:
yield result
class Monitor(object):
'''
Monitor object
Parameters
----------
name : str
name of the monitor |n|
if the name ends with a period (.),
auto serializing will be applied |n|
if the name end with a comma,
auto serializing starting at 1 will be applied |n|
if omitted, the name will be derived from the class
it is defined in (lowercased)
monitor : bool
if True (default), monitoring will be on. |n|
if False, monitoring is disabled |n|
it is possible to control monitoring later,
with the monitor method
type : str
specifies how tallied values are to be stored
- 'any' (default) stores values in a list. This allows
non numeric values. In calculations the values are
forced to a numeric value (0 if not possible)
- 'bool' (True, False) Actually integer >= 0 <= 255 1 byte
- 'int8' integer >= -128 <= 127 1 byte
- 'uint8' integer >= 0 <= 255 1 byte
- 'int16' integer >= -32768 <= 32767 2 bytes
- 'uint16' integer >= 0 <= 65535 2 bytes
- 'int32' integer >= -2147483648<= 2147483647 4 bytes
- 'uint32' integer >= 0 <= 4294967295 4 bytes
- 'int64' integer >= -9223372036854775808 <= 9223372036854775807 8 bytes
- 'uint64' integer >= 0 <= 18446744073709551615 8 bytes
- 'float' float 8 bytes
merge: list, tuple or set
the monitor will be created by merging the monitors mentioned in the list |n|
note that the types of all to be merged monitors should be the same. |n|
default: no merge
env : Environment
environment where the monitor is defined |n|
if omitted, default_env will be used
'''
cached_x = [(0, 0), (0, 0)] # index=ex0, value=[hash,x]
def __init__(self, name=None, monitor=True, type=None, merge=None,
env=None, *args, **kwargs):
if env is None:
self.env = g.default_env
else:
self.env = env
_set_name(name, self.env._nameserializeMonitor, self)
self._timestamp = False
if merge is None:
if type is None:
type = 'any'
try:
self.xtypecode, _ = type_to_typecode_off(type)
except KeyError:
raise SalabimError('type (' + type + ') not recognized')
self.reset(monitor)
else:
if not merge:
raise SalabimError('merge list empty')
for m in merge:
if not isinstance(m, Monitor):
raise SalabimError('non Monitor item found in merge list')
self.xtypecode = merge[0].xtypecode
for m in merge:
if m.xtypecode != self.xtypecode:
raise SalabimError('not all types in merge list are equal')
if type is not None:
if type_to_typecode_off(type)[0] != self.xtypecode:
raise SalabimError('type does not match the type of the monitors in the merge list')
if self.xtypecode:
self._x = array.array(self.xtypecode, itertools.chain(*[m._x for m in merge]))
else:
self._x = list(itertools.chain(*[m._x for m in merge]))
self._monitor = monitor
self.setup(*args, **kwargs)
def setup(self):
'''
called immediately after initialization of a monitor.
by default this is a dummy method, but it can be overridden.
only keyword arguments are passed
'''
pass
def register(self, registry):
'''
registers the monitor in the registry
Parameters
----------
registry : list
list of (to be) registered objects
Returns
-------
monitor (self) : Monitor
Note
----
Use Monitor.deregister if monitor does not longer need to be registered.
'''
if not isinstance(registry, list):
raise SalabimError('registry not list')
if self in registry:
raise SalabimError(self.name() + ' already in registry')
registry.append(self)
return self
def deregister(self, registry):
'''
deregisters the monitor in the registry
Parameters
----------
registry : list
list of registered objects
Returns
-------
monitor (self) : Monitor
'''
if not isinstance(registry, list):
raise SalabimError('registry not list')
if self not in registry:
raise SalabimError(self.name() + ' not in registry')
registry.remove(self)
return self
def __repr__(self):
return objectclass_to_str(self) + ' (' + self.name() + ')'
def reset_monitors(self, monitor=None):
'''
resets monitor
Parameters
----------
monitor : bool
if True (default), monitoring will be on. |n|
if False, monitoring is disabled |n|
if omitted, the monitor state remains unchanged
Note
----
Exactly same functionality as Monitor.reset()
'''
self.reset(monitor)
def reset(self, monitor=None):
'''
resets monitor
Parameters
----------
monitor : bool
if True, monitoring will be on. |n|
if False, monitoring is disabled
if omitted, no change of monitoring state
'''
if monitor is None:
monitor = self._monitor
if self.xtypecode:
self._x = array.array(self.xtypecode)
else:
self._x = []
self.monitor(monitor)
Monitor.cached_x = [(0, 0), (0, 0)] # invalidate the cache
def monitor(self, value=None):
'''
enables/disabled monitor
Parameters
----------
value : bool
if True, monitoring will be on. |n|
if False, monitoring is disabled |n|
if omitted, no change
Returns
-------
True, if monitoring enabled. False, if not : bool
'''
if value is not None:
self._monitor = value
return self.monitor
def tally(self, x):
'''
Parameters
----------
x : any, preferably int, float or translatable into int or float
value to be tallied
'''
if self._monitor:
self._x.append(x)
def name(self, value=None):
'''
Parameters
----------
value : str
new name of the monitor
if omitted, no change
Returns
-------
Name of the monitor : str
Note
----
base_name and sequence_number are not affected if the name is changed
'''
if value is not None:
self._name = value
return self._name
def base_name(self):
'''
Returns
-------
base name of the monitor (the name used at initialization): str
'''
return self._base_name
def sequence_number(self):
'''
Returns
-------
sequence_number of the monitor : int
(the sequence number at initialization) |n|
normally this will be the integer value of a serialized name,
but also non serialized names (without a dot or a comma at the end)
will be numbered)
'''
return self._sequence_number
def mean(self, ex0=False):
'''
mean of tallied values
Parameters
----------
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
Returns
-------
mean : float
'''
x = self.x(ex0=ex0)
if x:
return sum(x) / len(x)
else:
return nan
def std(self, ex0=False):
'''
standard deviation of tallied values
Parameters
----------
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
Returns
-------
standard deviation : float
'''
x = self.x(ex0=ex0)
if x:
wmean = self.mean(ex0)
wvar = sum(((vx - wmean)**2) for vx in x) / len(x)
return math.sqrt(wvar)
else:
return nan
def minimum(self, ex0=False):
'''
minimum of tallied values
Parameters
----------
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
Returns
-------
minimum : float
'''
x = self.x(ex0=ex0)
if x:
return min(x)
else:
return nan
def maximum(self, ex0=False):
'''
maximum of tallied values
Parameters
----------
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
Returns
-------
maximum : float
'''
x = self.x(ex0=ex0)
if x:
return max(x)
else:
return nan
def median(self, ex0=False):
'''
median of tallied values weighted wioth their durations
Parameters
----------
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
Returns
-------
median : float
'''
return self.percentile(50, ex0=ex0)
def percentile(self, q, ex0=False):
'''
q-th percentile of tallied values
Parameters
----------
q : float
percentage of the distribution |n|
values <0 are treated a 0 |n|
values >100 are treated as 100
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
Returns
-------
: float
q-th percentile |n|
0 returns the minimum, 50 the median and 100 the maximum
'''
q = max(0, min(q, 100))
if self._timestamp:
x, weights = self.xduration(ex0=ex0)
else:
x = self.x(ex0=ex0)
weights = [1] * len(x)
if len(x) == 1:
return x[0]
sumweights = sum(weights)
if not sumweights:
return nan
xweights = sorted(zip(x, weights), key=lambda v: v[0])
x_sorted, weights_sorted = zip(*xweights)
weights_sorted = [0] + list(weights_sorted)
threshold = sumweights * q / 100
vcum_imin1 = 0
for i, v in enumerate(weights_sorted):
vcum_i = vcum_imin1 + v
if vcum_i > threshold:
break
vcum_imin1 = vcum_i
return interpolate(threshold, vcum_imin1, vcum_i, x_sorted[i - 1], x_sorted[min(i, len(x_sorted) - 1)])
def bin_number_of_entries(self, lowerbound, upperbound, ex0=False):
'''
count of the number of tallied values in range (lowerbound,upperbound]
Parameters
----------
lowerbound : float
non inclusive lowerbound
upperbound : float
inclusive upperbound
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
Returns
-------
number of values >lowerbound and <=upperbound : int
'''
x = self.x(ex0=ex0)
return sum(1 for vx in x if (vx > lowerbound) and (vx <= upperbound))
def value_number_of_entries(self, value):
'''
count of the number of tallied values equal to value or in value
Parameters
----------
value : any
if list, tuple or set, check whether the tallied value is in value |n|
otherwise, check whether the tallied value equals the given value
Returns
-------
number of tallied values in value or equal to value : int
'''
if isinstance(value, (list, tuple, set)):
value = [str(v) for v in value]
else:
value = [str(value)]
return sum(1 for vx in self._x if (str(vx).strip() in value))
def number_of_entries(self, ex0=False):
'''
count of the number of entries
Parameters
----------
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
Returns
-------
number of entries : int
'''
return len(self.x(ex0=ex0))
def number_of_entries_zero(self):
'''
count of the number of zero entries
Returns
-------
number of zero entries : int
'''
return self.number_of_entries() - self.number_of_entries(ex0=True)
def print_statistics(self, show_header=True, show_legend=True, do_indent=False, as_str=False):
'''
print monitor statistics
Parameters
----------
show_header: bool
primarily for internal use
show_legend: bool
primarily for internal use
do_indent: bool
primarily for internal use
as_str: bool
if False (default), print the statistics
if True, return a string containing the statistics
Returns
-------
statistics (if as_str is True) : str
'''
result = []
if do_indent:
l = 45
else:
l = 0
indent = pad('', l)
if show_header:
result.append(
indent + 'Statistics of {} at {}'.format(self.name(), fn(self.env._now - self.env._offset, 13, 3)))
if show_legend:
result.append(
indent + ' all excl.zero zero')
result.append(
pad('-' * (l - 1) + ' ', l) + '-------------- ------------ ------------ ------------')
if self._timestamp:
if self.duration() == 0:
result.append(pad(self.name(), l) + 'no data')
return return_or_print(result, as_str)
else:
result.append(pad(self.name(), l) + 'duration {}{}{}'.
format(fn(self.duration(), 13, 3),
fn(self.duration(ex0=True), 13, 3), fn(self.duration_zero(), 13, 3)))
else:
if self.number_of_entries() == 0:
result.append(pad(self.name(), l) + 'no entries')
return return_or_print(result, as_str)
else:
result.append(pad(self.name(), l) + 'entries {}{}{}'.
format(fn(self.number_of_entries(), 13, 3),
fn(self.number_of_entries(ex0=True), 13, 3), fn(self.number_of_entries_zero(), 13, 3)))
result.append(indent + 'mean {}{}'.
format(fn(self.mean(), 13, 3), fn(self.mean(ex0=True), 13, 3)))
result.append(indent + 'std.deviation {}{}'.
format(fn(self.std(), 13, 3), fn(self.std(ex0=True), 13, 3)))
result.append('')
result.append(indent + 'minimum {}{}'.
format(fn(self.minimum(), 13, 3), fn(self.minimum(ex0=True), 13, 3)))
result.append(indent + 'median {}{}'.
format(fn(self.percentile(50), 13, 3), fn(self.percentile(50, ex0=True), 13, 3)))
result.append(indent + '90% percentile{}{}'.
format(fn(self.percentile(90), 13, 3), fn(self.percentile(90, ex0=True), 13, 3)))
result.append(indent + '95% percentile{}{}'.
format(fn(self.percentile(95), 13, 3), fn(self.percentile(95, ex0=True), 13, 3)))
result.append(indent + 'maximum {}{}'.
format(fn(self.maximum(), 13, 3), fn(self.maximum(ex0=True), 13, 3)))
return return_or_print(result, as_str)
def histogram_autoscale(self, ex0=False):
'''
used by histogram_print to autoscale |n|
may be overridden.
Parameters
----------
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
Returns
-------
bin_width, lowerbound, number_of_bins : tuple
'''
xmax = self.maximum(ex0=ex0)
xmin = self.minimum(ex0=ex0)
done = False
for i in range(10):
exp = 10 ** i
for bin_width in (exp, exp * 2, exp * 5):
lowerbound = math.floor(xmin / bin_width) * bin_width
number_of_bins = math.ceil((xmax - lowerbound) / bin_width)
if number_of_bins <= 30:
done = True
break
if done:
break
return bin_width, lowerbound, number_of_bins
def print_histograms(self, number_of_bins=None,
lowerbound=None, bin_width=None, values=False, ex0=False, as_str=False):
'''
print monitor statistics and histogram
Parameters
----------
number_of_bins : int
number of bins |n|
default: 30 |n|
if <0, also the header of the histogram will be surpressed
lowerbound: float
first bin |n|
default: 0
bin_width : float
width of the bins |n|
default: 1
values : bool
if False (default), bins will be used |n|
if True, the individual values will be shown (in the right order).
in that case, no cumulative values will be given |n|
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
as_str: bool
if False (default), print the histogram
if True, return a string containing the histogram
Returns
-------
histogram (if as_str is True) : str
Note
----
If number_of_bins, lowerbound and bin_width are omitted, the histogram will be autoscaled,
with a maximum of 30 classes. |n|
Exactly same functionality as Monitor.print_histogram()
'''
return self.print_histogram(number_of_bins, lowerbound, bin_width, values, ex0)
def print_histogram(self, number_of_bins=None,
lowerbound=None, bin_width=None, values=False, ex0=False, as_str=False):
'''
print monitor statistics and histogram
Parameters
----------
number_of_bins : int
number of bins |n|
default: 30 |n|
if <0, also the header of the histogram will be surpressed
lowerbound: float
first bin |n|
default: 0
bin_width : float
width of the bins |n|
default: 1
values : bool
if False (default), bins will be used |n|
if True, the individual values will be shown (in the right order).
in that case, no cumulative values will be given |n|
ex0 : bool
if False (default), include zeroes. if True, exclude zeroes
as_str: bool
if False (default), print the histogram
if True, return a string containing the histogram
Returns
-------
histogram (if as_str is True) : str
Note
----
If number_of_bins, lowerbound and bin_width are omitted, the histogram will be autoscaled,
with a maximum of 30 classes.
'''
result = []
result.append('Histogram of ' + self.name() + ('[ex0]' if ex0 else ''))
if self._timestamp:
x, weights = self.xduration(ex0=ex0, force_numeric=not values)
weight_total = sum(weights)
else:
x = self.x(ex0=ex0, force_numeric=not values)
weight_total = len(x)
if weight_total == 0:
result.append('')
if self._timestamp:
result.append('no data')
else:
result.append('no entries')
else:
if values:
nentries = len(x)
if self._timestamp:
result.append('duration {}'.
format(fn(weight_total, 13, 3)))
result.append('entries {}'.
format(fn(nentries, 13, 3)))
result.append('')
if self._timestamp:
result.append('value duration entries')
else:
result.append('value entries')
as_set = {str(x).strip() for x in set(x)}
values = sorted(list(as_set), key=self.key)
for value in values:
if self._timestamp:
count = self.value_duration(value)
count_entries = self.value_number_of_entries(value)
else:
count = self.value_number_of_entries(value)
perc = count / weight_total
scale = 80
n = int(perc * scale)
s = ('*' * n) + (' ' * (scale - n))
if self._timestamp:
result.append(pad(str(value), 20) + fn(count, 14, 3) + '(' + fn(perc * 100, 5, 1) + '%)' +
rpad(str(count_entries), 7) + '(' + fn(count_entries * 100 / nentries, 5, 1) + '%) ' + s)
else:
result.append(
pad(str(value), 20) + rpad(str(count), 7) + '(' + fn(perc * 100, 5, 1) + '%) ' + s)
else:
bin_width, lowerbound, number_of_bins = self.histogram_autoscale()
result.append(self.print_statistics(show_header=False, show_legend=True, do_indent=False, as_str=True))
if number_of_bins >= 0:
result.append('')
if self._timestamp:
result.append(' <= duration % cum%')
else:
result.append(' <= entries % cum%')
cumperc = 0
for i in range(-1, number_of_bins + 1):
if i == -1:
lb = -inf
else:
lb = lowerbound + i * bin_width
if i == number_of_bins:
ub = inf
else:
ub = lowerbound + (i + 1) * bin_width
if self._timestamp:
count = self.bin_duration(lb, ub)
else:
count = self.bin_number_of_entries(lb, ub)
perc = count / weight_total
cumperc += perc
scale = 80
n = int(perc * scale)
ncum = int(cumperc * scale) + 1
s = ('*' * n) + (' ' * (scale - n))
s = s[:ncum - 1] + '|' + s[ncum + 1:]
result.append('{} {}{}{} {}'.
format(fn(ub, 13, 3), fn(count, 13, 3), fn(perc * 100, 6, 1), fn(cumperc * 100, 6, 1), s))
result.append('')
return return_or_print(result, as_str)
def key(self, x):
try:
x1 = float(x)
x2 = ''
except:
x1 = math.inf
x2 = x
return(x1, x2)
def animate(self, *args, **kwargs):
'''
animates the monitor in a panel
Parameters
----------
linecolor : colorspec
color of the line or points (default foreground color)
linewidth : int
width of the line or points (default 1 for line, 3 for points)
fillcolor : colorspec
color of the panel (default transparent)
bordercolor : colorspec
color of the border (default foreground color)
borderlinewidth : int
width of the line around the panel (default 1)
nowcolor : colorspec
color of the line indicating now (default red)
titlecolor : colorspec
color of the title (default foreground color)
titlefont : font
font of the title (default '')
titlefontsize : int
size of the font of the title (default 15)
as_points : bool
if False, lines will be drawn between the points |n|
if True (default), only the points will be shown
as_level : bool
if True (default for lines), the timestamped monitor is considered to be a level
if False (default for points), just the tallied values will be shown, and connected (for lines)
title : str
title to be shown above panel |n|
default: name of the monitor
x : int
x-coordinate of panel, relative to xy_anchor, default 0
y : int
y-coordinate of panel, relative to xy_anchor. default 0