-
Notifications
You must be signed in to change notification settings - Fork 63
/
basics.lib
2931 lines (2664 loc) · 94.7 KB
/
basics.lib
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
//#################################### basics.lib ########################################
// A library of basic elements. Its official prefix is `ba`.
//
// #### References
// * <https://github.com/grame-cncm/faustlibraries/blob/master/basics.lib>
//########################################################################################
// A library of basic elements for Faust organized in 5 sections:
//
// * Conversion Tools
// * Counters and Time/Tempo Tools
// * Array Processing/Pattern Matching
// * Selectors (Conditions)
// * Other Tools (Misc)
//########################################################################################
/************************************************************************
************************************************************************
FAUST library file, GRAME section
Except where noted otherwise, Copyright (C) 2003-2017 by GRAME,
Centre National de Creation Musicale.
----------------------------------------------------------------------
GRAME LICENSE
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
EXCEPTION TO THE LGPL LICENSE : As a special exception, you may create a
larger FAUST program which directly or indirectly imports this library
file and still distribute the compiled code generated by the FAUST
compiler, or a modified version of this compiled code, under your own
copyright and license. This EXCEPTION TO THE LGPL LICENSE explicitly
grants you the right to freely choose the license for the resulting
compiled code. In particular the resulting compiled code has no obligation
to be LGPL or GPL. For example you are free to choose a commercial or
closed source license or any other license if you decide so.
************************************************************************
************************************************************************/
ma = library("maths.lib");
ro = library("routes.lib");
ba = library("basics.lib"); // for compatible copy/paste out of this file
fi = library("filters.lib");
it = library("interpolators.lib");
si = library("signals.lib");
declare name "Faust Basic Element Library";
declare version "1.21.0";
//=============================Conversion Tools===========================================
//========================================================================================
//-------`(ba.)samp2sec`----------
// Converts a number of samples to a duration in seconds at the current sampling rate (see `ma.SR`).
// `samp2sec` is a standard Faust function.
//
// #### Usage
//
// ```
// samp2sec(n) : _
// ```
//
// Where:
//
// * `n`: number of samples
//----------------------------
samp2sec(n) = n/ma.SR;
//-------`(ba.)sec2samp`----------
// Converts a duration in seconds to a number of samples at the current sampling rate (see `ma.SR`).
// `samp2sec` is a standard Faust function.
//
// #### Usage
//
// ```
// sec2samp(d) : _
// ```
//
// Where:
//
// * `d`: duration in seconds
//----------------------------
sec2samp(d) = d*ma.SR;
//-------`(ba.)db2linear`----------
// dB-to-linear value converter. It can be used to convert an amplitude in dB to a linear gain ]0-N].
// `db2linear` is a standard Faust function.
//
// #### Usage
//
// ```
// db2linear(l) : _
// ```
//
// Where:
//
// * `l`: amplitude in dB
//-----------------------------
db2linear(l) = pow(10.0, l/20.0);
//-------`(ba.)linear2db`----------
// linea-to-dB value converter. It can be used to convert a linear gain ]0-N] to an amplitude in dB.
// `linear2db` is a standard Faust function.
//
// #### Usage
//
// ```
// linear2db(g) : _
// ```
//
// Where:
//
// * `g`: a linear gain
//-----------------------------
linear2db(g) = 20.0*log10(max(ma.MIN, g));
//----------`(ba.)lin2LogGain`------------------
// Converts a linear gain (0-1) to a log gain (0-1).
//
// #### Usage
//
// ```
// lin2LogGain(n) : _
// ```
//
// Where:
//
// * `n`: the linear gain
//---------------------------------------------
lin2LogGain(n) = n*n;
//----------`(ba.)log2LinGain`------------------
// Converts a log gain (0-1) to a linear gain (0-1).
//
// #### Usage
//
// ```
// log2LinGain(n) : _
// ```
//
// Where:
//
// * `n`: the log gain
//---------------------------------------------
log2LinGain(n) = sqrt(n);
// end GRAME section
//########################################################################################
/************************************************************************
FAUST library file, jos section
Except where noted otherwise, The Faust functions below in this
section are Copyright (C) 2003-2017 by Julius O. Smith III <[email protected]>
([jos](http://ccrma.stanford.edu/~jos/)), and released under the
(MIT-style) [STK-4.3](#stk-4.3-license) license.
The MarkDown comments in this section are Copyright 2016-2017 by Romain
Michon and Julius O. Smith III, and are released under the
[CCA4I](https://creativecommons.org/licenses/by/4.0/) license (TODO: if/when Romain agrees)
************************************************************************/
//-------`(ba.)tau2pole`----------
// Returns a real pole giving exponential decay.
// Note that t60 (time to decay 60 dB) is ~6.91 time constants.
// `tau2pole` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : smooth(tau2pole(tau)) : _
// ```
//
// Where:
//
// * `tau`: time-constant in seconds
//-----------------------------
// tau2pole(tau) = exp(-1.0/(tau*ma.SR));
tau2pole(tau) = ba.if(clipCond, 0.0, exp(-1.0/(tauCenterClipped*float(ma.SR))))
with {
clipCond = abs(tau)<ma.EPSILON;
tauCenterClipped = ba.if(clipCond, 1.0, tau); // 1.0 can be any nonzero value (not used)
};
//-------`(ba.)pole2tau`----------
// Returns the time-constant, in seconds, corresponding to the given real,
// positive pole in (0-1).
// `pole2tau` is a standard Faust function.
//
// #### Usage
//
// ```
// pole2tau(pole) : _
// ```
//
// Where:
//
// * `pole`: the pole
//-----------------------------
pole2tau(pole) = -1.0/(log(max(ma.MIN, pole))*ma.SR);
//-------`(ba.)midikey2hz`----------
// Converts a MIDI key number to a frequency in Hz (MIDI key 69 = A440).
// `midikey2hz` is a standard Faust function.
//
// #### Usage
//
// ```
// midikey2hz(mk) : _
// ```
//
// Where:
//
// * `mk`: the MIDI key number
//-----------------------------
midikey2hz(mk) = 440.0*pow(2.0, (mk-69.0)/12.0);
//-------`(ba.)hz2midikey`----------
// Converts a frequency in Hz to a MIDI key number (MIDI key 69 = A440).
// `hz2midikey` is a standard Faust function.
//
// #### Usage
//
// ```
// hz2midikey(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//-----------------------------
hz2midikey(freq) = 12.0*ma.log2(freq/440.0) + 69.0;
//-------`(ba.)semi2ratio`----------
// Converts semitones in a frequency multiplicative ratio.
// `semi2ratio` is a standard Faust function.
//
// #### Usage
//
// ```
// semi2ratio(semi) : _
// ```
//
// Where:
//
// * `semi`: number of semitone
//-----------------------------
semi2ratio(semi) = pow(2.0, semi/12.0);
//-------`(ba.)ratio2semi`----------
// Converts a frequency multiplicative ratio in semitones.
// `ratio2semi` is a standard Faust function.
//
// #### Usage
//
// ```
// ratio2semi(ratio) : _
// ```
//
// Where:
//
// * `ratio`: frequency multiplicative ratio
//-----------------------------
ratio2semi(ratio) = 12.0*log(ratio)/log(2.0);
//-------`(ba.)cent2ratio`----------
// Converts cents in a frequency multiplicative ratio.
//
// #### Usage
//
// ```
// cent2ratio(cent) : _
// ```
//
// Where:
//
// * `cent`: number of cents
//-----------------------------
cent2ratio(cent) = pow(2.0, cent/1200.0);
//-------`(ba.)ratio2cent`----------
// Converts a frequency multiplicative ratio in cents.
//
// #### Usage
//
// ```
// ratio2cent(ratio) : _
// ```
//
// Where:
//
// * `ratio`: frequency multiplicative ratio
//-----------------------------
ratio2cent(ratio) = 1200.0*log(ratio)/log(2.0);
//-------`(ba.)pianokey2hz`----------
// Converts a piano key number to a frequency in Hz (piano key 49 = A440).
//
// #### Usage
//
// ```
// pianokey2hz(pk) : _
// ```
//
// Where:
//
// * `pk`: the piano key number
//-----------------------------
pianokey2hz(pk) = 440.0*pow(2.0, (pk-49.0)/12.0);
//-------`(ba.)hz2pianokey`----------
// Converts a frequency in Hz to a piano key number (piano key 49 = A440).
//
// #### Usage
//
// ```
// hz2pianokey(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//-----------------------------
hz2pianokey(freq) = 12.0*ma.log2(freq/440.0) + 49.0;
// end jos section
//########################################################################################
/************************************************************************
FAUST library file, GRAME section 2
************************************************************************/
//==============================Counters and Time/Tempo Tools=============================
//========================================================================================
//----------------------------`(ba.)counter`------------------------------
// Starts counting 0, 1, 2, 3..., and raise the current integer value
// at each upfront of the trigger.
//
// #### Usage
//
// ```
// counter(trig) : _
// ```
//
// Where:
//
// * `trig`: the trigger signal, each upfront will move the counter to the next integer
//-----------------------------------------------------------------------------
declare counter author "Stephane Letz";
counter(trig) = upfront(trig) : + ~ _ with { upfront(x) = x > x'; };
//----------------------------`(ba.)countdown`------------------------------
// Starts counting down from n included to 0. While trig is 1 the output is n.
// The countdown starts with the transition of trig from 1 to 0. At the end
// of the countdown the output value will remain at 0 until the next trig.
// `countdown` is a standard Faust function.
//
// #### Usage
//
// ```
// countdown(n,trig) : _
// ```
//
// Where:
//
// * `n`: the starting point of the countdown
// * `trig`: the trigger signal (1: start at `n`; 0: decrease until 0)
//-----------------------------------------------------------------------------
countdown(n, trig) = \(c).(if(trig>0, n, max(0, c-1))) ~ _;
//----------------------------`(ba.)countup`--------------------------------
// Starts counting up from 0 to n included. While trig is 1 the output is 0.
// The countup starts with the transition of trig from 1 to 0. At the end
// of the countup the output value will remain at n until the next trig.
// `countup` is a standard Faust function.
//
// #### Usage
//
// ```
// countup(n,trig) : _
// ```
//
// Where:
//
// * `n`: the maximum count value
// * `trig`: the trigger signal (1: start at 0; 0: increase until `n`)
//-----------------------------------------------------------------------------
countup(n, trig) = \(c).(if(trig>0, 0, min(n, c+1))) ~ _;
//--------------------`(ba.)sweep`--------------------------
// Counts from 0 to `period-1` repeatedly, generating a
// sawtooth waveform, like `os.lf_rawsaw`,
// starting at 1 when `run` transitions from 0 to 1.
// Outputs zero while `run` is 0.
//
// #### Usage
//
// ```
// sweep(period,run) : _
// ```
//-----------------------------------------------------------------
declare sweep author "Jonatan Liljedahl";
sweep = %(int(*:max(1)))~+(1);
//-------`(ba.)time`----------
// A simple timer that counts every samples from the beginning of the process.
// `time` is a standard Faust function.
//
// #### Usage
//
// ```
// time : _
// ```
//------------------------
time = +(1)~_ : mem;
//-------`(ba.)ramp`----------
// A linear ramp with a slope of '(+/-)1/n' samples to reach the next target value.
//
// #### Usage
//
// ```
// _ : ramp(n) : _
// ```
// Where:
//
// * `n`: number of samples to increment/decrement the value by one
//------------------------
ramp = case {
(0) => _;
(n) => \(y,x).(if(y+1.0/n < x, y+1.0/n, if(y-1.0/n > x, y-1.0/n, x))) ~ _;
};
//-------`(ba.)line`----------
// A ramp interpolator that generates a linear transition to reach a target value:
//
// - the interpolation process restarts each time a new and distinct input value is received
// - it utilizes 'n' samples to achieve the transition to the target value
// - after reaching the target value, the output value is maintained.
//
// #### Usage
//
// ```
// _ : line(n) : _
// ```
// Where:
//
// * `n`: number of samples to reach the new target received at its input
//------------------------
line(n, x) = state ~ (_,_) : !,_
with {
state(t, c) = nt,nc
with {
nt = ba.if(x != x', n, t-1);
nc = ba.if(nt > 0, c + (x - c)/nt, x);
};
};
//-------`(ba.)tempo`----------
// Converts a tempo in BPM into a number of samples.
//
// #### Usage
//
// ```
// tempo(t) : _
// ```
//
// Where:
//
// * `t`: tempo in BPM
//------------------------
tempo(t) = (60*ma.SR)/t;
//-------`(ba.)period`----------
// Basic sawtooth wave of period `p`.
//
// #### Usage
//
// ```
// period(p) : _
// ```
//
// Where:
//
// * `p`: period as a number of samples
//------------------------
// NOTE: may be this should go in oscillators.lib
period(p) = %(int(p))~+(1');
//-------`(ba.)spulse`----------
// Produces a single pulse of n samples when trig goes from 0 to 1.
//
// #### Usage
//
// ```
// spulse(n,trig) : _
// ```
//
// Where:
//
// * `n`: pulse length as a number of samples
// * `trig`: the trigger signal (1: start the pulse)
//------------------------
spulse(n, trig) = trig : trigger(n)
with {
upfront(x) = x > x'; // detect rising edge
reset = upfront(trig); // reset signal
decay(n, x) = ba.if(reset, 0, x - (x>0.0)/n); // decay the pulse, possibly using reset to restart the pulse
release(n) = + ~ decay(n);
trigger(n) = upfront : release(n) : >(0.0);
};
//-------`(ba.)pulse`----------
// Pulses (like 10000) generated at period `p`.
//
// #### Usage
//
// ```
// pulse(p) : _
// ```
//
// Where:
//
// * `p`: period as a number of samples
//------------------------
// NOTE: may be this should go in oscillators.lib
pulse(p) = period(p) : \(x).(x <= x');
//-------`(ba.)pulsen`----------
// Pulses (like 11110000) of length `n` generated at period `p`.
//
// #### Usage
//
// ```
// pulsen(n,p) : _
// ```
//
// Where:
//
// * `n`: pulse length as a number of samples
// * `p`: period as a number of samples
//------------------------
// NOTE: may be this should go in oscillators.lib
pulsen(n,p) = period(p)<n;
//-----------------------`(ba.)cycle`---------------------------
// Split nonzero input values into `n` cycles.
//
// #### Usage
//
// ```
// _ : cycle(n) : si.bus(n)
// ```
//
// Where:
//
// * `n`: the number of cycles/output signals
//---------------------------------------------------------
declare cycle author "Mike Olsen";
cycle(n) = _ <: par(i,n,resetCtr(n,(i+1)));
//-------`(ba.)beat`----------
// Pulses at tempo `t` in BPM.
// `beat` is a standard Faust function.
//
// #### Usage
//
// ```
// beat(t) : _
// ```
//
// Where:
//
// * `t`: tempo in BPM
//------------------------
beat(t) = pulse(tempo(t));
//----------------------------`(ba.)pulse_countup`-----------------------------------
// Starts counting up pulses. While trig is 1 the output is
// counting up, while trig is 0 the counter is reset to 0.
//
// #### Usage
//
// ```
// _ : pulse_countup(trig) : _
// ```
//
// Where:
//
// * `trig`: the trigger signal (1: start at next pulse; 0: reset to 0)
//------------------------------------------------------------------------------
declare pulse_countup author "Vince";
pulse_countup(trig) = + ~ _ * trig;
//----------------------------`(ba.)pulse_countdown`---------------------------------
// Starts counting down pulses. While trig is 1 the output is
// counting down, while trig is 0 the counter is reset to 0.
//
// #### Usage
//
// ```
// _ : pulse_countdown(trig) : _
// ```
//
// Where:
//
// * `trig`: the trigger signal (1: start at next pulse; 0: reset to 0)
//------------------------------------------------------------------------------
declare pulse_countdown author "Vince";
pulse_countdown(trig) = - ~ _ * trig;
//----------------------------`(ba.)pulse_countup_loop`------------------------------
// Starts counting up pulses from 0 to n included. While trig is 1 the output is
// counting up, while trig is 0 the counter is reset to 0. At the end
// of the countup (n) the output value will be reset to 0.
//
// #### Usage
//
// ```
// _ : pulse_countup_loop(n,trig) : _
// ```
//
// Where:
//
// * `n`: the highest number of the countup (included) before reset to 0
// * `trig`: the trigger signal (1: start at next pulse; 0: reset to 0)
//------------------------------------------------------------------------------
declare pulse_countup_loop author "Vince";
pulse_countup_loop(n, trig) = + ~ cond(n)*trig
with {
cond(n, x) = x * (x <= n);
};
//----------------------------`(ba.)pulse_countdown_loop`----------------------------
// Starts counting down pulses from 0 to n included. While trig is 1 the output
// is counting down, while trig is 0 the counter is reset to 0. At the end
// of the countdown (n) the output value will be reset to 0.
//
// #### Usage
//
// ```
// _ : pulse_countdown_loop(n,trig) : _
// ```
//
// Where:
//
// * `n`: the highest number of the countup (included) before reset to 0
// * `trig`: the trigger signal (1: start at next pulse; 0: reset to 0)
//------------------------------------------------------------------------------
declare pulse_countdown_loop author "Vince";
pulse_countdown_loop(n, trig) = - ~ cond(n)*trig
with {
cond(n, x) = x * (x >= n);
};
//-----------------------`(ba.)resetCtr`------------------------
// Function that lets through the mth impulse out of
// each consecutive group of `n` impulses.
//
// #### Usage
//
// ```
// _ : resetCtr(n,m) : _
// ```
//
// Where:
//
// * `n`: the total number of impulses being split
// * `m`: index of impulse to allow to be output
//---------------------------------------------------------
declare resetCtr author "Mike Olsen";
resetCtr(n,m) = _ <: (_,pulse_countup_loop(n-1,1)) : (_,(_==m)) : *;
//===============================Array Processing/Pattern Matching========================
//========================================================================================
//---------------------------------`(ba.)count`---------------------------------
// Count the number of elements of list l.
// `count` is a standard Faust function.
//
// #### Usage
//
// ```
// count(l)
// count((10,20,30,40)) -> 4
// ```
//
// Where:
//
// * `l`: list of elements
//-----------------------------------------------------------------------------
count((xs, xxs)) = 1 + count(xxs);
count(xx) = 1;
//-------------------------------`(ba.)take`-----------------------------------
// Take an element from a list.
// `take` is a standard Faust function.
//
// #### Usage
//
// ```
// take(P,l)
// take(3,(10,20,30,40)) -> 30
// ```
//
// Where:
//
// * `P`: position (int, known at compile time, P > 0)
// * `l`: list of elements
//-----------------------------------------------------------------------------
take(1, (xs, xxs)) = xs;
take(1, xs) = xs;
take(N, (xs, xxs)) = take(N-1, xxs);
//----------------------------`(ba.)subseq`--------------------------------
// Extract a part of a list.
//
// #### Usage
//
// ```
// subseq(l, P, N)
// subseq((10,20,30,40,50,60), 1, 3) -> (20,30,40)
// subseq((10,20,30,40,50,60), 4, 1) -> 50
// ```
//
// Where:
//
// * `l`: list
// * `P`: start point (int, known at compile time, 0: begin of list)
// * `N`: number of elements (int, known at compile time)
//
// #### Note:
//
// Faust doesn't have proper lists. Lists are simulated with parallel
// compositions and there is no empty list.
//-----------------------------------------------------------------------------
subseq((head, tail), 0, 1) = head;
subseq((head, tail), 0, N) = head, subseq(tail, 0, N-1);
subseq((head, tail), P, N) = subseq(tail, P-1, N);
subseq(head, 0, N) = head;
//============================Function tabulation=========================================
// The purpose of function tabulation is to speed up the computation of heavy functions over an interval,
// so that the computation at runtime can be faster than directly using the function.
// Two techniques are implemented:
//
// * `tabulate` computes the function in a table and read the points using interpolation. `tabulateNd` is the N dimensions version of `tabulate`
//
// * `tabulate_chebychev` uses Chebyshev polynomial approximation
//
// #### Comparison program example
// ```
///* Both tabulate() and tabulate_chebychev() create rdtable of size = 200, both use */
///* cubic polynomials, so this comparison is more or less fair. */
// process = line(50000, r0, r1) <: FX-tb,FX-ch : par(i, 2, maxerr)
// with {
// C = 0;
// FX = sin;
// NX = 50;
// CD = 3;
// r0 = 0;
// r1 = ma.PI;
// tb(x) = ba.tabulate(C, FX, NX*(CD+1), r0, r1, x).cub;
// ch(x) = ba.tabulate_chebychev(C, FX, NX, CD, r0, r1, x);
// maxerr = abs : max ~ _;
// line(n, x0, x1) = x0 + (ba.time%n)/n * (x1-x0);
// };
// ```
//-------`(ba.)tabulate`----------
// Tabulate a 1D function over the range [r0, r1] for access via nearest-value, linear, cubic interpolation.
// In other words, the uniformly tabulated function can be evaluated using interpolation of order 0 (none), 1 (linear), or 3 (cubic).
//
// #### Usage
//
// ```
// tabulate(C, FX, S, r0, r1, x).(val|lin|cub) : _
// ```
//
// * `C`: whether to dynamically force the `x` value to the range [r0, r1]: 1 forces the check, 0 deactivates it (constant numerical expression)
// * `FX`: unary function Y=F(X) with one output (scalar function of one variable)
// * `S`: size of the table in samples (constant numerical expression)
// * `r0`: minimum value of argument x
// * `r1`: maximum value of argument x
//
// ```
// tabulate(C, FX, S, r0, r1, x).val uses the value in the table closest to x
// ```
//
// ```
// tabulate(C, FX, S, r0, r1, x).lin evaluates at x using linear interpolation between the closest stored values
// ```
//
// ```
// tabulate(C, FX, S, r0, r1, x).cub evaluates at x using cubic interpolation between the closest stored values
// ```
//
// #### Example test program
//
// ```
// midikey2hz(mk) = ba.tabulate(1, ba.midikey2hz, 512, 0, 127, mk).lin;
// process = midikey2hz(ba.time), ba.midikey2hz(ba.time);
// ```
//
//--------------------------------------------
tabulate(C, FX, S, r0, r1, x) = environment {
// Maximum index to access
mid = S-1;
// Create the table
wf = r0 + float(rid(ba.time, 1))*(r1-r0)/float(mid) : FX;
// Prepare the 'float' table read index
id = (x-r0)/(r1-r0)*mid;
// Limit the table read index in [0, mid] if C = 1
rid(x, 0) = x;
rid(x, 1) = max(0, min(x, mid));
// Tabulate an unary 'FX' function on a range [r0, r1]
val = y0 with { y0 = rdtable(S, wf, rid(int(id+0.5), C)); };
// Tabulate an unary 'FX' function over the range [r0, r1] with linear interpolation
lin = it.interpolate_linear(d,y0,y1)
with {
x0 = int(id);
x1 = x0+1;
d = id-x0;
y0 = rdtable(S, wf, rid(x0, C));
y1 = rdtable(S, wf, rid(x1, C));
};
// Tabulate an unary 'FX' function over the range [r0, r1] with cubic interpolation
cub = it.interpolate_cubic(d,y0,y1,y2,y3)
with {
x0 = x1-1;
x1 = int(id);
x2 = x1+1;
x3 = x2+1;
d = id-x1;
y0 = rdtable(S, wf, rid(x0, C));
y1 = rdtable(S, wf, rid(x1, C));
y2 = rdtable(S, wf, rid(x2, C));
y3 = rdtable(S, wf, rid(x3, C));
};
};
declare tabulate author "Stephane Letz";
//-------`(ba.)tabulate_chebychev`----------
// Tabulate a 1D function over the range [r0, r1] for access via Chebyshev polynomial approximation.
// In contrast to `(ba.)tabulate`, which interpolates only between tabulated samples, `(ba.)tabulate_chebychev`
// stores coefficients of Chebyshev polynomials that are evaluated to provide better approximations in many cases.
// Two new arguments controlling this are NX, the number of segments into which [r0, r1] is divided, and CD,
// the maximum Chebyshev polynomial degree to use for each segment. A `rdtable` of size NX*(CD+1) is internally used.
//
// Note that processing `r1` the last point in the interval is not safe. So either be sure the input stays in [r0, r1[
// or use `C = 1`.
//
// #### Usage
//
// ```
// _ : tabulate_chebychev(C, FX, NX, CD, r0, r1) : _
// ```
//
// * `C`: whether to dynamically force the value to the range [r0, r1]: 1 forces the check, 0 deactivates it (constant numerical expression)
// * `FX`: unary function Y=F(X) with one output (scalar function of one variable)
// * `NX`: number of segments for uniformly partitioning [r0, r1] (constant numerical expression)
// * `CD`: maximum polynomial degree for each Chebyshev polynomial (constant numerical expression)
// * `r0`: minimum value of argument x
// * `r1`: maximum value of argument x
//
// #### Example test program
//
// ```
// midikey2hz_chebychev(mk) = ba.tabulate_chebychev(1, ba.midikey2hz, 100, 4, 0, 127, mk);
// process = midikey2hz_chebychev(ba.time), ba.midikey2hz(ba.time);
// ```
//
//--------------------------------------------
tabulate_chebychev(C, FX, NX, CD, r0, r1, x) = y with {
ck(0) = _;
ck(1) = max(0) : min(NX-1);
// number of chebyshev coefficients
NC = CD + 1;
// length of the segments
DX = (r1 - r0) / NX;
// number of segment 'x' falls in
nx = (x - r0) / DX : int : ck(C);
// center of n's segment
xc(n) = r0 + DX * (n + 1/2);
// so ch(0) .. ch(NC) are the coeffs we use for approximation
// on nx's segment
ch(i) = chtab(NC * nx + i);
// map the input in segment [nx*DX, (nx+1)*DX] to [-1,1]
y = (x - xc(nx)) * 2/DX <: sum(i, NC, ch(i) * ma.chebychev(i));
// map [-1,1] to the segment [nx*DX, (nx+1)*DX] so mapfx(nx)
// is simply the "renormalized" FX defined on [-1,1]
mapfx(nx, x) = FX(xc(nx) + DX/2 * x);
// calculate the nc's chebyshev coefficient we use on nx's segment
gench(nx, nc) = (1+(nc!=0))/NC * sum(k,NC,
mapfx(nx, cos(ma.PI*(k+1/2)/NC)) * cos(ma.PI*nc*(k+1/2)/NC));
// record gench(nx, nc) in rdtable() to avoid the run-time calculations
chtab = rdtable(NX*NC, (ba.time <: int(/(NC)), %(NC) : gench));
};
declare tabulate_chebychev author "Oleg Nesterov";
declare tabulate_chebychev copyright "Copyright (C) 2022 Oleg Nesterov <[email protected]>";
declare tabulate_chebychev license "MIT-style STK-4.3 license";
//-------`(ba.)tabulateNd`----------
// Tabulate an nD function for access via nearest-value or linear or cubic interpolation. In other words, the tabulated function can be evaluated using interpolation of order 0 (none), 1 (linear), or 3 (cubic).
//
// The table size and parameter range of each dimension can and must be separately specified. You can use it anywhere you have an expensive function with multiple parameters with known ranges. You could use it to build a wavetable synth, for example.
//
// The number of dimensions is deduced from the number of parameters you give, see below.
//
// Note that processing the last point in each interval is not safe. So either be sure the inputs stay in their respective ranges, or use `C = 1`. Similarly for the first point when doing cubic interpolation.
//
// #### Usage
//
// ```
// tabulateNd(C, function, (parameters) ).(val|lin|cub) : _
// ```
//
// * `C`: whether to dynamically force the parameter values for each dimension to the ranges specified in parameters: 1 forces the check, 0 deactivates it (constant numerical expression)
// * `function`: the function we want to tabulate. Can have any number of inputs, but needs to have just one output.
// * `(parameters)`: sizes, ranges and read values. Note: these need to be in brackets, to make them one entity.
//
// If N is the number of dimensions, we need:
//
// * N times `S`: number of values to store for this dimension (constant numerical expression)