-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathchart.arr
2719 lines (2451 loc) · 86.3 KB
/
chart.arr
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
provide:
render-chart,
render-charts,
from-list,
type DataSeries,
type ChartWindow,
data StackType,
data TrendlineType,
data PointShape
end
import global as G
import base as B
include lists
include option
import image-structs as I
import internal-image-untyped as IM
import sets as S
import chart-lib as P
import either as E
import string-dict as SD
import valueskeleton as VS
import statistics as ST
import color as C
import render-error-display as RED
################################################################################
# CONSTANTS
################################################################################
SHOW-LENGTH = 3
FUNCTION-POINT-SIZE = 0.1
DEFAULT-RANGE = {-10; 10}
################################################################################
# DATA + TYPE SYNONYMS
################################################################################
type PlottableFunction = (Number -> Number)
type Posn = RawArray<Number>
type TableIntern = RawArray<RawArray<Any>>
data Pointer:
| pointer(label :: String, value :: Number)
end
data SciNumber:
| sci-notation(coeff :: Number, exponent :: Number, base :: Number)
end
data AxisData:
| axis-data(axisTop :: Number, axisBottom :: Number, ticks :: RawArray<Pointer>)
end
data StackType:
| absolute
| relative
| percent
| grouped
end
fun check-positive-degree(v :: Number) -> Boolean block:
when v < 0:
raise("degree: degree must be non-negative")
end
true
end
data TrendlineType:
| no-trendline
| linear
| exponential
| polynomial(degree :: NumInteger%(check-positive-degree))
end
fun check-positive-sides(v :: Number) -> Boolean block:
when v < 0:
raise("regular-polygon-shape: number of sides must be non-negative")
end
true
end
fun check-positive-dent(v :: Number) -> Boolean block:
when v < -1:
raise("regular-polygon-shape: dent cannot be less than -1")
end
true
end
data PointShape:
| circle-shape
| regular-polygon-shape(sides :: NumInteger%(check-positive-sides), dent :: Number%(check-positive-dent))
end
################################################################################
# HELPERS
################################################################################
fun check-num(v :: Number) -> Nothing: nothing end
fun check-string(v :: String) -> Nothing: nothing end
fun check-image(v :: IM.Image) -> Nothing: nothing end
fst = raw-array-get(_, 0)
snd = raw-array-get(_, 1)
thd = raw-array-get(_, 2)
posn = {(x :: Number, y :: Number): [raw-array: x, y]}
sprintf = (lam():
generic-sprintf = lam(arr :: RawArray<Any>):
raw-array-fold(lam(str, elt, _): str + tostring(elt) end, '', arr, 0)
end
{
make5: {(a, b, c, d, e): generic-sprintf([raw-array: a, b, c, d, e])},
make4: {(a, b, c, d): generic-sprintf([raw-array: a, b, c, d])},
make3: {(a, b, c): generic-sprintf([raw-array: a, b, c])},
make2: {(a, b): generic-sprintf([raw-array: a, b])},
make1: tostring,
make0: {(): ''},
make: generic-sprintf
}
end)()
unsafe-equal = {(x :: Number, y :: Number): (x <= y) and (y <= x)}
fun to-table2(xs :: List<Any>, ys :: List<Any>) -> TableIntern:
map2(raw-array.make2, xs, ys) ^ builtins.raw-array-from-list
end
fun to-table2-n(xs :: List<Any>, ys :: List<Any>) -> TableIntern:
map2_n({(n, x, y): raw-array.make3(x, y, n)}, 0, xs, ys) ^ builtins.raw-array-from-list
end
fun to-table3(xs :: List<Any>, ys :: List<Any>, zs :: List<Any>) -> TableIntern:
map3(raw-array.make3, xs, ys, zs) ^ builtins.raw-array-from-list
end
fun to-table3-n(xs :: List<Any>, ys :: List<Any>, zs :: List<Any>) -> TableIntern:
map3_n({(n, x, y, z): raw-array.make4(x, y, z, n)}, 0, xs, ys, zs) ^ builtins.raw-array-from-list
end
fun to-table4(xs :: List<Any>, ys :: List<Any>, zs :: List<Any>, ks :: List<Any>) -> TableIntern:
map4(raw-array.make4, xs, ys, zs, ks) ^ builtins.raw-array-from-list
end
fun list-to-table2<A>(table :: List<List<A>>) -> RawArray<RawArray<A>>:
builtins.raw-array-from-list(table.map(builtins.raw-array-from-list))
end
fun table2-to-list<A>(table :: RawArray<RawArray<A>>) -> List<List<A>>:
raw-array-to-list(table).map(raw-array-to-list)
end
fun get-vs-from-img(s :: String, raw-img :: IM.Image) -> VS.ValueSkeleton:
I.color(190, 190, 190, 0.75)
^ IM.text-font(s, 72, _, "", "modern", "normal", "bold", false)
^ IM.overlay-align("center", "bottom", _, raw-img)
^ VS.vs-value
end
fun table-sorter<A,B>(
t :: TableIntern,
value-getter :: (RawArray -> A),
scorer :: (A -> B),
cmp :: (B, B -> Boolean),
eq :: (B, B -> Boolean)):
doc: ```
General Data Table Sorting Function:
Value-getter grabs the Column of the Data table you want to use to sort
Scorer Modifies the values in that Column to what you want to sort-by
```
list-of-rows = t ^ raw-array-to-list
scored-values =
map(
{(row): {row; row ^ value-getter ^ scorer}},
list-of-rows)
sorted-by-score =
scored-values.sort-by(
{(row-score, oth-row-score): cmp(row-score.{1}, oth-row-score.{1})},
{(row-score, oth-row-score): eq(row-score.{1}, oth-row-score.{1})})
sorted-rows = map({(row-score): row-score.{0}}, sorted-by-score)
sorted-rows ^ builtins.raw-array-from-list
end
fun num-to-scientific(base :: Number) -> (Number -> SciNumber) block:
doc: ```
Produces a function that takes a number and turns it into it's scientific representation.
Calculates the resulting Coeff, Exponent where number = coeff * base ^ Exponent.
Currently only works with bases > 1.
```
when base <= 1:
raise("Num-to-scientific: Only defined on bases > 1")
end
fun convert(n :: Number):
if num-is-rational(n) and (n == 0): sci-notation(0, 0, base)
else:
pow = num-floor(num-log(num-abs(n)) / num-log(base))
c = n / num-expt(base, pow)
sci-notation(c, pow, base)
end
end
convert
#|
where:
num-to-scientific(10)(0) is sci-notation(0, 0, 10)
num-to-scientific(10)(3.214) is sci-notation(3.214, 0, 10)
num-to-scientific(10)(513) is sci-notation(5.13, 2, 10)
num-to-scientific(10)(-23) is sci-notation(-2.3, 1, 10)
num-to-scientific(10)(0.00123) is sci-notation(1.23, -3, 10)
num-to-scientific(10)(-0.0231) is sci-notation(-2.31, -2, 10)
num-to-scientific(2)(256) is sci-notation(1, 8, 2)
num-to-scientific(1) raises "Only defined on bases > 1"
num-to-scientific(0.32) raises "Only defined on bases > 1"
num-to-scientific(0) raises "Only defined on bases > 1"
num-to-scientific(-50) raises "Only defined on bases > 1"
|#
end
fun string-to-stacktype(s :: String) -> StackType:
doc: ```Converts ['none', 'absolute', relative', percent'] to their respective stacktype```
ask:
| string-equal(s, 'none') then: grouped
| string-equal(s, 'absolute') then: absolute
| string-equal(s, 'percent') then: percent
| string-equal(s, 'relative') then: relative
| otherwise: raise('type must be absolute, relative, percent, or none')
end
end
fun prep-axis(values :: P.LoN) -> {Number; Number}:
doc: ``` Calculate the max axis (top) and min axis (bottom) values for bar-chart-series```
max-positive-height = fold(num-max, 0, values)
max-negative-height = fold(num-min, 0, values)
{max-positive-height; max-negative-height}
end
fun multi-prep-axis(stack-type :: StackType, value-lists :: P.LoLoN)
-> {Number; Number}:
doc: ```
Calculate the max axis (top) and min axis (bottom) values for multi-bar-chart-series
```
ask:
| stack-type == grouped then:
# Find the tallest bar in the entire group
# We know that the value lists have at least one value since we check for that when initializing the value list data.
positive-max-groups = map({(l): fold(num-max, l.first, l)}, value-lists)
negative-max-groups = map({(l): fold(num-min, l.first, l)}, value-lists)
max-positive-height = fold(num-max, 0, positive-max-groups)
max-negative-height = fold(num-min, 0, negative-max-groups)
{max-positive-height; max-negative-height}
| stack-type == absolute then:
# Find height of stack using sum functions
sum = {(l :: List<Number>): fold({(acc, elm): acc + elm}, 0, l)}
positive-only-sum = {(l :: List<Number>): sum(filter({(e): e >= 0}, l))}
negative-only-sum = {(l :: List<Number>): sum(filter({(e): e <= 0}, l))}
positive-sums = map(positive-only-sum, value-lists)
negative-sums = map(negative-only-sum, value-lists)
max-positive-height = fold(num-max, 0, positive-sums)
max-negative-height = fold(num-min, 0, negative-sums)
{max-positive-height; max-negative-height}
| otherwise:
has-pos = any({(l): any({(e): e > 0}, l)}, value-lists)
has-neg = any({(l): any({(e): e < 0}, l)}, value-lists)
ask:
| has-pos and has-neg then: {1; -1}
| has-pos then: {1; 0}
| has-neg then: {0; -1}
| otherwise: {1; -1}
end
end
end
fun get-box-data(label :: String, lst :: List<Number>) -> RawArray:
n = lst.length()
shadow lst = lst.sort()
median = ST.median(lst)
{first-quartile; third-quartile} = if num-modulo(n, 2) == 0:
splitted = lst.split-at(n / 2)
{ST.median(splitted.prefix); ST.median(splitted.suffix)}
else:
splitted = lst.split-at((n - 1) / 2)
{ST.median(splitted.prefix); ST.median(splitted.suffix.rest)}
end
iqr = third-quartile - first-quartile
high-outliers = for filter(shadow n from lst):
n > (third-quartile + (1.5 * iqr))
end ^ builtins.raw-array-from-list
low-outliers = for filter(shadow n from lst):
n < (first-quartile - (1.5 * iqr))
end ^ builtins.raw-array-from-list
min-val = lst.first
max-val = lst.last()
low-whisker = lst.drop(raw-array-length(low-outliers)).get(0)
high-whisker = lst.get(n - raw-array-length(high-outliers) - 1)
[list: label, max-val, min-val, first-quartile, median, third-quartile, high-whisker, low-whisker, high-outliers, low-outliers]
^ builtins.raw-array-from-list
end
################################################################################
# METHODS
################################################################################
color-method = method(self, color :: I.Color):
self.constr()(self.obj.{color: some(color)})
end
color-list-method = method(self, colors :: P.LoC):
cases (List) colors:
| empty => self.constr()(self.obj.{colors: none})
| link(_, _) =>
block:
each({(c :: I.Color): c}, colors)
self.constr()(self.obj.{colors: some(colors ^ builtins.raw-array-from-list)})
end
end
end
pointer-color-method = method(self, color :: I.Color):
self.constr()(self.obj.{pointer-color: some(color)})
end
interval-color-method = method(self, color :: I.Color):
self.constr()(self.obj.{default-interval-color: some(color)})
end
line-width-method = method(self, lineWidth :: Number) block:
when lineWidth < 0:
raise("line-width: Line Width must be non-negative")
end
self.constr()(self.obj.{lineWidth: lineWidth})
end
style-method = method(self, style :: String) block:
when not(string-equal(style, "sticks")) and not(string-equal(style, "bars")) and not(string-equal(style, "boxes")):
raise("style: must be either sticks, bars, or boxes")
end
self.constr()(self.obj.{style: style})
end
curve-method = method(self, curved :: Boolean):
if curved: self.constr()(self.obj.{curved: "function"})
else: self.constr()(self.obj.{curved: "none"})
end
end
labels-method = method(self, labels :: P.LoS):
block:
when self.obj!ps.length() <> labels.length():
raise('plot: xs and labels should have the same length')
end
self.constr()(self.obj.{ps: map2({(arr, label): raw-array-set(arr, 2, label)}, self.obj!ps, labels)})
end
end
image-labels-method = method(self, images :: P.LoI):
block:
when self.obj!ps.length() <> images.length():
raise('plot: xs and images should have the same length')
end
self.constr()(self.obj.{ps: map2({(arr, image): raw-array-set(arr, 3, image)}, self.obj!ps, images)})
end
end
explode-method = method(self, offsets :: P.LoN) block:
when raw-array-length(self.obj!tab) <> offsets.length():
raise('exploding-pie-chart: labels and offsets should have the same length')
end
for each(offset from offsets):
when (offset < 0) or (offset > 1):
raise('exploding-pie-chart: offset must be between 0 and 1')
end
end
self.constr()(self.obj.{tab: raw-array-from-list(map2({(arr, offset): raw-array-set(arr, 2, offset)}, raw-array-to-list(self.obj!tab), offsets))})
end
histogram-label-method = method(self, labels :: P.LoS) block:
when raw-array-length(self.obj!tab) <> labels.length():
raise('histogram: xs and labels should have the same length')
end
self.constr()(self.obj.{tab: raw-array-from-list(map2({(arr, label): raw-array-set(arr, 0, label)}, raw-array-to-list(self.obj!tab), labels))})
end
box-labels-method = method(self, labels :: P.LoS) block:
when labels.length() <> self.obj!values.length():
raise('labeled-box-plot: labels and values should have the same length')
end
when labels.length() == 0:
raise('labeled-box-plot: expect at least one box')
end
self.constr()(self.obj.{tab: map2(get-box-data, labels, self.obj!values) ^ builtins.raw-array-from-list,})
end
threeD-method = method(self, threeD :: Boolean):
self.constr()(self.obj.{threeD: threeD})
end
piehole-method = method(self, piehole :: Number):
if (piehole < 0) or (piehole > 1): raise("piehole: Value must be between 0 and 1")
else: self.constr()(self.obj.{piehole: piehole})
end
end
starting-angle-method = method(self, startingAngle :: Number):
self.constr()(self.obj.{startingAngle: startingAngle})
end
collapse-threshold-method = method(self, collapseThreshold :: Number) block:
when (collapseThreshold < 0) or (collapseThreshold > 1):
raise("collapse-threshold: Threshold must be between 0 and 1")
end
self.constr()(self.obj.{collapseThreshold: collapseThreshold})
end
trendline-type-method = method(self, trendlineType :: TrendlineType):
cases (TrendlineType) trendlineType:
| no-trendline => self.constr()(self.obj.{trendlineType: none})
| linear => self.constr()(self.obj.{trendlineType: some("linear")})
| exponential => self.constr()(self.obj.{trendlineType: some("exponential")})
| polynomial(degree) => self.constr()(self.obj.{trendlineType: some("polynomial"), trendlineDegree: degree})
end
end
trendline-color-method = method(self, color :: I.Color):
self.constr()(self.obj.{trendlineColor: some(color)})
end
trendline-width-method = method(self, lineWidth :: Number) block:
when lineWidth < 0:
raise("trendline-width: Trendline Width must be non-negative")
end
self.constr()(self.obj.{trendlineWidth: lineWidth})
end
trendline-opacity-method = method(self, opacity :: Number):
if (opacity < 0) or (opacity > 1): raise("Trendline opacity: Value must be between 0 and 1")
else: self.constr()(self.obj.{trendlineOpacity: opacity})
end
end
dashed-line-method = method(self, dashed :: Boolean):
self.constr()(self.obj.{dashedLine: dashed})
end
dashed-line-style-method = method(self, dashed-line-style :: P.LoNi) block:
when any({(n): n < 0}, dashed-line-style):
raise("Dashed Line Style: Values must be non-negative")
end
self.constr()(self.obj.{dashedLine: true, dashlineStyle: raw-array-from-list(dashed-line-style)})
end
pointshape-method = method(self, pointshape :: PointShape):
cases (PointShape) pointshape:
| circle-shape => self.constr()(self.obj.{pointshapeType: "circle"})
| regular-polygon-shape(sides, dent) => self.constr()(self.obj.{pointshapeType: "polygon", pointshapeSides: sides, pointshapeDent: dent})
end
end
select-multiple-method = method(self, multiple :: Boolean):
self.constr()(self.obj.{multiple: multiple})
end
background-color-method = method(self, color :: I.Color):
self.constr()(self.obj.{backgroundColor: some(color)})
end
background-border-method = method(self, border-size :: Number) block:
when border-size < 0:
raise("border-size: Border Size must be non-negative")
end
self.constr()(self.obj.{borderSize: border-size})
end
border-color-method = method(self, border-color :: I.Color):
self.constr()(self.obj.{borderColor: some(border-color)})
end
legend-method = method(self, legend :: String):
self.constr()(self.obj.{legend: legend})
end
show-minor-grid-lines-method = method(self, is-showing :: Boolean):
self.constr()(self.obj.{show-minor-grid-lines: is-showing})
end
gridlines-color-method = method(self, color :: I.Color):
self.constr()(self.obj.{gridlineColor: some(color)})
end
minor-gridlines-color-method = method(self, color :: I.Color):
self.constr()(self.obj.{show-minor-grid-lines: true, minorGridlineColor: some(color)})
end
gridlines-min-spacing-method = method(self, minspacing :: Number) block:
when minspacing < 0:
raise("gridlines-minspacing: Min spacing must be non-negative")
end
self.constr()(self.obj.{gridlineMinspacing: some(minspacing)})
end
minor-gridlines-min-spacing-method = method(self, minspacing :: Number) block:
when minspacing < 0:
raise("minor-gridlines-minspacing: Min spacing must be non-negative")
end
self.constr()(self.obj.{show-minor-grid-lines: true, minorGridlineMinspacing: minspacing})
end
x-axis-method = method(self, x-axis :: String):
self.constr()(self.obj.{x-axis: x-axis})
end
y-axis-method = method(self, y-axis :: String):
self.constr()(self.obj.{y-axis: y-axis})
end
x-min-method = method(self, x-min :: Number):
self.constr()(self.obj.{x-min: some(x-min)})
end
x-max-method = method(self, x-max :: Number):
self.constr()(self.obj.{x-max: some(x-max)})
end
y-min-method = method(self, y-min :: Number):
self.constr()(self.obj.{y-min: some(y-min)})
end
y-max-method = method(self, y-max :: Number):
self.constr()(self.obj.{y-max: some(y-max)})
end
sort-method = method(self,
cmp :: (Number, Number -> Boolean),
eq :: (Number, Number -> Boolean)):
fun get-value(row :: RawArray) -> Number:
doc:```
VALUE GETTER: Gets the values from the row of data in Number form
ASSUMES the row of data is ordered by [LABEL, VALUES, OTHER]
```
raw-array-get(row, 1)
end
identity = {(x): x}
sorted-table = table-sorter(self.obj!tab, get-value, identity, cmp, eq)
self.constr()(self.obj.{tab: sorted-table})
end
default-sort-method = method(self):
self.sort-by({(a, b): a < b}, {(a, b): a == b})
end
label-sort-method = method(self,
cmp :: (String, String -> Boolean),
eq :: (String, String -> Boolean)):
fun get-label(row :: RawArray) -> String:
doc:```
VALUE GETTER: Gets the values from the row of data in Number form
ASSUMES the row of data is ordered by [LABEL, VALUES, OTHER]
```
raw-array-get(row, 0)
end
identity = {(x): x}
sorted-table = table-sorter(self.obj!tab, get-label, identity, cmp, eq)
self.constr()(self.obj.{tab: sorted-table})
end
multi-sort-method = method(self,
scorer :: (List<Number> -> Number),
cmp :: (Number, Number -> Boolean),
eq :: (Number, Number -> Boolean)):
fun get-values(row :: RawArray) -> List<Number>:
doc:```
VALUE GETTER: Gets the values from the row of data in List form
ASSUMES the row of data is ordered by [LABEL, VALUES, OTHER]
```
raw-array-get(row, 1) ^ raw-array-to-list
end
sorted-table = table-sorter(self.obj!tab, get-values, scorer, cmp, eq)
self.constr()(self.obj.{tab: sorted-table})
end
default-multi-sort-method = method(self,
cmp :: (Number, Number -> Boolean),
eq :: (Number, Number -> Boolean)):
fun get-values(row :: RawArray) -> List<Number>:
doc:```
VALUE GETTER: Gets the values from the row of data in List form
ASSUMES the row of data is ordered by [LABEL, VALUES, OTHER]
```
raw-array-get(row, 1) ^ raw-array-to-list
end
sum = {(l :: List<Number>): fold({(acc, elm): acc + elm}, 0, l)}
sorted-table = table-sorter(self.obj!tab, get-values, sum, cmp, eq)
self.constr()(self.obj.{tab: sorted-table})
end
super-default-multi-sort-method = method(self):
self.sort-by({(a, b): a < b}, {(a, b): a == b})
end
axis-pointer-method = method(self,
tickValues :: P.LoN,
tickLabels :: P.LoS) block:
# Lengths of Lists
TVLen = tickValues.length()
TLLen = tickLabels.length()
distinctTVLen = distinct(tickValues).length()
# Edge Case Error Checking
when not(distinctTVLen == TVLen):
raise('add-pointers: pointers cannot overlap')
end
when not(TVLen == TLLen):
raise('add-pointers: pointers values and names should have the same length')
end
ticks = fold2({(acc, e1, e2): link(pointer(e1, e2), acc)}, empty, tickLabels, tickValues)
self.constr()(self.obj.{pointers: some(distinct(ticks) ^ builtins.raw-array-from-list)})
end
make-axis-data-method = method(self, pos-bar-height :: Number, neg-bar-height :: Number):
step-types = [list: 0, 0.2, 0.25, 0.5, 1, 2]
# Turn the numbers into Scientific Numbers
scientific-b10 = num-to-scientific(10)
pos-sci = scientific-b10(pos-bar-height)
neg-sci = scientific-b10(neg-bar-height)
# Calculate the step distance between gridlines
pos-step = step-types.filter({(n): n >= num-abs(pos-sci.coeff / 9)}).get(0) * num-expt(10, pos-sci.exponent)
neg-step = step-types.filter({(n): n >= num-abs(neg-sci.coeff / 9)}).get(0) * num-expt(10, neg-sci.exponent)
step = num-max(pos-step, neg-step)
step-sci = scientific-b10(step)
# Use step distance to calculate Axis Properties
name-tick =
{(n):
ask:
| (step-sci.coeff == 2.5) and (step-sci.exponent <= 0) then:
pointer(num-to-string-digits(n, 2 - step-sci.exponent), n)
| step-sci.exponent < 0 then:
pointer(num-to-string-digits(n, 1 - step-sci.exponent), n)
| otherwise:
pointer(num-to-string(n), n)
end}
axisTop = num-max(0, step * num-ceiling(pos-bar-height / step))
axisBottom = num-min(0, step * num-floor(neg-bar-height / step))
pos-ticks = map(name-tick, range-by(0, axisTop + step, step))
neg-ticks = map(name-tick, range-by(0, axisBottom - step, -1 * step))
ticks = distinct(pos-ticks + neg-ticks) ^ builtins.raw-array-from-list
self.constr()(
self.obj.{axisdata: some(axis-data(axisTop, axisBottom, ticks))}
)
end
format-axis-data-method = method(self, format-func :: (Number -> String)):
cases (Option) self.obj!axisdata:
| none =>
raise("Axis properties initialized improperly. Please report as a bug!")
| some(ad) =>
ad-tick-list = ad.ticks ^ raw-array-to-list
new-ticks = map({(p): pointer(format-func(p.value), p.value)}, ad-tick-list) ^ builtins.raw-array-from-list
self.constr()(self.obj.{axisdata: some(axis-data(ad.axisTop, ad.axisBottom, new-ticks))})
end
end
scale-method = method(self, scale-fun :: (Number -> Number)):
exact-sf = {(n): n ^ scale-fun ^ num-to-rational}
list-of-rows = self.obj!tab ^ raw-array-to-list
scale-row = {(row): [raw-array: raw-array-get(row, 0), raw-array-get(row, 1) ^ exact-sf]}
scaled-tab = map(scale-row, list-of-rows) ^ builtins.raw-array-from-list
scaled-self = self.constr()(self.obj.{tab: scaled-tab})
scaled-values = map({(row): raw-array-get(row, 1) ^ exact-sf}, list-of-rows)
{max-positive-height; max-negative-height} = prep-axis(scaled-values)
scaled-self.make-axis(max-positive-height, max-negative-height)
end
multi-scale-method = method(self, scale-fun :: (Number -> Number)):
exact-sf = {(n): n ^ scale-fun ^ num-to-rational}
list-of-rows = self.obj!tab ^ raw-array-to-list
get-values = {(row): raw-array-get(row, 1) ^ raw-array-to-list}
scale-row = {(row): [raw-array: raw-array-get(row, 0), map(exact-sf, row ^ get-values) ^ builtins.raw-array-from-list]}
scaled-tab = map(scale-row, list-of-rows) ^ builtins.raw-array-from-list
scaled-self = self.constr()(self.obj.{tab: scaled-tab})
scaled-values = map({(row): map(exact-sf, row ^ get-values)}, list-of-rows)
{max-positive-height; max-negative-height} =
multi-prep-axis(string-to-stacktype(scaled-self.obj!is-stacked), scaled-values)
scaled-self.make-axis(max-positive-height, max-negative-height)
end
stacking-type-method = method(self, stack-type :: StackType):
get-values = {(row): raw-array-get(row, 1) ^ raw-array-to-list}
value-lists = map(get-values, self.obj!tab ^ raw-array-to-list)
ask:
| stack-type == absolute then:
new-self = self.constr()(self.obj.{is-stacked: 'absolute'})
{max-positive-height; max-negative-height} =
multi-prep-axis(absolute, value-lists)
new-self.make-axis(max-positive-height, max-negative-height)
| stack-type == relative then:
new-self = self.constr()(self.obj.{is-stacked: 'relative'})
{max-positive-height; max-negative-height} =
multi-prep-axis(relative, value-lists)
new-self.make-axis(max-positive-height, max-negative-height)
| stack-type == percent then:
new-self = self.constr()(self.obj.{is-stacked: 'percent'})
{max-positive-height; max-negative-height} =
multi-prep-axis(percent, value-lists)
new-self.make-axis(max-positive-height, max-negative-height)
.format-axis({(n): num-to-string(n * 100) + "%"})
| stack-type == grouped then:
new-self = self.constr()(self.obj.{is-stacked: 'none'})
{max-positive-height; max-negative-height} =
multi-prep-axis(grouped, value-lists)
new-self.make-axis(max-positive-height, max-negative-height)
| otherwise: raise('stacking-type: type must be absolute, relative, percent, or grouped')
end
end
annotations-method = method(self,
annotations :: P.LoLoOoS) block:
# Annotations should match previous lengths
expected-length = raw-array-length(self.obj.annotations)
given-length = annotations.length()
when given-length <> expected-length:
raise("annotations: input dimensions mismatch. Expected length "
+ num-to-string(expected-length)
+ ", received "
+ num-to-string(given-length))
end
block:
each({(l :: List<Option<String>>):
each({(o :: Option<String>):
cases (Option) o:
| none => true
| some(s :: String) => true
end}, l)}, annotations)
for each3(expected from raw-array-to-list(self.obj.annotations),
given from annotations,
index from range(0, annotations.length())):
shadow expected-length = raw-array-length(expected)
shadow given-length = given.length()
when given-length <> expected-length:
raise("annotations: length mismatch on row "
+ num-to-string(index)
+ ". Expected "
+ num-to-string(expected-length)
+ ", received "
+ num-to-string(given-length))
end
end
end
self.constr()(self.obj.{annotations: list-to-table2(annotations)})
end
single-annotations-method = method(self, annotations :: P.LoOoS):
self.{annotations-method: annotations-method}
.annotations-method(annotations.map(link(_, empty)))
end
intervals-method = method(self, intervals :: P.LoLoLoN) block:
expected-length = raw-array-length(self.obj.intervals)
given-length = intervals.length()
when given-length <> expected-length:
raise("intervals: input dimensions mismatch. Expected length "
+ num-to-string(expected-length)
+ ", received "
+ num-to-string(given-length))
end
block:
each({(l :: List<List<Number>>):
each({(l1 :: List<Number>):
each({(n :: Number): true}, l1)}, l)}, intervals)
for each3(expected from raw-array-to-list(self.obj.intervals),
given from intervals,
index from range(0, intervals.length())):
shadow expected-length = raw-array-length(expected)
shadow given-length = given.length()
when given-length <> expected-length:
raise("intervals: length mismatch on row "
+ num-to-string(index)
+ ". Expected "
+ num-to-string(expected-length)
+ ", received "
+ num-to-string(given-length))
end
end
end
raw-intervals = intervals.map(_.map(raw-array-from-list)) ^ list-to-table2
flatten = {(lol): fold({(acc, elm): acc + elm}, empty, lol)}
curr-axis = self.obj!axisdata.value
interval-max = fold(num-max, 0, flatten(flatten(intervals)))
interval-min = fold(num-min, 0, flatten(flatten(intervals)))
self.constr()(
self.obj.{intervals: raw-intervals})
.make-axis(
num-max(curr-axis.axisTop, interval-max),
num-min(curr-axis.axisBottom, interval-min))
end
single-intervals-method = method(self, intervals :: P.LoLoN):
self.{intervals: intervals-method}.intervals(intervals.map(link(_, empty)))
end
error-bars-method = method(self, errors :: P.LoLoLoN) block:
doc: ```Given a list of one negative number and one positive number for every
data point, set intervals to lower and upper error intervals.```
expected-length = raw-array-length(self.obj.intervals)
given-length = errors.length()
when given-length <> expected-length:
raise("error-bars: input dimensions mismatch. Expected length "
+ num-to-string(expected-length)
+ ", received "
+ num-to-string(given-length))
end
block:
each({(l :: List<List<Number>>):
each({(l1 :: List<Number>):
each({(n :: Number): true}, l1)}, l)}, errors)
for each3(expected from raw-array-to-list(self.obj.intervals),
given from errors,
index from range(0, errors.length())):
block:
shadow expected-length = raw-array-length(expected)
shadow given-length = given.length()
row-str = num-to-string(index)
when given-length <> expected-length:
raise("error-bars: length mismatch on row " + row-str
+ ". Expected "
+ num-to-string(expected-length)
+ ", received "
+ num-to-string(given-length))
end
for each2(pair from given, column from range(0, given.length())):
block:
col-str = num-to-string(column)
when pair.length() <> 2:
raise("error-bars: on row " + row-str + " column " + col-str
+ ", 2 intervals must be given.")
end
when pair.get(0) > 0:
raise("error-bars: on row " + row-str + " column " + col-str
+ ", first pair must be non-positive.")
end
when pair.get(1) < 0:
raise("error-bars: on row " + row-str + " column " + col-str
+ ", second pair must be non-negative.")
end
end
end
end
end
end
# Defer to intervals-method
raw-table-data = raw-array-map(raw-array-get(_, 1), self.obj.tab)
table-data = table2-to-list(raw-table-data)
intervals-at-end = for map2(data-row from table-data,
error-row from errors):
for map2(data-col from data-row, error-bounds from error-row):
error-bounds.map(_ + data-col)
end
end
self.intervals(intervals-at-end)
end
single-error-bars-method = method(self, errors :: P.LoLoN) block:
doc: ```Given a list of pairs of one positive and one negative number
corresponding to upper and lower bounds, produces a chart with error
bars using the given bounds.```
expected-length = raw-array-length(self.obj.intervals)
given-length = errors.length()
when given-length <> expected-length:
raise("error-bars: input dimensions mismatch. Expected length "
+ num-to-string(expected-length)
+ ", received "
+ num-to-string(given-length))
end
block:
each({(l :: List<Number>):
each({(n :: Number): true}, l)}, errors)
for each3(expected from raw-array-to-list(self.obj.intervals),
given from errors,
index from range(0, errors.length())):
block:
row-str = num-to-string(index)
when given.length() <> 2:
raise("error-bars: on row " + row-str
+ ", 2 intervals must be given (received "
+ num-to-string(given.length()) + ").")
end
when given.get(0) > 0:
raise("error-bars: on row " + row-str
+ ", first pair must be non-positive.")
end
when given.get(1) < 0:
raise("error-bars: on row " + row-str
+ ", second pair must be non-negative.")
end
end
end
end
# Defer to intervals-method
raw-table-data = raw-array-map(raw-array-get(_, 1), self.obj.tab)
table-data = raw-array-to-list(raw-table-data)
intervals-at-end = for map2(data-val from table-data,
error from errors):
error.map(_ + data-val)
end
self.intervals(intervals-at-end)
end
min-method = method(self, min :: Number):
self.constr()(self.obj.{min: some(min)})
end
max-method = method(self, max :: Number):
self.constr()(self.obj.{max: some(max)})
end
################################################################################
# BOUNDING BOX
################################################################################
type BoundingBox = {
x-min :: Number,
x-max :: Number,
y-min :: Number,
y-max :: Number,
is-valid :: Boolean
}
default-bounding-box :: BoundingBox = {
x-min: 0,
x-max: 0,
y-min: 0,
y-max: 0,
is-valid: false,
}
fun get-bounding-box(ps :: List<Posn>) -> BoundingBox:
cases (List<Number>) ps:
| empty => default-bounding-box.{is-valid: false}
| link(f, r) =>
fun compute(p :: (Number, Number -> Number), accessor :: (Posn -> Number)):
for fold(prev from accessor(f), e from r): p(prev, accessor(e)) end
end
default-bounding-box.{
x-min: compute(num-min, fst),
x-max: compute(num-max, fst),
y-min: compute(num-min, snd),
y-max: compute(num-max, snd),
is-valid: true,
}
end
end
fun get-list-of-bounding-boxes(list-of-plots, self, other-accessor) -> List<BoundingBox>:
for map(plot-pts from list-of-plots):
for filter(pt from plot-pts):
cases (Option) self.x-min:
| none => true
| some(v) => fst(pt) >= v
end and
cases (Option) self.x-max:
| none => true
| some(v) => fst(pt) <= v
end and
cases (Option) self.y-min:
| none => true
| some(v) => other-accessor(pt) >= v
end and
cases (Option) self.y-max:
| none => true
| some(v) => other-accessor(pt) <= v
end
end ^ get-bounding-box
end
end
fun merge-bounding-box(bs :: List<BoundingBox>) -> BoundingBox:
for fold(prev from default-bounding-box, e from bs):
ask: