-
Notifications
You must be signed in to change notification settings - Fork 5
/
ProgressBar.m
866 lines (691 loc) · 32.7 KB
/
ProgressBar.m
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
classdef ProgressBar < matlab.System
%PROGRESSBAR A class to provide a convenient and useful progress bar
% -------------------------------------------------------------------------
% This class mimics the design and some features of the TQDM
% (https://github.com/tqdm/tqdm) progress bar in python. All optional
% functionalities are set via name-value pairs in the constructor after the
% argument of the total numbers of iterations used in the progress (which
% can also be empty if unknown or even neglected if no name-value pairs are
% passed). The central class' method is 'step()' to increment the
% progress state of the object.
%
% Usage: pbar = ProgressBar()
% pbar = ProgressBar(total)
% pbar = ProgressBar(total, Name, Value)
%
% where 'total' is the total number of iterations.
%
%
% ProgressBar Properties:
% Total - the total number of iterations [default: []]
% Title - the progress bar's title shown in front [default: 'Processing']
% Unit - the unit of the update process. Can either be 'Iterations' or
% 'Bytes' [default: 'Iterations']
% UpdateRate - the progress bar's update rate in Hz. Defines the printing
% update interval [default: 5 Hz]
%
%
% ProgressBar Methods:
% ProgressBar - class constructor
% release - clean up and finish the progress bar's internal state
% printMessage - print some infos during the iterations. Messages get
% printed above the bar and the latter shifts one row down
% setup - not needed in a common application. Tiny helper function when
% setting up nested loops to print a parent bar before the first
% update occured. When the inner loop takes long, a nasty white
% space is shown in place of the parent bar until the first
% update takes place. This function can be used as a remedy.
% step - the central update method to increment the internal progress
% state
%
% Author : J.-A. Adrian (JA) <jensalrik.adrian AT gmail.com>
%
properties (Constant)
% Tag every timer with this to find it properly
TIMER_TAG_NAME = 'ProgressBar';
VERSION = '3.3.0';
end
properties (Nontunable)
% Total number of iterations to compute progress and ETA
Total;
% Titel of the progress bar if desired. Shown in front of the bar
Title = 'Processing';
% The visual printing rate in Hz. Default is 5 Hz
UpdateRate = 5;
% The unit of each update. Can be either 'Iterations' or 'Bytes'.
% Default is 'Iterations'.
Unit = 'Iterations';
% Directory in which the worker binary files are being saved when in
% parallel mode.
WorkerDirectory = tempdir;
end
properties (Logical, Nontunable)
% Boolean whether to activate progress bar at all
% useful for non-interactive / batch / hpc usage
IsActive = true;
% Boolean whether to use Unicode symbols or ASCII hash symbols (i.e. #)
UseUnicode = true;
% Boolean whether the progress bar is to be used in parallel computing setup
IsParallel = false;
% Boolean whether to override Windows' monospaced font to cure "growing bar" syndrome
OverrideDefaultFont = false;
end
properties (Access = private)
Bar = '';
IterationCounter = 0;
NumWrittenCharacters = 0;
FractionMainBlock;
FractionSubBlock;
HasTotalIterations = false;
HasBeenUpdated = false;
HasFiniteUpdateRate = true;
HasItPerSecBelow1 = false;
BlockCharacters;
IsTimerRunning = false;
TicObject;
TimerObject;
MaxBarWidth = 90;
CurrentTitleState = '';
CurrentFont;
end
properties (Constant, Hidden)
% The number of sub blocks in one main block of width of a character.
% HTML 'left blocks' go in eigths -> 8 sub blocks in one main block
NUM_SUB_BLOCKS = 8;
% The number of characters the title string should shift each cycle
NUM_CHARACTERS_SHIFT = 3;
% The maximum length of the title string without banner cycling
MAX_TITLE_LENGTH = 20;
OVERRIDE_FONT_NAME = 'Courier New';
end
properties (Access = private, Dependent)
IsThisBarNested;
end
methods
% Class Constructor
function [obj] = ProgressBar(total, varargin)
if nargin
obj.Total = total;
obj.setProperties(nargin-1, varargin{:});
end
if ~isempty(obj.Total)
obj.HasTotalIterations = true;
end
if isinf(obj.UpdateRate)
obj.HasFiniteUpdateRate = false;
end
% check if prog. bar runs in deployed mode and if so, switch to
% ASCII symbols and a smaller bar width
if isdeployed
obj.UseUnicode = false;
obj.MaxBarWidth = 72;
end
% setup ASCII symbols if desired
if obj.UseUnicode
obj.BlockCharacters = ProgressBar.getUnicodeSubBlocks();
else
obj.BlockCharacters = ProgressBar.getAsciiSubBlocks();
end
end
function [] = printMessage(obj, message, shouldPrintNextProgBar)
%PRINTMESSAGE class method to print a message while prog bar running
%----------------------------------------------------------------------
% This method lets the user print a message during the processing. A
% normal fprintf() or disp() would break the bar so this method can be
% used to print information about iterations or debug infos.
%
% Usage: obj.printMessage(obj, message)
% obj.printMessage(obj, message, shouldPrintNextProgBar)
%
% Input: ---------
% message - the message that should be printed to screen
% shouldPrintNextProgBar - Boolean to define wether to
% immidiately print another prog. bar
% after print the success message. Can
% be usefule when every iteration takes
% a long time and a white space appears
% where the progress bar used to be.
% [default: shouldPrintNextProgBar = false]
%
% input parsing and validation
narginchk(2, 3);
if nargin < 3 || isempty(shouldPrintNextProgBar)
shouldPrintNextProgBar = false;
end
validateattributes(shouldPrintNextProgBar, ...
{'logical', 'numeric'}, ...
{'scalar', 'binary', 'nonempty', 'nonnan'} ...
);
% remove the current prog bar
fprintf(1, ProgressBar.backspace(obj.NumWrittenCharacters));
% print the message and break the line
fprintf(1, '\t');
fprintf(1, message);
fprintf(1, '\n');
% reset the number of written characters
obj.NumWrittenCharacters = 0;
% if the next prog bar should be printed immideately do this
if shouldPrintNextProgBar
obj.printProgressBar();
end
end
function [yesNo] = get.IsThisBarNested(obj)
% If there are more than one timer object with our tag, the current
% bar must be nested
yesNo = length(obj.getTimerList()) > 1;
end
end
methods (Access = protected)
function [] = validatePropertiesImpl(obj)
valFunStrings = @(in) validateattributes(in, {'char'}, {'nonempty'});
valFunNumeric = @(in) validateattributes(in, ...
{'numeric'}, ...
{'scalar', 'positive', 'real', 'nonempty', 'nonnan'} ...
);
valFunBoolean = @(in) validateattributes(in, ...
{'logical', 'numeric'}, ...
{'scalar', 'binary', 'nonnan', 'nonempty'} ...
);
assert(ProgressBar.checkInputOfTotal(obj.Total));
assert(any(strcmpi(obj.Unit, {'Iterations', 'Bytes'})));
valFunStrings(obj.Title);
valFunStrings(obj.WorkerDirectory);
valFunNumeric(obj.UpdateRate);
valFunBoolean(obj.UseUnicode);
valFunBoolean(obj.IsParallel);
end
function [] = setupImpl(obj)
if obj.IsActive
% get a new tic object
obj.TicObject = tic;
% workaround for issue "Bar Gets Longer With Each Iteration" on windows systems
s = settings;
if obj.OverrideDefaultFont && ispc()
% store current font to reset the code font back to this value in the release() method
obj.CurrentFont = s.matlab.fonts.codefont.Name.ActiveValue;
% change to Courier New which is shipped by every Windows distro since Windows 3.1
s.matlab.fonts.codefont.Name.TemporaryValue = ob.OVERRIDE_FONT_NAME;
end
% add a new timer object with the standard tag name and hide it
obj.TimerObject = timer(...
'Tag', obj.TIMER_TAG_NAME, ...
'ObjectVisibility', 'off' ...
);
% if the bar should not be printed in every iteration setup the
% timer to the desired update rate
if obj.HasFiniteUpdateRate
obj.setupTimer();
end
% if 'Total' is known setup the bar correspondingly and compute
% some constant values
if obj.HasTotalIterations
% initialize the progress bar and pre-compute some measures
obj.setupBar();
obj.computeBlockFractions();
end
obj.CurrentTitleState = obj.Title;
if length(obj.Title) > obj.MAX_TITLE_LENGTH
obj.CurrentTitleState = [obj.CurrentTitleState, ' -- '];
end
% if the bar is used in a parallel setup start the timer right now
if obj.IsParallel
obj.startTimer();
end
% if this is a nested bar hit return
if obj.IsThisBarNested
fprintf(1, '\n');
end
obj.printProgressBar();
end
end
function [] = stepImpl(obj, stepSize, wasSuccessful, shouldPrintNextProgBar)
%STEPIMPL class method to increment the object's progress state
%----------------------------------------------------------------------
% This method is the central update function in the loop to indicate
% the increment of the progress. Pass empty arrays for each input
% argument if default is desired.
%
% Usage: obj.step(stepSize, wasSuccessful, shouldPrintNextProgBar)
%
% Input: ---------
% stepSize - the size of the progress step when the method is
% called. This can be used to pass the number of
% processed bytes when using 'Bytes' as units.
% [default: stepSize = 1]
% wasSuccessful - Boolean to provide information about the
% success of an individual iteration. If you pass
% a 'false' a message will be printed stating the
% current iteration was not successful.
% [default: wasSuccessful = true]
% shouldPrintNextProgBar - Boolean to define wether to
% immidiately print another prog. bar
% after print the success message. Can
% be useful when every iteration takes
% a long time and a white space appears
% where the progress bar used to be.
% [default: shouldPrintNextProgBar = false]
%
% input parsing and validating
if isempty(shouldPrintNextProgBar)
shouldPrintNextProgBar = false;
end
if isempty(wasSuccessful)
wasSuccessful = true;
end
if isempty(stepSize)
stepSize = 1;
end
validateattributes(stepSize, ...
{'numeric'}, ...
{'scalar', 'positive', 'real', 'nonnan', 'finite', 'nonempty'} ...
);
validateattributes(wasSuccessful, ...
{'logical', 'numeric'}, ...
{'scalar', 'binary', 'nonnan', 'nonempty'} ...
);
validateattributes(shouldPrintNextProgBar, ...
{'logical', 'numeric'}, ...
{'scalar', 'binary', 'nonnan', 'nonempty'} ...
);
if obj.IsActive
% increment the iteration counter
obj.incrementIterationCounter(stepSize);
% if the timer was stopped before, because no update was given,
% start it now again.
if ~obj.IsTimerRunning && obj.HasFiniteUpdateRate
obj.startTimer();
end
% if the iteration was not successful print a message saying so.
if ~wasSuccessful
infoMsg = sprintf('Iteration %i was not successful!', ...
obj.IterationCounter);
obj.printMessage(infoMsg, shouldPrintNextProgBar);
end
% when the bar should be updated in every iteration, do this with
% each time calling update()
if ~obj.HasFiniteUpdateRate
obj.printProgressBar();
end
% stop the timer after the last iteration if an update rate is
% used. The first condition is needed to prevent the if-statement
% to fail if obj.Total is empty. This happens when no total number
% of iterations was passed / is known.
if ~isempty(obj.Total) ...
&& obj.IterationCounter == obj.Total ...
&& obj.HasFiniteUpdateRate
obj.stopTimer();
end
end
end
function [] = releaseImpl(obj)
% stop the timer
if obj.IsTimerRunning
obj.stopTimer();
end
if obj.IsThisBarNested
% when this prog bar was nested, remove it from the command
% line and get back to the end of the parent bar.
% +1 due to the line break
fprintf(1, ProgressBar.backspace(obj.NumWrittenCharacters + 1));
elseif obj.IterationCounter && ~obj.IsThisBarNested
% when a non-nested progress bar has been plotted, hit return
fprintf(1, '\n');
end
% delete the timer object
delete(obj.TimerObject);
% restore previously used font
if obj.OverrideDefaultFont && ~isempty(obj.CurrentFont)
s = settings;
s.matlab.fonts.codefont.Name.TemporaryValue = obj.CurrentFont;
end
% if used in parallel processing delete all aux. files and clear
% the persistent variables inside of updateParallel()
if obj.IsParallel
files = ProgressBar.findWorkerFiles(obj.WorkerDirectory);
if ~isempty(files)
delete(files{:});
end
clear updateParallel;
% rest some time to not flood the screen with the parent bar
pause(0.1);
end
end
function [] = computeBlockFractions(obj)
% Compute the progress percentage of a single main and a single sub
% block
obj.FractionMainBlock = 1 / length(obj.Bar);
obj.FractionSubBlock = obj.FractionMainBlock / obj.NUM_SUB_BLOCKS;
end
function [] = setupBar(obj)
% Set up the growing bar part of the printed line by computing the
% width of it
[~, preBarFormat, postBarFormat] = obj.returnFormatString();
% insert worst case inputs to get (almost) maximum length of bar
preBar = sprintf(...
preBarFormat, ...
blanks(min(length(obj.CurrentTitleState), obj.MAX_TITLE_LENGTH)), ...
100 ...
);
postBar = sprintf(...
postBarFormat, ...
obj.Total, ...
obj.Total, ...
10, 60, 60, 10, 60, 60, 1e2 ...
);
lenBar = obj.MaxBarWidth - length(preBar) - length(postBar);
obj.Bar = blanks(lenBar);
end
function [] = printProgressBar(obj)
% This method removes the old and prints the current bar to the screen
% and saves the number of written characters for the next iteration
% remove old previous bar
fprintf(1, ProgressBar.backspace(obj.NumWrittenCharacters));
formatString = obj.returnFormatString();
argumentList = obj.returnArgumentList();
% print new bar
obj.NumWrittenCharacters = fprintf(1, ...
formatString, ...
argumentList{:} ...
);
end
function [format, preString, postString] = returnFormatString(obj)
% This method returns the format string for the fprintf() function in
% printProgressBar()
% use the correct units
if strcmp(obj.Unit, 'Bytes')
unitString = 'K';
if obj.HasItPerSecBelow1
fractionString = {'s', 'KB'};
else
fractionString = {'KB', 's'};
end
else
unitString = 'it';
if obj.HasItPerSecBelow1
fractionString = {'s', 'it'};
else
fractionString = {'it', 's'};
end
end
% consider a growing bar if the total number of iterations is known
% and consider a title if one is given.
if obj.HasTotalIterations
preString = '%s: %03.0f%% ';
centerString = '|%s|';
postString = ...
[
' %i/%i', unitString, ...
' [%02.0f:%02.0f:%02.0f<%02.0f:%02.0f:%02.0f, %.2f ', ...
fractionString{1}, '/', fractionString{2}, ']'
];
format = [preString, centerString, postString];
else
preString = '';
postString = '';
format = [
'%s: %i', unitString, ' [%02.0f:%02.0f:%02.0f, %.2f ', ...
fractionString{1}, '/', fractionString{2}, ']'
];
end
end
function [argList] = returnArgumentList(obj)
% This method returns the argument list as a cell array for the
% fprintf() function in printProgressBar()
% elapsed time (ET)
thisTimeSec = toc(obj.TicObject);
etHoursMinsSecs = ProgressBar.convertTime(thisTimeSec);
% mean iterations per second counted from the start
iterationsPerSecond = obj.IterationCounter / thisTimeSec;
if iterationsPerSecond < 1
iterationsPerSecond = 1 / iterationsPerSecond;
obj.HasItPerSecBelow1 = true;
else
obj.HasItPerSecBelow1 = false;
end
% consider the correct units
scaledIteration = obj.IterationCounter;
scaledTotal = obj.Total;
if strcmp(obj.Unit, 'Bytes')
% let's show KB
scaledIteration = round(scaledIteration / 1000);
scaledTotal = round(scaledTotal / 1000);
iterationsPerSecond = iterationsPerSecond / 1000;
end
if obj.HasTotalIterations
% 1 : Title
% 2 : progress percent
% 3 : progBar string
% 4 : iterationCounter
% 5 : Total
% 6 : ET.hours
% 7 : ET.minutes
% 8 : ET.seconds
% 9 : ETA.hours
% 10: ETA.minutes
% 11: ETA.seconds
% 12: it/s
% estimated time of arrival (ETA)
[etaHoursMinsSecs] = obj.estimateETA(thisTimeSec);
if obj.IterationCounter
% usual case -> the iteration counter is > 0
barString = obj.getCurrentBar;
else
% if startMethod() calls this method return the empty bar
barString = obj.Bar;
end
argList = {
obj.CurrentTitleState(...
1:min(length(obj.Title), obj.MAX_TITLE_LENGTH) ...
), ...
floor(obj.IterationCounter / obj.Total * 100), ...
barString, ...
scaledIteration, ...
scaledTotal, ...
etHoursMinsSecs(1), ...
etHoursMinsSecs(2), ...
etHoursMinsSecs(3), ...
etaHoursMinsSecs(1), ...
etaHoursMinsSecs(2), ...
etaHoursMinsSecs(3), ...
iterationsPerSecond ...
};
else
% 1: Title
% 2: iterationCounter
% 3: ET.hours
% 4: ET.minutes
% 5: ET.seconds
% 6: it/s
argList = {
obj.CurrentTitleState(...
1:min(length(obj.Title), obj.MAX_TITLE_LENGTH) ...
), ..., ...
scaledIteration, ...
etHoursMinsSecs(1), ...
etHoursMinsSecs(2), ...
etHoursMinsSecs(3), ...
iterationsPerSecond ...
};
end
% cycle the bar's title
obj.updateCurrentTitle();
end
function [barString] = getCurrentBar(obj)
% This method constructs the growing bar part of the printed line by
% indexing the correct part of the blank bar and getting either a
% Unicode or ASCII symbol.
% set up the bar and the current progress as a ratio
lenBar = length(obj.Bar);
currProgress = obj.IterationCounter / obj.Total;
% index of the current main block
thisMainBlock = min(ceil(currProgress / obj.FractionMainBlock), lenBar);
% index of the current sub block
continuousBlockIndex = ceil(currProgress / obj.FractionSubBlock);
thisSubBlock = mod(continuousBlockIndex - 1, obj.NUM_SUB_BLOCKS) + 1;
% fix for non-full last blocks when steps are large: make them full
obj.Bar(1:max(thisMainBlock-1, 0)) = ...
repmat(obj.BlockCharacters(end), 1, thisMainBlock - 1);
% return a full bar in the last iteration or update the current
% main block
if obj.IterationCounter == obj.Total
obj.Bar = repmat(obj.BlockCharacters(end), 1, lenBar);
else
obj.Bar(thisMainBlock) = obj.BlockCharacters(thisSubBlock);
end
barString = obj.Bar;
end
function [etaHoursMinsSecs] = estimateETA(obj, elapsedTime)
% This method estimates linearly the remaining time
% the current progress as ratio
progress = obj.IterationCounter / obj.Total;
% the remaining seconds
remainingSeconds = elapsedTime * ((1 / progress) - 1);
% convert seconds to hours:mins:seconds
etaHoursMinsSecs = ProgressBar.convertTime(remainingSeconds);
end
function [] = setupTimer(obj)
% This method initializes the timer object if an upate rate is used
obj.TimerObject.BusyMode = 'drop';
obj.TimerObject.ExecutionMode = 'fixedSpacing';
if ~obj.IsParallel
obj.TimerObject.TimerFcn = @(~, ~) obj.timerCallback();
obj.TimerObject.StopFcn = @(~, ~) obj.timerCallback();
else
obj.TimerObject.TimerFcn = @(~, ~) obj.timerCallbackParallel();
obj.TimerObject.StopFcn = @(~, ~) obj.timerCallbackParallel();
end
updatePeriod = round(1 / obj.UpdateRate * 1000) / 1000;
obj.TimerObject.Period = updatePeriod;
end
function [] = timerCallback(obj)
% This method is the timer callback. If an update came in between the
% last printing and now print a new prog bar, else stop the timer and
% wait.
if obj.HasBeenUpdated
obj.printProgressBar();
else
obj.stopTimer();
end
obj.HasBeenUpdated = false;
end
function [] = timerCallbackParallel(obj)
% find the aux. worker files
[files, numFiles] = ProgressBar.findWorkerFiles(obj.WorkerDirectory);
% if none have been written yet just print a progressbar and return
if ~numFiles
obj.printProgressBar();
return;
end
% read the status in every file
results = zeros(numFiles, 1);
for iFile = 1:numFiles
fid = fopen(files{iFile}, 'rb');
if fid > 0
results(iFile) = fread(fid, 1, 'uint64');
fclose(fid);
end
end
% the sum of all files should be the current iteration
obj.IterationCounter = sum(results);
% print the progress bar
obj.printProgressBar();
% if total is known and we are at the end stop the timer
if ~isempty(obj.Total) && obj.IterationCounter == obj.Total
obj.stopTimer();
end
end
function [] = startTimer(obj)
% This method starts the timer object and updates the status bool
start(obj.TimerObject);
obj.IsTimerRunning = true;
end
function [] = stopTimer(obj)
% This method stops the timer object and updates the status bool
stop(obj.TimerObject);
obj.IsTimerRunning = false;
end
function [] = incrementIterationCounter(obj, stepSize)
% This method increments the iteration counter and updates the status
% bool
obj.IterationCounter = obj.IterationCounter + stepSize;
obj.HasBeenUpdated = true;
end
function [list] = getTimerList(obj)
% This function returns the list of all hidden timers which are tagged
% with our default tag
list = timerfindall('Tag', obj.TIMER_TAG_NAME);
end
function [] = updateCurrentTitle(obj)
strTitle = obj.CurrentTitleState;
if length(strTitle) > obj.MAX_TITLE_LENGTH
strTitle = circshift(strTitle, -obj.NUM_CHARACTERS_SHIFT);
obj.CurrentTitleState = strTitle;
end
end
end
methods (Static)
function deleteAllTimers()
delete(timerfindall('Tag', ProgressBar.TIMER_TAG_NAME));
end
function [blocks] = getUnicodeSubBlocks()
% This function returns the HTML 'left blocks' to construct the growing bar. The HTML
% 'left blocks' range from 1 to 8 excluding the 'space'.
blocks = [
char(9615), ...
char(9614), ...
char(9613), ...
char(9612), ...
char(9611), ...
char(9610), ...
char(9609), ...
char(9608) ...
];
end
function [blocks] = getAsciiSubBlocks()
% This function returns the ASCII number signs (hashes) to construct the growing bar.
% The HTML 'left blocks' range from 1 to 8 excluding the 'space'.
blocks = repmat('#', 1, 8);
end
function [str] = backspace(numChars)
% This function returns the desired numbers of backspaces to delete characters from the
% current line
str = repmat(sprintf('\b'), 1, numChars);
end
function [hoursMinsSecs] = convertTime(secondsIn)
% This fast implementation to convert seconds to hours:mins:seconds using mod() stems
% from http://stackoverflow.com/a/21233409
hoursMinsSecs = floor(mod(secondsIn, [0, 3600, 60]) ./ [3600, 60, 1]);
end
function [isOk] = checkInputOfTotal(total)
% This function is the input checker of the main constructor argument 'total'. It is ok
% if it's empty but if not it must obey validateattributes.
isTotalEmpty = isempty(total);
if isTotalEmpty
isOk = true;
return;
else
validateattributes(total, ...
{'numeric'}, ...
{'scalar', 'integer', 'positive', 'real', 'nonnan', 'finite'} ...
);
isOk = true;
end
end
function [files, numFiles] = findWorkerFiles(workerDir)
% This function returns file names and the number of files that were written by the
% updateParallel() function if the prog. bar is used in a parallel setup.
%
% Input: workerDir - directory where the aux. files of the worker are saved
%
[pattern] = updateParallel();
files = dir(fullfile(workerDir, pattern));
files = {files.name};
files = cellfun(...
@(filename) fullfile(workerDir, filename), ...
files, ...
'uni', false ...
);
numFiles = length(files);
end
end
end