-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdraw.m
914 lines (814 loc) · 33.7 KB
/
draw.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
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
function draw
%%%%%% VISUALIZATION: Generates plots of cells and substrates
load('ResultsSim.mat')
load('R.mat')
fprintf('\n VISUALIZATION >>>> \n')
prompt = '\n>> Graphics (default [0]):\n [1] - Bacteria\n [2] - Average of Substrates, Products and Biomass with time\n [3] - Diffusion of Substrates or Products in the liquid phase\n [4] - pH\n [5] - Gibbs energy of microbial catabolism \n [6] - Gibbs energy of microbial anabolism \n\n [0] - Nothing - End of the program\n\n>> Answer: ';
x = input(prompt);
if isempty(x)
x = 0;
end
while x ~= 0
if x == 1
draw_bacteria(R, B)
elseif x == 2
draw_substrate(R, Sxy, All_StatesVar, B, 1) %#ok<*NODEF>
elseif x == 3
draw_substrate(R, Sxy, All_StatesVar, B, 2)
elseif x == 4
draw_pH(R, pH, All_StatesVar(:,1))
elseif x == 5
draw_thermo(R, DGRCat, All_StatesVar(:,1))
elseif x == 6
draw_thermo(R, DGRAn, All_StatesVar(:,1))
end
x = input(prompt);
end
fprintf('\n>>>>>>>>> END of the program. See you later alligator !\n')
return
end
function draw_bacteria(R, B)
n_sp = R.St.numX;
CM = hsv(double(n_sp)); %Array of colours for plotting
writerObjB = VideoWriter('bacteria.avi');
writerObjB.FrameRate = 2.3;
open(writerObjB);
for k=1:n_sp % Assignation of a colour to a microbial species
fprintf('\n Microbial Species %d: %s %d bacteria.>> COLOUR: ',k,char(R.rm.rNamesX(k)), R.bac.bac_ns(k))
cprintf(CM(k,:),['GROUP - ',char(R.rm.rNamesX(k)),'\n']);
end
fprintf('\nTOTAL Number of cells: %d\n', R.bac.bac_n)
fprintf('\n>>> Bacterial growth with time ... ')
% Plot and video of bacteria
fB=figure('Name','bacterias','PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 700 200 700 500 ],'Color','w');
% maxix = max(max(B(:,2,:)))+2*R.bac.bac_rmax;
maxix = R.Sxy.maxxSys;
maxiy = max(max(B(:,3,:)))+2*R.bac.bac_rmax;
% minix = min(min((B(:,5,:)== 0).*10000+B(:,2,:)))-2*R.bac.bac_rmax;
minix = 0;
miniy = min(min((B(:,5,:)== 0).*10000+B(:,3,:)))-2*R.bac.bac_rmax;
for i = 1:size(B,3)
figure(fB)
clf;
Time = B(1,1,i);
bac_x = B(:,2,i);
bac_y = B(:,3,i);
bac_s = B(:,4,i);
bac_r = B(:,5,i);
for k=1:length(bac_x)
if bac_s(k)>0
col = CM(bac_s(k),:);
rectangle('Curvature',[1 1],'Position',[bac_x(k)-bac_r(k) bac_y(k)-bac_r(k) 2*bac_r(k) 2*bac_r(k)],'LineWidth',1,'FaceColor',col,'EdgeColor',col);
end
end
axis equal; axis([minix maxix miniy maxiy]);
% axis([0 R.Sxy.maxx 0 R.Sxy.maxy]);
numBac = sum(ne(bac_s,0));
xlabel('x')
ylabel('y')
title({[num2str(n_sp),' types of Bacteria',];['Time = ',num2str(Time),' hours. ','Number of bacteria = ',num2str(numBac)]})
drawnow;
frame = getframe(fB);
writeVideo(writerObjB,frame);
end
writeVideo(writerObjB,frame);
writeVideo(writerObjB,frame);
writeVideo(writerObjB,frame);
writeVideo(writerObjB,frame);
close(writerObjB);
fprintf('\nTotal size of the space discretization x: %.3e y: %.3e', R.Sxy.maxxSys, R.Sxy.maxySys)
fprintf('\nTotal size ocupied by bacteria x: %.3e y: %e', maxix - minix, maxiy - miniy)
fprintf('\nDiscretization size Dx: %.3e Dy: %.3e', R.Sxy.dx, R.Sxy.dx)
fprintf('\nDiscretization steps in the biofilm Dx: %.3f Dy: %.3f\n', (maxix - minix)/R.Sxy.dx, (maxiy - miniy)/R.Sxy.dx)
fprintf('END\n')
end
function draw_substrate(R, Sxy, All_StatesVar, B, flag)
time = All_StatesVar(:,1);
if flag == 2
fprintf('\nSelect substrate to display diffusion (default [1]):\n')
for i = 1: R.St.numStVLiq2
fprintf('[%i] - %s\n', i, char(R.St.StNames(i)))
end
prompt = '\n>> Answer: ';
j = input(prompt);
if isempty(j)
j = 1;
end
fprintf('\n>>> Diffusion of %s ... ', char(R.St.StNames(j)))
nT = size(Sxy,3);
Si = reshape(Sxy(:,j,:),R.Sxy.nySys-2,R.Sxy.nxSys-2,nT);
Smax = max(R.Sxy.Sbc_Dir(j),max(max(max(Si))));
writerObjS = VideoWriter('diffusion.avi');
open(writerObjS);
minix = 0;
miniy = 0;
maxix = R.Sxy.maxxSys;
maxiy = R.Sxy.maxySys;
fS=figure('Name',['Substrate/Product: ',char(R.St.StNames(j))],'PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 50 200 500 500 ],'Color','w');
for i = 1:nT
figure(fS)
surf(R.Sxy.x_pnSys,R.Sxy.y_pnSys,Si(:,:,i),'EdgeColor','none'); %plotting the field variable
shading interp
axis ([minix maxix miniy maxiy 0 Smax])
title({['2-D Diffusion with {\nu} = ',num2str(R.kTr.Diffn(j))];['time (\itt) = ',num2str(time(i))]})
xlabel('Spatial co-ordinate (x) \rightarrow')
ylabel('{\leftarrow} Spatial co-ordinate (y)')
zlabel('Transport property profile (u) \rightarrow')
drawnow;
% pause
frame = getframe(fS);
writeVideo(writerObjS,frame);
end
close(writerObjS);
fprintf('END\n')
else
fprintf('\n>>> Evolution of Substrates and Products with time ... ')
% Plot of liquid substrates
fL = figure('Name','LIQUID Chemicals','PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 50 200 500 500 ],'Color','w');
figure(fL)
n_Liq = sum(strcmp(R.St.Phase,'L'));
l = R.St.StNames(1:n_Liq,1);
for i = 1: n_Liq
plot(time, All_StatesVar(:,i+1))
hold on
end
legend(l);
% savefig(fL,'SPLiquids.fig')
% Plot of Ntotal
fNtotal = figure('Name','Ntotal','PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 75 200 500 500 ],'Color','w');
figure(fNtotal)
nt = {'Ntotal','NH3 Inf'};
plot(time, All_StatesVar(:,end));
hold on
plot(time, R.Inf.St(1)*ones(size(time)), 'r');
hold off
legend(nt);
% Plot of HRT
HRT = figure('Name','HRT','PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 75 200 500 500 ],'Color','w');
figure(HRT)
nhrt = 'HRT';
plot(time, All_StatesVar(:,end-1));
legend(nhrt);
% Plot of liquid substrates
fP = figure('Name','CHARGES Chemicals','PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 75 200 500 500 ],'Color','w');
figure(fP)
n_Ph = sum(strcmp(R.St.Phase,'P'));
p = R.St.StNames(n_Liq+1:n_Liq+n_Ph,1);
for i = 1: n_Ph
plot(time, All_StatesVar(:,n_Liq+i+1))
hold on
end
legend(p);
% savefig(fP,'SPCharges.fig')
% Plot of gas substrates
fG=figure('Name','GAS Chemicals','PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 100 200 500 500 ],'Color','w');
figure(fG)
n_Gas = sum(strcmp(R.St.Phase,'G'));
g = R.St.StNames(n_Liq+n_Ph+1:n_Liq+n_Ph+n_Gas,1);
for i = 1: n_Gas
plot(time, All_StatesVar(:,n_Liq+n_Ph+i+1))
hold on
end
legend(g);
% savefig(fG,'SPGas.fig')
% Plot of biomass
fX=figure('Name','Biomass overall','PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 100 200 500 500 ],'Color','w');
figure(fX)
n_X = sum(strcmp(R.St.Phase,'S'));
x = R.St.StNames(n_Liq+n_Ph+n_Gas+1:n_Liq+n_Ph+n_Gas+n_X,1);
for i = 1: n_X
plot(time, All_StatesVar(:,n_Liq+n_Ph+n_Gas+i+1))
hold on
end
legend(x);
% Plot of biomass
fX=figure('Name','Biomass Number','PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 100 200 500 500 ],'Color','w');
figure(fX)
n_X = sum(strcmp(R.St.Phase,'S'));
x = R.St.StNames(n_Liq+n_Ph+n_Gas+1:n_Liq+n_Ph+n_Gas+n_X,1);
ns = zeros(size(B,3),n_X);
for j = 1:size(B,3)
bac_s = B(:,4,j);
for i = 1: n_X
ns(j,i) = sum(bac_s == i);
end
end
for i = 1: n_X
plot(time, ns(:,i))
hold on
end
legend(x);
fprintf('END\n')
end
end
function draw_pH(R, pH, time)
pHmax = max(max(pH));
writerObjS = VideoWriter('pH.avi');
open(writerObjS);
minix = 0;
miniy = 0;
maxix = R.Sxy.maxxSys;
maxiy = R.Sxy.maxySys;
nT = size(pH,2);
Si = reshape(pH,R.Sxy.nySys-2,R.Sxy.nxSys-2,nT);
pHFig=figure('Name','pH','PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 50 200 500 500 ],'Color','w');
for i = 1:nT
figure(pHFig)
surf(R.Sxy.x_pnSys,R.Sxy.y_pnSys,Si(:,:,i),'EdgeColor','none'); %plotting the field variable
shading interp
axis ([minix maxix miniy maxiy 0 pHmax])
title({'pH';['time (\itt) = ',num2str(time(i))]})
xlabel('Spatial co-ordinate (x) \rightarrow')
ylabel('{\leftarrow} Spatial co-ordinate (y)')
zlabel('Transport property profile (u) \rightarrow')
drawnow;
frame = getframe(pHFig);
writeVideo(writerObjS,frame);
end
close(writerObjS);
fprintf('END\n')
end
function draw_thermo(R, DGR, time)
fprintf('\nSelect reaction to display DGR (default [1]):\n')
for i = 1: R.St.numX
fprintf('[%i] - %s\n', i, char(R.St.StNames(R.St.numStVLiq+i)))
end
prompt = '\n>> Answer: ';
j = input(prompt);
if isempty(j)
j = 1;
end
fprintf('\n>>> Catabolic DG of %s ... ', char(R.St.StNames(R.St.numStVLiq+j)))
nT = size(DGR,3);
Si = reshape(DGR(:,j,:),R.Sxy.nySys-2,R.Sxy.nxSys-2,nT);
writerObjS = VideoWriter('diffusion.avi');
open(writerObjS);
minix = 0;
miniy = 0;
maxix = R.Sxy.maxxSys;
maxiy = R.Sxy.maxySys;
fS=figure('Name',['Microbial specie: ',char(R.St.StNames(R.St.numStVLiq+j))],'PaperPosition',[0.05 0.0 3.5 3.5],'Position',[ 50 200 500 500 ],'Color','w');
for i = 1:nT
figure(fS)
Smax = max(max(Si(:,:,i)))+5; Smin = min(min(Si(:,:,i)))-5;
surf(R.Sxy.x_pnSys,R.Sxy.y_pnSys,Si(:,:,i),'EdgeColor','none'); %plotting the field variable
shading interp
axis ([minix maxix miniy maxiy Smin Smax])
title({['Catabolic Gibbs Energy of ',char(R.St.StNames(R.St.numStVLiq+j))];['time (\itt) = ',num2str(time(i))]})
xlabel('Spatial co-ordinate (x) \rightarrow')
ylabel('{\leftarrow} Spatial co-ordinate (y)')
zlabel('Gibbs energy (u) \rightarrow')
drawnow;
frame = getframe(fS);
writeVideo(writerObjS,frame);
end
close(writerObjS);
fprintf('END\n')
end
function count = cprintf(style,format,varargin)
%%%%%%% This function only generates the necessary code to be able to write with
%%%%%%% colours (necessary for the visualization)
% CPRINTF displays styled formatted text in the Command Window
%
% Syntax:
% count = cprintf(style,format,...)
%
% Description:
% CPRINTF processes the specified text using the exact same FORMAT
% arguments accepted by the built-in SPRINTF and FPRINTF functions.
%
% CPRINTF then displays the text in the Command Window using the
% specified STYLE argument. The accepted styles are those used for
% Matlab's syntax highlighting (see: File / Preferences / Colors /
% M-file Syntax Highlighting Colors), and also user-defined colors.
%
% The possible pre-defined STYLE names are:
%
% 'Text' - default: black
% 'Keywords' - default: blue
% 'Comments' - default: green
% 'Strings' - default: purple
% 'UnterminatedStrings' - default: dark red
% 'SystemCommands' - default: orange
% 'Errors' - default: light red
% 'Hyperlinks' - default: underlined blue
%
% 'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White'
%
% STYLE beginning with '-' or '_' will be underlined. For example:
% '-Blue' is underlined blue, like 'Hyperlinks';
% '_Comments' is underlined green etc.
%
% STYLE beginning with '*' will be bold (R2011b+ only). For example:
% '*Blue' is bold blue;
% '*Comments' is bold green etc.
% Note: Matlab does not currently support both bold and underline,
% only one of them can be used in a single cprintf command. But of
% course bold and underline can be mixed by using separate commands.
%
% STYLE also accepts a regular Matlab RGB vector, that can be underlined
% and bolded: -[0,1,1] means underlined cyan, '*[1,0,0]' is bold red.
%
% STYLE is case-insensitive and accepts unique partial strings just
% like handle property names.
%
% CPRINTF by itself, without any input parameters, displays a demo
%
% Example:
% cprintf; % displays the demo
% cprintf('text', 'regular black text');
% cprintf('hyper', 'followed %s','by');
% cprintf('key', '%d colored', 4);
% cprintf('-comment','& underlined');
% cprintf('err', 'elements\n');
% cprintf('cyan', 'cyan');
% cprintf('_green', 'underlined green');
% cprintf(-[1,0,1], 'underlined magenta');
% cprintf([1,0.5,0],'and multi-\nline orange\n');
% cprintf('*blue', 'and *bold* (R2011b+ only)\n');
% cprintf('string'); % same as fprintf('string') and cprintf('text','string')
%
% Bugs and suggestions:
% Please send to Yair Altman (altmany at gmail dot com)
%
% Warning:
% This code heavily relies on undocumented and unsupported Matlab
% functionality. It works on Matlab 7+, but use at your own risk!
%
% A technical description of the implementation can be found at:
% <a href="http://undocumentedmatlab.com/blog/cprintf/">http://UndocumentedMatlab.com/blog/cprintf/</a>
%
% Limitations:
% 1. In R2011a and earlier, a single space char is inserted at the
% beginning of each CPRINTF text segment (this is ok in R2011b+).
%
% 2. In R2011a and earlier, consecutive differently-colored multi-line
% CPRINTFs sometimes display incorrectly on the bottom line.
% As far as I could tell this is due to a Matlab bug. Examples:
% >> cprintf('-str','under\nline'); cprintf('err','red\n'); % hidden 'red', unhidden '_'
% >> cprintf('str','regu\nlar'); cprintf('err','red\n'); % underline red (not purple) 'lar'
%
% 3. Sometimes, non newline ('\n')-terminated segments display unstyled
% (black) when the command prompt chevron ('>>') regains focus on the
% continuation of that line (I can't pinpoint when this happens).
% To fix this, simply newline-terminate all command-prompt messages.
%
% 4. In R2011b and later, the above errors appear to be fixed. However,
% the last character of an underlined segment is not underlined for
% some unknown reason (add an extra space character to make it look better)
%
% 5. In old Matlab versions (e.g., Matlab 7.1 R14), multi-line styles
% only affect the first line. Single-line styles work as expected.
% R14 also appends a single space after underlined segments.
%
% 6. Bold style is only supported on R2011b+, and cannot also be underlined.
%
% Change log:
% 2015-06-24: Fixed a few discoloration issues (some other issues still remain)
% 2015-03-20: Fix: if command window isn't defined yet (startup) use standard fprintf as suggested by John Marozas
% 2012-08-09: Graceful degradation support for deployed (compiled) and non-desktop applications; minor bug fixes
% 2012-08-06: Fixes for R2012b; added bold style; accept RGB string (non-numeric) style
% 2011-11-27: Fixes for R2011b
% 2011-08-29: Fix by Danilo (FEX comment) for non-default text colors
% 2011-03-04: Performance improvement
% 2010-06-27: Fix for R2010a/b; fixed edge case reported by Sharron; CPRINTF with no args runs the demo
% 2009-09-28: Fixed edge-case problem reported by Swagat K
% 2009-05-28: corrected nargout behavior suggested by Andreas Gäb
% 2009-05-13: First version posted on <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">MathWorks File Exchange</a>
%
% See also:
% sprintf, fprintf
% License to use and modify this code is granted freely to all interested, as long as the original author is
% referenced and attributed as such. The original author maintains the right to be solely associated with this work.
% Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com
% $Revision: 1.10 $ $Date: 2015/06/24 01:29:18 $
persistent majorVersion minorVersion
if isempty(majorVersion)
%v = version; if str2double(v(1:3)) <= 7.1
%majorVersion = str2double(regexprep(version,'^(\d+).*','$1'));
%minorVersion = str2double(regexprep(version,'^\d+\.(\d+).*','$1'));
%[a,b,c,d,versionIdStrs]=regexp(version,'^(\d+)\.(\d+).*'); %#ok unused
v = sscanf(version, '%d.', 2);
majorVersion = v(1); %str2double(versionIdStrs{1}{1});
minorVersion = v(2); %str2double(versionIdStrs{1}{2});
end
% The following is for debug use only:
%global docElement txt el
if ~exist('el','var') || isempty(el), el=handle([]); end
if nargin<1, showDemo(majorVersion,minorVersion); return; end
if isempty(style), return; end
if all(ishandle(style)) && length(style)~=3
dumpElement(style);
return;
end
% Process the text string
if nargin<2, format = style; style='text'; end
%error(nargchk(2, inf, nargin, 'struct'));
%str = sprintf(format,varargin{:});
% In compiled mode
try useDesktop = usejava('desktop'); catch, useDesktop = false; end
if isdeployed | ~useDesktop %#ok<OR2> - for Matlab 6 compatibility
% do not display any formatting - use simple fprintf()
% See: http://undocumentedmatlab.com/blog/bold-color-text-in-the-command-window/#comment-103035
% Also see: https://mail.google.com/mail/u/0/?ui=2&shva=1#all/1390a26e7ef4aa4d
% Also see: https://mail.google.com/mail/u/0/?ui=2&shva=1#all/13a6ed3223333b21
count1 = fprintf(format,varargin{:});
else
% Else (Matlab desktop mode)
% Get the normalized style name and underlining flag
[underlineFlag, boldFlag, style, debugFlag] = processStyleInfo(style);
% Set hyperlinking, if so requested
if underlineFlag
format = ['<a href="">' format '</a>'];
% Matlab 7.1 R14 (possibly a few newer versions as well?)
% have a bug in rendering consecutive hyperlinks
% This is fixed by appending a single non-linked space
if majorVersion < 7 || (majorVersion==7 && minorVersion <= 1)
format(end+1) = ' ';
end
end
% Set bold, if requested and supported (R2011b+)
if boldFlag
if (majorVersion > 7 || minorVersion >= 13)
format = ['<strong>' format '</strong>'];
else
boldFlag = 0;
end
end
% Get the current CW position
cmdWinDoc = com.mathworks.mde.cmdwin.CmdWinDocument.getInstance;
lastPos = cmdWinDoc.getLength;
% If not beginning of line
bolFlag = 0; %#ok
%if docElement.getEndOffset - docElement.getStartOffset > 1
% Display a hyperlink element in order to force element separation
% (otherwise adjacent elements on the same line will be merged)
if majorVersion<7 || (majorVersion==7 && minorVersion<13)
if ~underlineFlag
fprintf('<a href=""> </a>'); %fprintf('<a href=""> </a>\b');
elseif format(end)~=10 % if no newline at end
fprintf(' '); %fprintf(' \b');
end
end
%drawnow;
bolFlag = 1;
%end
% Get a handle to the Command Window component
mde = com.mathworks.mde.desk.MLDesktop.getInstance;
cw = mde.getClient('Command Window');
% Fix: if command window isn't defined yet (startup), use standard fprintf()
if (isempty(cw))
count1 = fprintf(format,varargin{:});
if nargout
count = count1;
end
return;
end
xCmdWndView = cw.getComponent(0).getViewport.getComponent(0);
% Store the CW background color as a special color pref
% This way, if the CW bg color changes (via File/Preferences),
% it will also affect existing rendered strs
com.mathworks.services.Prefs.setColorPref('CW_BG_Color',xCmdWndView.getBackground);
% Display the text in the Command Window
% Note: fprintf(2,...) is required in order to add formatting tokens, which
% ^^^^ can then be updated below (no such tokens when outputting to stdout)
count1 = fprintf(2,format,varargin{:});
% Repaint the command window
%awtinvoke(cmdWinDoc,'remove',lastPos,1); % TODO: find out how to remove the extra '_'
drawnow; % this is necessary for the following to work properly (refer to Evgeny Pr in FEX comment 16/1/2011)
xCmdWndView.repaint;
%hListeners = cmdWinDoc.getDocumentListeners; for idx=1:numel(hListeners), try hListeners(idx).repaint; catch, end, end
docElement = cmdWinDoc.getParagraphElement(lastPos+1);
if majorVersion<7 || (majorVersion==7 && minorVersion<13)
if bolFlag && ~underlineFlag
% Set the leading hyperlink space character ('_') to the bg color, effectively hiding it
% Note: old Matlab versions have a bug in hyperlinks that need to be accounted for...
%disp(' '); dumpElement(docElement)
setElementStyle(docElement,'CW_BG_Color',1+underlineFlag,majorVersion,minorVersion); %+getUrlsFix(docElement));
%disp(' '); dumpElement(docElement)
el(end+1) = handle(docElement); % #ok used in debug only
end
% Fix a problem with some hidden hyperlinks becoming unhidden...
fixHyperlink(docElement);
%dumpElement(docElement);
end
% Get the Document Element(s) corresponding to the latest fprintf operation
while docElement.getStartOffset < cmdWinDoc.getLength
% Set the element style according to the current style
if debugFlag, dumpElement(docElement); end
specialFlag = underlineFlag | boldFlag;
setElementStyle(docElement,style,specialFlag,majorVersion,minorVersion);
if debugFlag, dumpElement(docElement); end
docElement2 = cmdWinDoc.getParagraphElement(docElement.getEndOffset+1);
if isequal(docElement,docElement2), break; end
docElement = docElement2;
end
if debugFlag, dumpElement(docElement); end
% Force a Command-Window repaint
% Note: this is important in case the rendered str was not '\n'-terminated
xCmdWndView.repaint;
% The following is for debug use only:
el(end+1) = handle(docElement); %#ok used in debug only
%elementStart = docElement.getStartOffset;
%elementLength = docElement.getEndOffset - elementStart;
%txt = cmdWinDoc.getText(elementStart,elementLength);
end
if nargout
count = count1;
end
return; % debug breakpoint
end
% Process the requested style information
function [underlineFlag,boldFlag,style,debugFlag] = processStyleInfo(style)
underlineFlag = 0;
boldFlag = 0;
debugFlag = 0;
% First, strip out the underline/bold markers
if ischar(style)
% Styles containing '-' or '_' should be underlined (using a no-target hyperlink hack)
%if style(1)=='-'
underlineIdx = (style=='-') | (style=='_');
if any(underlineIdx)
underlineFlag = 1;
%style = style(2:end);
style = style(~underlineIdx);
end
% Check for bold style (only if not underlined)
boldIdx = (style=='*');
if any(boldIdx)
boldFlag = 1;
style = style(~boldIdx);
end
if underlineFlag && boldFlag
warning('YMA:cprintf:BoldUnderline','Matlab does not support both bold & underline')
end
% Check for debug mode (style contains '!')
debugIdx = (style=='!');
if any(debugIdx)
debugFlag = 1;
style = style(~debugIdx);
end
% Check if the remaining style sting is a numeric vector
%styleNum = str2num(style); %#ok<ST2NM> % not good because style='text' is evaled!
%if ~isempty(styleNum)
if any(style==' ' | style==',' | style==';')
style = str2num(style); %#ok<ST2NM>
end
end
% Style = valid matlab RGB vector
if isnumeric(style) && length(style)==3 && all(style<=1) && all(abs(style)>=0)
if any(style<0)
underlineFlag = 1;
style = abs(style);
end
style = getColorStyle(style);
elseif ~ischar(style)
error('YMA:cprintf:InvalidStyle','Invalid style - see help section for a list of valid style values')
% Style name
else
% Try case-insensitive partial/full match with the accepted style names
matlabStyles = {'Text','Keywords','Comments','Strings','UnterminatedStrings','SystemCommands','Errors'};
validStyles = [matlabStyles, ...
'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White', ...
'Hyperlinks'];
matches = find(strncmpi(style,validStyles,length(style)));
% No match - error
if isempty(matches)
error('YMA:cprintf:InvalidStyle','Invalid style - see help section for a list of valid style values')
% Too many matches (ambiguous) - error
elseif length(matches) > 1
error('YMA:cprintf:AmbigStyle','Ambiguous style name - supply extra characters for uniqueness')
% Regular text
elseif matches == 1
style = 'ColorsText'; % fixed by Danilo, 29/8/2011
% Highlight preference style name
elseif matches <= length(matlabStyles)
style = ['Colors_M_' validStyles{matches}];
% Color name
elseif matches < length(validStyles)
colors = [0,0,0; 0,1,1; 1,0,1; 0,0,1; 0,1,0; 1,0,0; 1,1,0; 1,1,1];
requestedColor = colors(matches-length(matlabStyles),:);
style = getColorStyle(requestedColor);
% Hyperlink
else
style = 'Colors_HTML_HTMLLinks'; % CWLink
underlineFlag = 1;
end
end
end
% Convert a Matlab RGB vector into a known style name (e.g., '[255,37,0]')
function styleName = getColorStyle(rgb)
intColor = int32(rgb*255);
javaColor = java.awt.Color(intColor(1), intColor(2), intColor(3));
styleName = sprintf('[%d,%d,%d]',intColor);
com.mathworks.services.Prefs.setColorPref(styleName,javaColor);
end
% Fix a bug in some Matlab versions, where the number of URL segments
% is larger than the number of style segments in a doc element
function delta = getUrlsFix(docElement) %#ok currently unused
tokens = docElement.getAttribute('SyntaxTokens');
links = docElement.getAttribute('LinkStartTokens');
if length(links) > length(tokens(1))
delta = length(links) > length(tokens(1));
else
delta = 0;
end
end
% fprintf(2,str) causes all previous '_'s in the line to become red - fix this
function fixHyperlink(docElement)
try
tokens = docElement.getAttribute('SyntaxTokens');
urls = docElement.getAttribute('HtmlLink');
urls = urls(2);
links = docElement.getAttribute('LinkStartTokens');
offsets = tokens(1);
styles = tokens(2);
doc = docElement.getDocument;
% Loop over all segments in this docElement
for idx = 1 : length(offsets)-1
% If this is a hyperlink with no URL target and starts with ' ' and is collored as an error (red)...
if strcmp(styles(idx).char,'Colors_M_Errors')
character = char(doc.getText(offsets(idx)+docElement.getStartOffset,1));
if strcmp(character,' ')
if isempty(urls(idx)) && links(idx)==0
% Revert the style color to the CW background color (i.e., hide it!)
styles(idx) = java.lang.String('CW_BG_Color');
end
end
end
end
catch
% never mind...
end
end
% Set an element to a particular style (color)
function setElementStyle(docElement,style,specialFlag, majorVersion,minorVersion)
%global tokens links urls urlTargets % for debug only
global oldStyles
if nargin<3, specialFlag=0; end
% Set the last Element token to the requested style:
% Colors:
tokens = docElement.getAttribute('SyntaxTokens');
try
styles = tokens(2);
oldStyles{end+1} = cell(styles);
% Correct edge case problem
extraInd = double(majorVersion>7 || (majorVersion==7 && minorVersion>=13)); % =0 for R2011a-, =1 for R2011b+
%{
if ~strcmp('CWLink',char(styles(end-hyperlinkFlag))) && ...
strcmp('CWLink',char(styles(end-hyperlinkFlag-1)))
extraInd = 0;%1;
end
hyperlinkFlag = ~isempty(strmatch('CWLink',tokens(2)));
hyperlinkFlag = 0 + any(cellfun(@(c)(~isempty(c)&&strcmp(c,'CWLink')),cell(tokens(2))));
%}
jStyle = java.lang.String(style);
if numel(styles)==4 && isempty(char(styles(2)))
% Attempt to fix discoloration issues - NOT SURE THAT THIS IS OK! - 24/6/2015
styles(1) = jStyle;
end
styles(end-extraInd) = java.lang.String('');
styles(end-extraInd-specialFlag) = jStyle; % #ok apparently unused but in reality used by Java
if extraInd
styles(end-specialFlag) = jStyle;
end
oldStyles{end} = [oldStyles{end} cell(styles)];
catch
% never mind for now
end
% Underlines (hyperlinks):
%{
links = docElement.getAttribute('LinkStartTokens');
if isempty(links)
%docElement.addAttribute('LinkStartTokens',repmat(int32(-1),length(tokens(2)),1));
else
%TODO: remove hyperlink by setting the value to -1
end
%}
% Correct empty URLs to be un-hyperlinkable (only underlined)
urls = docElement.getAttribute('HtmlLink');
if ~isempty(urls)
urlTargets = urls(2);
for urlIdx = 1 : length(urlTargets)
try
if urlTargets(urlIdx).length < 1
urlTargets(urlIdx) = []; % '' => []
end
catch
% never mind...
a=1; %#ok used for debug breakpoint...
end
end
end
% Bold: (currently unused because we cannot modify this immutable int32 numeric array)
%{
try
%hasBold = docElement.isDefined('BoldStartTokens');
bolds = docElement.getAttribute('BoldStartTokens');
if ~isempty(bolds)
%docElement.addAttribute('BoldStartTokens',repmat(int32(1),length(bolds),1));
end
catch
% never mind - ignore...
a=1; %#ok used for debug breakpoint...
end
%}
return; % debug breakpoint
end
% Display information about element(s)
function dumpElement(docElements)
%return;
disp(' ');
numElements = length(docElements);
cmdWinDoc = docElements(1).getDocument;
for elementIdx = 1 : numElements
if numElements > 1, fprintf('Element #%d:\n',elementIdx); end
docElement = docElements(elementIdx);
if ~isjava(docElement), docElement = docElement.java; end
%docElement.dump(java.lang.System.out,1)
disp(docElement)
tokens = docElement.getAttribute('SyntaxTokens');
if isempty(tokens), continue; end
links = docElement.getAttribute('LinkStartTokens');
urls = docElement.getAttribute('HtmlLink');
try bolds = docElement.getAttribute('BoldStartTokens'); catch, bolds = []; end
txt = {};
tokenLengths = tokens(1);
for tokenIdx = 1 : length(tokenLengths)-1
tokenLength = diff(tokenLengths(tokenIdx+[0,1]));
if (tokenLength < 0)
tokenLength = docElement.getEndOffset - docElement.getStartOffset - tokenLengths(tokenIdx);
end
txt{tokenIdx} = cmdWinDoc.getText(docElement.getStartOffset+tokenLengths(tokenIdx),tokenLength).char; %#ok
end
lastTokenStartOffset = docElement.getStartOffset + tokenLengths(end);
try
txt{end+1} = cmdWinDoc.getText(lastTokenStartOffset, docElement.getEndOffset-lastTokenStartOffset).char; %#ok
catch
txt{end+1} = ''; %#ok<AGROW>
end
%cmdWinDoc.uiinspect
%docElement.uiinspect
txt = strrep(txt',sprintf('\n'),'\n');
try
data = [cell(tokens(2)) m2c(tokens(1)) m2c(links) m2c(urls(1)) cell(urls(2)) m2c(bolds) txt];
if elementIdx==1
disp(' SyntaxTokens(2,1) - LinkStartTokens - HtmlLink(1,2) - BoldStartTokens - txt');
disp(' ==============================================================================');
end
catch
try
data = [cell(tokens(2)) m2c(tokens(1)) m2c(links) txt];
catch
disp([cell(tokens(2)) m2c(tokens(1)) txt]);
try
data = [m2c(links) m2c(urls(1)) cell(urls(2))];
catch
% Mtlab 7.1 only has urls(1)...
data = [m2c(links) cell(urls)];
end
end
end
disp(data)
end
end
% Utility function to convert matrix => cell
function cells = m2c(data)
%datasize = size(data); cells = mat2cell(data,ones(1,datasize(1)),ones(1,datasize(2)));
cells = num2cell(data);
end
% Display the help and demo
function showDemo(majorVersion,minorVersion)
fprintf('cprintf displays formatted text in the Command Window.\n\n');
fprintf('Syntax: count = cprintf(style,format,...); click <a href="matlab:help cprintf">here</a> for details.\n\n');
url = 'http://UndocumentedMatlab.com/blog/cprintf/';
fprintf(['Technical description: <a href="' url '">' url '</a>\n\n']);
fprintf('Demo:\n\n');
boldFlag = majorVersion>7 || (majorVersion==7 && minorVersion>=13);
s = ['cprintf(''text'', ''regular black text'');' 10 ...
'cprintf(''hyper'', ''followed %s'',''by'');' 10 ...
'cprintf(''key'', ''%d colored'',' num2str(4+boldFlag) ');' 10 ...
'cprintf(''-comment'',''& underlined'');' 10 ...
'cprintf(''err'', ''elements:\n'');' 10 ...
'cprintf(''cyan'', ''cyan'');' 10 ...
'cprintf(''_green'', ''underlined green'');' 10 ...
'cprintf(-[1,0,1], ''underlined magenta'');' 10 ...
'cprintf([1,0.5,0], ''and multi-\nline orange\n'');' 10];
if boldFlag
% In R2011b+ the internal bug that causes the need for an extra space
% is apparently fixed, so we must insert the sparator spaces manually...
% On the other hand, 2011b enables *bold* format
s = [s 'cprintf(''*blue'', ''and *bold* (R2011b+ only)\n'');' 10];
s = strrep(s, ''')',' '')');
s = strrep(s, ''',5)',' '',5)');
s = strrep(s, '\n ','\n');
end
disp(s);
eval(s);
end
%%%%%%%%%%%%%%%%%%%%%%%%%% TODO %%%%%%%%%%%%%%%%%%%%%%%%%
% - Fix: Remove leading space char (hidden underline '_')
% - Fix: Find workaround for multi-line quirks/limitations
% - Fix: Non-\n-terminated segments are displayed as black
% - Fix: Check whether the hyperlink fix for 7.1 is also needed on 7.2 etc.
% - Enh: Add font support