-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathplot.d
More file actions
3088 lines (2579 loc) · 93.9 KB
/
plot.d
File metadata and controls
3088 lines (2579 loc) · 93.9 KB
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 file contains all of the plots types in Plot2kill, which can be
* drawn on screen using plot2kill.figure.Figure.
*
* Copyright (C) 2010-2012 David Simcha
*
* License:
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
module plot2kill.plot;
import plot2kill.figure, plot2kill.util, plot2kill.hierarchical;
import std.random, std.typetuple;
version(dfl) {
public import plot2kill.dflwrapper;
} else {
public import plot2kill.gtkwrapper;
}
/**Abstract base class for all types of plot objects.*/
abstract class Plot {
protected:
// Top of the plot.
double upperLim = -double.infinity;
// Bottom of the plot.
double lowerLim = double.infinity;
// Leftmost limit of the plot.
double leftLim = double.infinity;
// Rightmost limit of the plot.
double rightLim = -double.infinity;
string _legendText;
// Hook in case the plot needs to reset its limits after seeing
// the figure it's about to be drawn to.
void resetLimits(Figure figure) {}
package:
PlotSize measureLegend(Font legendFont, FigureBase fig) {
if(!legendText().length) return PlotSize(0, 0);
auto ret = fig.measureText(legendText(), legendFont);
ret.width += legendSymbolSize + legendSymbolTextSpace;
ret.height = max(ret.height, legendSymbolSize);
return PlotSize(ret.width, ret.height);
}
public:
// This should be package but for some reason package functions can't
// be abstract.
abstract void drawLegendSymbol(FigureBase fig, PlotRect where);
/* Draw the plot on Figure using the rectangular area described by the
* integer parameters.
*/
abstract void drawPlot(Figure, double, double, double, double);
/**
Returns true if this plot type supports legends, otherwise false.
*/
bool hasLegend() {
return true;
}
/**Convenience method that instantiates a Figure object with this plot.
* Useful for creating single-plot figures w/o a lot of boilerplate.
*
* Examples:
* ---
* auto hist = Histogram([1,2,3,4,5], 3).toFigure;
* hist.showAsMain();
* ---
*/
Figure toFigure() {
return new Figure(this);
}
/**Instantiates a Figure object with this plot and also places the default
* axes and tick labeling and title for the plot type, if any, on the
* Figure. If a plot type has no default labeling, simply forwards to
* toFigure().
*/
Figure toLabeledFigure() {
return toFigure;
}
/**The leftmost point on the plot.*/
double leftMost() {
return leftLim;
}
/**The rightmost point on the plot.*/
double rightMost() {
return rightLim;
}
/**The topmost point on the plot.*/
double topMost() {
return upperLim;
}
/**The bottommost point on the plot.*/
double bottomMost() {
return lowerLim;
}
///
string legendText()() {
return _legendText;
}
///
This legendText(this This)(string newText) {
_legendText = newText;
return cast(This) this;
}
}
/**A basic bar plot.*/
class BarPlot : Plot {
private:
double[] _centers;
double[] _heights;
double[] _lowerErrors;
double[] _upperErrors;
BarPlot _stackOn;
bool _outlineBar = true;
// Return the bottom of the bar at a given index. This is zero unless
// we have a stacked plot.
double bottom(size_t index) pure nothrow {
return (_stackOn is null) ? 0 :
_stackOn.bottom(index) + _stackOn._heights[index];
}
void fixBounds() {
// We should never have both error bars and stacking. The API doesn't
// allow this, but double-check here.
enforce(_stackOn is null ||
(_lowerErrors.length == 0 && upperErrors.length == 0));
this.leftLim = reduce!min(double.infinity, this.centers) - width / 2;
this.rightLim = reduce!max(-double.infinity, this.centers) + width / 2;
lowerLim = double.infinity;
upperLim = -double.infinity;
foreach(i, height; _heights) {
if(lowerErrors.length > 0) {
lowerLim = min(height - lowerErrors[i], lowerLim);
} else {
lowerLim = min(height + bottom(i), lowerLim);
}
if(upperErrors.length > 0) {
upperLim = max(height + upperErrors[i], upperLim);
} else {
upperLim = max(height + bottom(i), upperLim);
}
}
// Don't blend error bars into axes. Handle the case where a boundary
// is 0 as a special case, since it would look worse to have the axis
// not be exactly zero if all bars are positive or all are negative than
// to blend an error bar into an axis.
if(upperErrors.length || lowerErrors.length) {
immutable pad = 0.01 * (upperLim - lowerLim);
if(upperErrors.length && upperLim != 0) {
upperLim += pad;
}
if(lowerErrors.length && lowerLim != 0) {
lowerLim -= pad;
}
}
if(lowerLim > 0) {
lowerLim = 0;
}
if(upperLim < 0) {
upperLim = 0;
}
}
this(double[] centers, double[] heights, double width) {
this._centers = centers;
this._heights = heights;
this.width = width;
_barColor = getColor(0, 0, 255);
fixBounds();
}
protected:
override void drawPlot(
Figure form,
double leftMargin,
double topMargin,
double plotWidth,
double plotHeight
) {
mixin(toPixels);
mixin(drawErrorMixin);
immutable multiplier = plotHeight / (this.upperLim - this.lowerLim);
auto brush = form.getBrush(_barColor);
scope(exit) doneWith(brush);
auto blackPen = form.getPen(getColor(0, 0, 0));
scope(exit) doneWith(blackPen);
foreach(i, center; centers) {
immutable zeroPoint = toPixelsY(bottom(i));
immutable height = heights[i];
immutable left = center - width / 2;
immutable right = center + width / 2;
immutable leftPixels = toPixelsX(left);
immutable rightPixels = toPixelsX(right);
immutable widthPixels = rightPixels - leftPixels;
immutable heightPixels = roundTo!int(abs(height) * multiplier);
immutable startAt = (height > 0) ?
zeroPoint - heightPixels :
zeroPoint;
form.fillClippedRectangle(brush, leftPixels,
startAt, widthPixels, heightPixels);
if(_outlineBar) {
form.drawClippedRectangle(blackPen, leftPixels,
startAt, widthPixels, heightPixels);
}
// Do error bars.
if(lowerErrors.length) {
drawErrorBar(blackPen,
center, height, height - lowerErrors[i], width / 2);
}
if(upperErrors.length) {
drawErrorBar(blackPen,
center, height, height + upperErrors[i], width / 2);
}
}
if(lowerLim < 0) {
immutable zeroPoint = toPixelsY(0);
auto pen = form.getPen(getColor(0, 0, 0), 2);
// Draw line across figure at the zero point.
form.drawClippedLine(pen,
PlotPoint(toPixelsX(leftLim), zeroPoint),
PlotPoint(toPixelsX(rightLim), zeroPoint)
);
}
}
override void drawLegendSymbol(FigureBase fig, PlotRect where) {
drawFillLegend(_barColor, fig, where);
}
Color _barColor;
public:
/**Controls the color of the bar. Defaults to blue.*/
final Color barColor()() {
return _barColor;
}
/// Setter
final This barColor(this This)(Color newColor) {
_barColor = newColor;
return cast(This) this;
}
/**Controls whether each bar is outlined in a black rectange.*/
final bool outlineBar()() {
return _outlineBar;
}
final This outlineBar(this This)(bool shouldOutline) {
_outlineBar = shouldOutline;
return cast(This) this;
}
///
immutable double width;
/**Create a BarPlot. centers and heights must be input ranges with elements
* implicitly convertible to double. width determines the width of each
* bar relative to the X-axis scale and must be greater than 0.
*/
static BarPlot opCall(R1, R2)(R1 centers, R2 heights, double width)
if(isInputRange!R1 && is(ElementType!R1 : double) &&
isInputRange!R2 && is(ElementType!R2 : double)) {
auto c = toDoubleArray(centers);
auto h = toDoubleArray(heights);
enforce(c.length == h.length,
"Centers and heights must be same length for bar plot.");
enforce(width > 0, "Width must be >0 for bar plot.");
auto ret = new typeof(return)(c, h, width);
return ret;
}
/**
Create a BarPlot with error bars. lowerErrors and upperErrors
must be input ranges with elements implicitly convertible to double for
error bars to be shown. Any other value, such as null or 0, will result
in no error bars being shown. Therefore, to only show, for example,
upper erros, simply pass in null or 0 for the lower errors.
To draw symmetric error bars, simply pass in the same range for
lowerErrors and upperErrors. However, note that if you do this,
the range will need to be a forward range, not an input range.
*/
static BarPlot opCall(R1, R2, R3, R4)
(R1 centers, R2 heights, double width, R3 lowerErrors, R4 upperErrors)
if(isInputRange!R1 && is(ElementType!R1 : double) &&
isInputRange!R2 && is(ElementType!R2 : double)) {
auto ret = opCall(centers, heights, width);
static if(isForwardRange!R3) {
ret._lowerErrors = toDoubleArray(lowerErrors.save);
} else static if(isInputRange!R3) {
ret._lowerErrors = toDoubleArray(lowerErrors);
}
static if(isForwardRange!R4) {
ret._upperErrors = toDoubleArray(upperErrors.save);
} else static if(isInputRange!R4) {
ret._upperErrors = toDoubleArray(upperErrors);
}
enforce(ret.upperErrors.length == 0 || ret.upperErrors.length ==
ret.centers.length, "Length of upperErrors must equal number of bars.");
enforce(ret.lowerErrors.length == 0 || ret.lowerErrors.length ==
ret.centers.length, "Length of lowerErrors must equal number of bars.");
ret.fixBounds();
return ret;
}
/**
Create a BarPlot that is to be stacked on top of this one. For a
convenience function for creating such a plot, see stackedBar().
Warning: Creating a cycle (two BarPlots mutually on top of each other)
will cause infinite loops, stack overflows and otherwise bad
things.
*/
BarPlot stack(R)(R heights) {
auto ret = new typeof(return)
(_centers, toDoubleArray(heights), width);
ret._stackOn = this;
ret.fixBounds();
return ret;
}
/**Scale this object by a factor of scaleFactor in the X direction.
* This is useful for getting it onto the same scale as another plot.
*/
void scaleCenters(double scaleFactor) {
enforce(isFinite(scaleFactor), "Can't scale by infinity or NaN.");
_centers[] *= scaleFactor;
fixBounds();
}
/**Scale this object by a factor of scaleFactor in the Y direction.
* This is useful for getting it onto the same scale as another plot.*/
void scaleHeights(double scaleFactor) {
enforce(isFinite(scaleFactor), "Can't scale by infinity or NaN.");
_heights[] *= scaleFactor;
fixBounds();
}
/**Shift this graph by shiftBy units in the X direction.
* This is useful for getting it onto the same scale as another plot.
*/
void shiftCenters(double shiftBy) {
enforce(isFinite(shiftBy), "Can't shift by infinity or NaN.");
_centers[] += shiftBy;
fixBounds();
}
/**Get the centers of the bars.*/
final const(double)[] centers() {
return _centers;
}
/**Get the heights of the bars.*/
final const(double)[] heights() {
return _heights;
}
///
final const(double)[] lowerErrors() {
return _lowerErrors;
}
///
final const(double)[] upperErrors() {
return _upperErrors;
}
/**The default labeling includes each center receiving its own x tick
* label if there are <= 10 bars on the graph.
*/
override Figure toLabeledFigure() {
auto ret = toFigure;
if(centers.length <= 10) {
ret.xTickLabels(centers);
}
return ret;
}
}
private template isRoR(T) {
enum isRoR = isInputRange!T && isInputRange!(ElementType!T);
}
/**
Create an array of bar plots that, when inserted into a Figure, will effectively
become a grouped bar plot.
Parameters:
centers:
An input range of the overall center of each group of bars.
data:
A range of ranges, with one range for each bar color. This range should have
one number for each group.
width:
The combined width of all of the bars for each group.
legendText:
An array of strings, one for each bar color, or null if no legend is desired.
colors:
An array of colors, one for each bar. If none is provided, the default
colors are used. These are, in order, blue, red, green, black, orange,
and purple. If more colors are needed, they are generated using a random
number generator with a deterministic seed.
Examples:
---
// Make a plot with three groups: One for "In Meeting", one for "On Phone",
// and one for "Coding". The plot will also have two bar colors: One for
// "Without Caffeine" and one for "With Caffeine".
auto withoutCaffeine = [8, 6, 3];
auto withCaffeine = [5, 3, 1];
auto sleepinessPlot = groupedBar(
iota(3), [withoutCaffeine, withCaffeine], 0.6,
["W/o Caffeine", "W/ Caffeine"],
[getColor(64, 64, 255), getColor(255, 64, 64)]
);
auto sleepinessFig = Figure(sleepinessPlot)
.title("Sleepiness Survey")
.yLabel("Sleepiness Rating")
.xLabel("Activity")
.legendLocation(LegendLocation.right)
.horizontalGrid(true)
.xTickLabels(
iota(3),
["In Meeting", "On Phone", "Coding"]
);
---
*/
BarPlot[] groupedBar(R1, R2)(
R1 centers,
R2 data,
double width,
string[] legendText = null,
Color[] colors = null
)
if(isInputRange!R1 && isRoR!R2) {
return groupedBar(centers, data, (double[][]).init, (double[][]).init,
width, legendText, colors);
}
/**
Create a grouped bar plot with error bars. lowerErrors and upperErrors
must either have the same dimensions as data or be empty.
*/
BarPlot[] groupedBar(R1, R2, R3, R4)(
R1 centers,
R2 data,
R3 lowerErrors,
R4 upperErrors,
double width,
string[] legendText = null,
Color[] colors = null
)
if(isInputRange!R1 && isRoR!R2 && isRoR!R3 && isRoR!R4) {
return groupStackImpl(CompoundBar.group, centers, data, lowerErrors,
upperErrors, width, legendText, colors);
}
/**
Create a stacked bar plot. The usage mechanics are identical to those of the
no error bar overload of groupedBar().
Examples:
---
// Stack coffee and tea consumption on top of each other.
Figure(
stackedBar(iota(3), [[5, 3, 1], [1, 2, 3]], 0.6,
["Coffee", "Tea"]
)
).legendLocation(LegendLocation.right)
.title("Caffeine Consumption")
.xLabel("Time of Day")
.xTickLabels(iota(3), ["Morning", "Afternoon", "Evening"])
.yLabel("Beverages")
.showAsMain();
---
*/
BarPlot[] stackedBar(R1, R2)(
R1 centers,
R2 data,
double width,
string[] legendText = null,
Color[] colors = null
)
if(isInputRange!R1 && isRoR!R2) {
return groupStackImpl(CompoundBar.stack, centers, data, (double[][]).init,
(double[][]).init, width, legendText, colors);
}
private enum CompoundBar {
group,
stack
}
private BarPlot[] groupStackImpl(R1, R2, R3, R4)(
CompoundBar whatToDo,
R1 centers,
R2 data,
R3 lowerErrors,
R4 upperErrors,
double width,
string[] legendText = null,
Color[] colors = null
) {
if(whatToDo == CompoundBar.stack) {
enforce(lowerErrors.length == 0 && upperErrors.length == 0);
}
auto centerArr = toDoubleArray(centers);
auto dataArr = array(map!toDoubleArray(data));
auto lerrArr = array(map!toDoubleArray(lowerErrors));
auto uerrArr = array(map!toDoubleArray(upperErrors));
foreach(elem; tuple(lerrArr, uerrArr, legendText, colors)) {
enforce(elem.empty || elem.length == dataArr.length,
"Range length mismatch in groupedBar.");
}
if(!colors.length) {
colors = [
getColor(0, 0, 255), getColor(255, 0, 0), getColor(0, 255, 0),
getColor(0, 0, 0), getColor(255, 128, 0), getColor(255, 0, 255)
];
// If we need more colors, generate them "randomly" but from a
// deterministic seed.
auto gen = Random(31415);
while(colors.length < dataArr.length) {
colors ~= getColor(
uniform!"[]"(cast(ubyte) 0, cast(ubyte) 255, gen),
uniform!"[]"(cast(ubyte) 0, cast(ubyte) 255, gen),
uniform!"[]"(cast(ubyte) 0, cast(ubyte) 255, gen)
);
}
}
BarPlot[] ret;
foreach(int groupIndex, group; dataArr) {
BarPlot plot;
enforce(group.length == centerArr.length,
"Each group's length must be equal to centers.length for "
~ "grouped and stacked bar plots."
);
if(whatToDo == CompoundBar.group) {
immutable groupWidth = width / dataArr.length;
// Shift groupCenters over from overall centers.
auto groupCenters = centerArr.dup;
immutable offset = (groupIndex + 0.5) * groupWidth;
groupCenters[] += offset - width / 2;
if(lowerErrors.length && upperErrors.length) {
plot = BarPlot(NoCopy(groupCenters), NoCopy(group), groupWidth,
NoCopy(lerrArr[groupIndex]), NoCopy(uerrArr[groupIndex])
);
} else {
plot = BarPlot(NoCopy(groupCenters), NoCopy(group), groupWidth);
}
} else if(whatToDo == CompoundBar.stack) {
if(groupIndex == 0) {
plot = BarPlot(NoCopy(centerArr), NoCopy(group), width);
} else {
plot = ret[$ - 1].stack(NoCopy(group));
}
} else {
assert(0);
}
plot.barColor(colors[groupIndex]);
if(legendText.length) {
plot.legendText(legendText[groupIndex]);
}
ret ~= plot;
}
return ret;
}
/**Determine behavior for elements outside of a fixed-border histogram's bounds.
*/
enum OutOfBounds {
/** Throw throws an exception.*/
throwException,
/**Ignore simply skips the number.*/
ignore,
// For backwards compatibility, will eventually be removed.
Throw = throwException,
Ignore=ignore
}
/**Controls whether a histogram plots counts or probability.*/
enum HistType {
/// The Y-axis should be counts.
counts,
/// The Y-axis should be probabilities.
probability,
// For backwards compatibility, will eventually be removed.
Probability = probability,
Counts = counts
}
/**A class for plotting regular (equal-width) histograms.*/
class Histogram : Plot {
private double binWidth;
private uint[] binCounts;
private uint nElem;
private HistType countsOrProbs;
private this() {
_barColor = getColor(0, 0, 255);
}
private bool isCumulative = false;
protected override void drawPlot(
Figure form,
double leftMargin,
double topMargin,
double plotWidth,
double plotHeight
) {
uint[] binCounts = this.binCounts;
if(isCumulative) {
binCounts = binCounts.dup;
foreach(i; 1..binCounts.length) {
binCounts[i] += binCounts[i - 1];
}
}
immutable maxCount = reduce!max(0U, binCounts);
immutable multiplier = plotHeight / cast(double) maxCount;
immutable binWidth = cast(double) plotWidth / nBin;
immutable bottom = plotHeight + topMargin;
auto blackPen = form.getPen(getColor(0, 0, 0), 1);
scope(exit) doneWith(blackPen);
auto brush = form.getBrush(_barColor);
scope(exit) doneWith(brush);
double horizPos = leftMargin;
double lastPosPixels = leftMargin;
foreach(i, count; binCounts) {
// Most of the complexity of this loop body is for making the bin
// boundaries accurate in the context of having to round to
// pixels.
immutable barHeight = multiplier * count;
immutable horizPixels = min(roundTo!int(horizPos), lastPosPixels);
immutable stopAt = horizPos + binWidth;
immutable thisBinWidth = max(1.0, stopAt - horizPixels);
form.fillClippedRectangle(brush, lastPosPixels,
bottom - barHeight, thisBinWidth, barHeight);
form.drawClippedRectangle(blackPen, lastPosPixels,
bottom - barHeight, thisBinWidth, barHeight);
horizPos += binWidth;
lastPosPixels = horizPixels + thisBinWidth;
}
}
protected override void drawLegendSymbol(FigureBase fig, PlotRect where) {
drawFillLegend(_barColor, fig, where);
}
private void fixBounds() {
if(isCumulative) {
if(countsOrProbs == HistType.Probability) {
upperLim = 1;
} else {
upperLim = nElem;
}
} else{
if(countsOrProbs == HistType.Probability) {
upperLim = reduce!max(0U, binCounts) / cast(double) nElem;
} else {
upperLim = reduce!max(0U, binCounts);
}
}
}
private OutOfBounds outOfBoundsBehavior = OutOfBounds.Throw;
private Color _barColor;
/**Controls the color of the bar. Defaults to blue.*/
final Color barColor()() {
return _barColor;
}
/// Setter
final This barColor(this This)(Color newColor) {
_barColor = newColor;
return cast(This) this;
}
/// The number of bins this histogram contains.
final uint nBin() const pure nothrow {
return cast(uint) binCounts.length;
}
/**Factory method to instantiate this class. nums must be a forward range
* with elements implicitly convertible to double. nBin specifies how many
* bins the histogram should contain.
*/
static Histogram opCall(R)(R nums, uint nBin)
if(isForwardRange!R && is(ElementType!R : double)) {
double leftLim = double.infinity, rightLim = -double.infinity;
foreach(num; nums.save) {
leftLim = min(leftLim, num);
rightLim = max(rightLim, num);
}
return Histogram(nums, nBin, leftLim, rightLim);
}
/**Factory method to instantiate this class with predetermined limits.
* This allows nums to be an input range instead of a forward range, since
* no pass is necessary to compute the limits.
*
* This function both obeys and permanently sets whatever bounds behavior
* is specified (throwing or ignoring on out of bounds numbers). The
* default behavior is to throw. Rationale: Errors should only pass
* silently if explicitly silenced.
*/
static Histogram opCall(R)(
R nums,
uint nBin,
double leftLim,
double rightLim,
OutOfBounds outOfBoundsBehavior = OutOfBounds.throwException
) if(isInputRange!R && is(ElementType!R : double)) {
auto ret = Histogram(nBin, leftLim, rightLim, outOfBoundsBehavior);
foreach(num; nums) {
ret.put(num);
}
return ret;
}
/**Create an empty histogram with pre-specified bounds, which will be
* filled with data using the put method.
*
* Note: The only reason this is a template is because of bugs in
* overloading non-templated functions agsinst templated functions.
*/
static Histogram opCall(I)(
I nBin,
double leftLim,
double rightLim,
OutOfBounds outOfBoundsBehavior = OutOfBounds.Throw
) if(isIntegral!I) {
auto ret = new Histogram;
ret.outOfBoundsBehavior = outOfBoundsBehavior;
enforce(rightLim > leftLim,
"Cannot create a histogram w/ upper lim <= lower lim.");
enforce(nBin > 1, "Cannot create a histogram w/ <2 bins.");
immutable binWidth = (rightLim - leftLim) / nBin;
ret.binWidth = binWidth;
ret.leftLim = leftLim;
ret.rightLim = rightLim;
ret.binCounts.length = to!uint(nBin);
ret.lowerLim = 0;
ret.upperLim = 0;
return ret;
}
/**Add a number to the histogram on the fly.*/
This put(this This)(double num) {
if(outOfBoundsBehavior == OutOfBounds.Throw) {
enforce(num >= leftLim && num <= rightLim, text(
"Number out of bounds for histogram. Got: ", num,
", expected between ", leftLim, " and ", rightLim, "."));
} else {
if(!(num >= leftLim && num <= rightLim)) {
return cast(This) this;
}
}
uint bin;
bin = to!uint((num - leftLim) / binWidth);
if(bin == nBin) { // Edge case.
bin--;
}
binCounts[bin]++;
nElem++;
if(countsOrProbs == HistType.Counts) {
if(isCumulative) {
upperLim = nElem;
} else if(binCounts[bin] > upperLim) {
upperLim = binCounts[bin];
}
} else if(!isCumulative) {
immutable binProb = binCounts[bin] / cast(double) nElem;
if(binProb > upperLim) {
upperLim = binProb;
}
}
return cast(This) this;
}
/**Add the contents of another Histogram to this one. The boundaries and
* numbers of bins must be the same. This histogram's settings are
* retained.
*/
This put(this This)(const Histogram rhs) {
if(rhs is null) {
return cast(This) this;
}
enforce(rhs.leftLim == this.leftLim && rhs.rightLim == this.rightLim,
"Boundaries must be the same to combine histograms.");
binCounts[] += rhs.binCounts[];
nElem += rhs.nElem;
fixBounds();
return cast(This) this;
}
/**Assumes the LineGraph input is a plot of a PDF that this histogram is
* supposed to approximate, and scales the Y axis of the LineGraph
* accordingly so that both appear on the same scale.
*
* If this Histogram is cumulative, assumes that the input LineGraph is
* a CDF instead.
*/
This scaleDistributionFunction(this This)(LineGraph g) {
if(isCumulative) {
if(countsOrProbs == HistType.Counts) {
g.scaleY(nElem);
}
// Don't need to do anything if this is a probability histogram.
} else {
double scaleFactor = (rightLim - leftLim) / nBin;
if(countsOrProbs == HistType.Counts) {
scaleFactor *= nElem;
}
g.scaleY(scaleFactor);
}
return cast(This) this;
}
/**Determine whether this object throws or ignores if it receives a number
* outside its bounds via put.
*/
This boundsBehavior(this This)(OutOfBounds behavior) {
outOfBoundsBehavior = behavior;
return cast(This) this;
}
/**Set whether this histogram displays counts or probabilities.*/
This histType(this This)(HistType newType) {
countsOrProbs = newType;
fixBounds();
return cast(This) this;
}
/**Determines whether this histogram is cumulative.*/
This cumulative(this This)(bool newVal) {
isCumulative = newVal;
fixBounds();
return cast(This) this;
}
}
/**Creates a histogram with equal frequency binning instead of equal width
* binning. The scale of a FrequencyHistogram is the probability density scale.
*
* Note that equal frequency binning doesn't work with discrete
* distributions where probability density may be infinite at a point.
* Therefore, if a probability density is calculated to be infinite, this
* class will throw.
*
*
*/
class FrequencyHistogram : Plot {
private double[] binWidths;
private double elemsPerBin;
private Color _barColor;
this() {
_barColor = getColor(0, 0, 255);
}
protected override void drawPlot(
Figure form,
double leftMargin,
double topMargin,
double plotWidth,
double plotHeight
) {
mixin(toPixels);
immutable multiplier = plotHeight / (this.upperLim - this.lowerLim);
immutable zeroPoint = toPixelsY(0);
auto brush = form.getBrush(_barColor);
scope(exit) doneWith(brush);
auto pen = form.getPen(_barColor, 1);
scope(exit) doneWith(pen);
auto blackPen = form.getPen(getColor(0, 0, 0));
scope(exit) doneWith(blackPen);
double xStart = leftLim;
immutable totalWidth = rightLim - leftLim;
foreach(width; binWidths) {