File: wdmodels.lib

package info (click to toggle)
faust 2.79.3%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 397,496 kB
  • sloc: cpp: 278,433; ansic: 116,164; javascript: 18,529; vhdl: 14,052; sh: 13,884; java: 5,900; objc: 3,852; python: 3,222; makefile: 2,655; cs: 1,672; lisp: 1,146; ruby: 954; yacc: 586; xml: 471; lex: 247; awk: 110; tcl: 26
file content (2276 lines) | stat: -rw-r--r-- 89,953 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
//#################################### wdmodels.lib ##############################################################################
// A library of basic adaptors and methods to help construct Wave Digital Filter models in Faust. Its official prefix is `wd`.

// ## Library Readme

// This library is intended for use for creating Wave Digital (WD) based models of audio circuitry for real-time audio processing within the Faust programming language. The goal is to provide a framework to create real-time virtual-analog audio effects and synthesizers using WD models without the use of C++. Furthermore, we seek to provide access to the technique of WD modeling to those without extensive knowledge of advanced digital signal processing techniques. Finally, we hope to provide a library which can integrate with all aspects of Faust, thus creating a platform for virtual circuit bending. 
// The library itself is written in Faust to maintain portability. 
//
// This library is heavily based on Kurt Werner's Dissertation, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters." I have tried to maintain consistent notation between the adaptors appearing within thesis and my adaptor code. The majority of the adaptors found in chapter 1 and chapter 3 are currently supported. 
//
// For inquires about use of this library in a commercial product, please contact dirk [dot] roosenburg [dot] 30 [at] gmail [dot] com.
// This documentation is taken directly from the [readme](https://github.com/droosenb/faust-wdf-library). Please refer to it for a more updated version. 
//
// Many of the more in depth comments within the library include jargon. I plan to create videos detailing the theory of WD models.
// For now I recommend Kurt Werner's PhD, [Virtual analog modeling of Audio circuitry using Wave Digital Filters](https://searchworks.stanford.edu/view/11891203).   
// I have tried to maintain consistent syntax and notation to the thesis. 
// This library currently includes the majority of the adaptors covered in chapter 1 and some from chapter 3. 
//
//
// ## Using this Library
//
// Use of this library expects some level of familiarity with WDF techniques, especially simplification and decomposition of electronic circuits into WDF connection trees. I plan to create video to cover both these techniques and use of the library. 
//
// ### Quick Start
//
// To get a quick overview of the library, start with the `secondOrderFilters.dsp` code found in [examples](https://github.com/droosenb/faust-wdf-library/tree/main/examples). 
// Note that the `wdmodels.lib` library is now embedded in the [online Faust IDE](https://faustide.grame.fr/).
//
// ### A Simple RC Filter Model
//
// Creating a model using this library consists fo three steps. First, declare a set of components. 
// Second, model the relationship between them using a tree. Finally, build the tree using the libraries build functions.  
//
// First, a set of components is declared using adaptors from the library. 
// This list of components is created based on analysis of the circuit using WDF techniques, 
// though generally each circuit element (resistor, capacitor, diode, etc.) can be expected to appear 
// within the component set. For example, first order RC lowpass filter would require an unadapted voltage source, 
// a 47k resistor, and a 10nF capacitor which outputs the voltage across itself. These can be declared with: 
//
// ```
// vs1(i) = wd.u_voltage(i, no.noise);
// r1(i) = wd.resistor(i, 47*10^3);
// c1(i) = wd.capacitor_Vout(i, 10*10^-9);
// ```
//
// Note that the first argument, i, is left un-parametrized. Components must be declared in this form, as the build algorithm expects to receive adaptors which have exactly one parameter. 
//
// Also note that we have chosen to declare a white noise function as the input to our voltage source. 
// We could potentially declare this as a direct input to our model, but to do so is more complicated 
// process which cannot be covered within this tutorial. For information on how to do this see 
// [Declaring Model Parameters as Inputs](#declaring-model-parameters-as-inputs) or see various implementations 
// in [examples](https://github.com/droosenb/faust-wdf-library/tree/main/examples).
//
// Second, the declared components and interconnection/structural adaptors (i.e. series, parallel, etc) are arranged 
// into the connection tree which is produced from performing WD analysis on the modeled circuit. 
// For example, to produce our first order RC lowpass circuit model, the following tree is declared: 
//
// `tree_lowpass = vs1 : wd.series : (r1, c1);`
//
// For more information on how to represent trees in Faust, see [Trees in Faust](#trees-in-faust). 
//
// Finally, the tree is built using the the `buildtree` function. To build and compute our first order 
// RC lowpass circuit model, we use:
//
// `process = wd.buildtree(tree_lowpass);`
//
// More information about build functions, see [Model Building Functions](#model-building-functions). 
//
// ### Building a Model
//
// After creating a connection tree which consists of WD adaptors, the connection tree must be passed 
// to a build function in order to build the model.
//
// ##### Automatic model building 
//
// `buildtree(connection_tree)`
//
// The simplest build function for use with basic models. This automatically implements `buildup`, `builddown`, 
// and `buildout` to create a working model. However, it gives minimum control to the user and cannot 
// currently be used on trees which have parameters declared as inputs.
//
// ##### Manual model building
//
// Wave Digital Filters are an explicit state-space model, meaning they use a previous system state 
// in order to calculate the current output. This is achieved in Faust by using a single global feedback operator.
// The models feed-forward terms are generated using `builddown` and the models feedback terms are generated 
// using `buildup`. Thus, the most common model implementation (the method used by `buildtree`) is:
//
// `builddown(connection_tree)~buildup(connection_tree) : buildout(connection_tree)`
//
// Since the `~` operator in Faust will leave feedback terms hanging as outputs, `buildout` is a function provided for convenience. 
// It automatically truncates the hanging outputs by identifying leaf components which have an intended output 
// and generating an output matrix.
//
// Building the model manually allows for greater user control and is often very helpful in testing. 
// Also provided for testing are the `getres` and `parres` functions, which can be used to determine 
// the upward-facing port resistance of an element. 
//
// ### Declaring Model Parameters as Inputs
//
// When possible, parameters of components should be declared explicitly, meaning they are dependent on a function with no inputs. 
// This might be something as simple as integer(declaring a static component), a function dependent on a UI input (declaring a component with variable value), 
// or even a time-dependent function like an oscillator (declaring an audio input or circuit bending). 
//
// However, it is often necessary to declare parameters as input. To achieve this there are two possible methods. 
// The first and recommended option is to create a separate model function and declare parameters which will later 
// be implemented as inputs. This allows inputs to be explicitly declared as component parameters. 
// For example, one might use:
//
// ```
// model(in1) = buildtree(tree)
// with {
//    ...
//    vin(i) = wd.u_voltage(i, in1);
//    ...
//    tree = vin : ...; 
// };
// ```
//
// In order to simulate an audio input to the circuit. 
//
// Note that the tree and components must be declared inside a `with {...}` statement, or the model's parameters will not be accessible. 
//
// ##### The Empty Signal Operator
//
// The Empty signal operator, `_` should NEVER be used to declare a parameter as in input in a wave-digital model. 
//
// Using it will result on breaking the internal routing of the model and thus breaks the model. 
// Instead, use explicit declaration as shown directly above. 
//
// ### Trees in Faust
//
// Since WD models use connection trees to represent relationships of elements, a comprehensive way to represent trees is critical.
//  As there is no current convention for creating trees in Faust, I've developed a method using the existing series and parallel/list 
// methods in Faust.
//
// The series operator ` : ` is used to separate parent and child elements. For example the tree:
//
// ```
//    A
//    |
//    B
// ```
//
// is represented by `A : B` in Faust. 
//
// To denote a parent element with multiple child elements, simply use a list `(a1, a2, ... an)` of children connected to a single parent. `
// For example the tree:
//
// ```
//    A
//   / \
//  B   C
//
// ```
// is represented by:
//
// `A : (B, C)`
//
// Finally, for a tree with many levels, simply break the tree into subtrees following the above rules and connect 
// the subtree as if it was an individual node. For example the tree:
//
// ```
//       A
//      / \
//     B   C
//    /   / \
//   X   Y   Z
// ```
//
// can be represented by:
//
// ```
// B_sub = B : X; //B subtree
// C_sub = C : (Y, Z); //C subtree
// tree = A : (B_sub, C_sub); //full tree
// ```
//
// or more simply, using parentheses: 
//
// `A : ((B : X), (C : (Y, Z)))`

// ### How Adaptors are Structured

// In wave digital filters, adaptors can be described by the form `b = Sa` where `b` is a vector of output waves `b = (b0, b1, b2, ... bn)`, `a` is a vector of input waves`a = (a0, a1, a2, ... an)`, and `S` is an n x n scattering matrix. 
// `S` is dependent on `R`, a list of port resistances `(R0, R1, R2, ... Rn)`. 
//
// The output wave vector `b` can be divided into downward-going and upward-going waves 
// (downward-going waves travel down the connection tree, upward-going waves travel up). 
// For adapted adaptors, with the zeroth port being the upward-facing port, the downward-going wave vector is `(b1, b2, ... bn)` and the upward-going wave vector is `(b0)`. 
// For unadapted adaptors, there are no upward-going waves, so the downward-going wave vector is simply `b = (b0, b1, b2, ... bn)`. 
//
// In order for adaptors to be interpretable by the compiler, they must be structured in a specific way. 
// Each adaptor is divided into three cases by their first parameter. This parameter, while accessible by the user, should only be set by the compiler/builder.
//
// All other parameters are value declarations (for components), inputs (for voltage or current ins), or parameter controls (for potentiometers/variable capacitors/variable inductors).
//
// ##### First case - downward going waves
//
// `(0, params) => downward-going(R1, ... Rn, a0, a1, ... an)` 
// outputs: `(b1, b2, ... bn)`
// this function takes any number of port resistances, the downward going wave, and any number of upward going waves as inputs. 
// These values/waves are used to calculate the downward going waves coming from this adaptor.
//
// ##### Second case 
//
// `(1, params) => upward-going(R1, ... Rn, a1, ... an)`
// outputs : `(b0)`
// this function takes any number of port resistances and any number of upward going waves as inputs.
// These values/waves are used to calculate the upward going wave coming from this adaptor.
//
// ##### Third case  
//
// `(2, params) => port-resistance(R1, ... Rn)` 
// outputs: `(R0)`
// this function takes any number of port resistances as inputs.
// These values are used to calculate the upward going port resistance of the element.
//
// ##### Unadapted Adaptors
//
// Unadapted adaptor's names will always begin `u_`
// An unadapted adaptor MUST be used as the root of the WD connection tree.
// Unadapted adaptors can ONLY be used as a root of the WD connection tree. 
// While unadapted adaptors contain all three cases, the second and third are purely structural. 
// Only the first case should contain computational information. 
//
// ### How the Build Functions Work
//
// Expect this section to be added soon! It's currently in progress.
//
// ### Acknowledgements
//
// Many thanks to Kurt Werner for helping me to understand wave digital filter models. Without his publications and consultations, the library would not exist. 
// Thanks also to my advisors, Rob Owen and Eli Stine whose input was critical to the development of the library.
// Finally, thanks to Romain Michon, Stephane Letz, and the Faust Slack for contributing to testing, development, and inspiration when creating the library. 
//
// #### References
// * <https://github.com/grame-cncm/faustlibraries/blob/master/wdmodels.lib>
//################################################################################################################################

ba = library("basics.lib");
ro = library("routes.lib");
ma = library("maths.lib");
si = library("signals.lib");

declare name "Faust Wave Digital Model Library";
declare version "1.2.1";


//=============================Algebraic One Port Adaptors=================================
//=========================================================================================

//----------------------`(wd.)resistor`--------------------------
// Adapted Resistor.
//
// A basic node implementing a resistor for use within Wave Digital Filter connection trees.
//
// It should be used as a leaf/terminating element of the connection tree.
//
// #### Usage
//
// ```
// r1(i) = resistor(i, R);
// buildtree( A : r1 );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared.
// * `R` : Resistance/Impedance of the resistor being modeled in Ohms. 
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.1
//----------------------------------------------------------
declare resistor author "Dirk Roosenburg";
declare resistor copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare resistor license "MIT-style STK-4.3 license";
resistor = 
case{
    (0, R) => !, 0; 
    (1, R) => _; 
    (2, R) => R0 
    with{
        R0 = R; 
    };
};


//----------------------`(wd.)resistor_Vout`--------------------------
// Adapted Resistor + voltage Out.
//
// A basic adaptor implementing a resistor for use within Wave Digital Filter connection trees.
//
// It should be used as a leaf/terminating element of the connection tree.
// The resistor will also pass the voltage across itself as an output of the model.
//
// #### Usage
//
// ```
// rout(i) = resistor_Vout(i, R);
// buildtree( A : rout ) : _
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared.
// * `R` : Resistance/Impedance of the resistor being modeled in Ohms. 
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.1
//----------------------------------------------------------
declare resistor_Vout author "Dirk Roosenburg";
declare resistor_Vout copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare resistor_Vout license "MIT-style STK-4.3 license";
resistor_Vout = 
case{
    (0, R) => 0, _*.5; 
    (1, R) => _, !; 
    (2, R) => R0 
    with{
        R0 = R; 
    };
}with{
    rho = 1; 
};


//----------------------`(wd.)resistor_Iout`--------------------------
// Resistor + current Out.
//
// A basic adaptor implementing a resistor for use within Wave Digital Filter connection trees.
//
// It should be used as a leaf/terminating element of the connection tree.
// The resistor will also pass the current through itself as an output of the model.
//
// #### Usage
//
// ```
// rout(i) = resistor_Iout(i, R);
// buildtree( A : rout ) : _
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared.
// * `R` : Resistance/Impedance of the resistor being modeled in Ohms. 
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.1
//----------------------------------------------------------
declare resistor_Iout author "Dirk Roosenburg";
declare resistor_Iout copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare resistor_Iout license "MIT-style STK-4.3 license";
resistor_Iout = 
case{
    (0, R) => 0, _*.5/R; 
    (1, R) => _, !; 
    (2, R) => R0 
    with{
        R0 = R; 
    };
};


//----------------------`(wd.)u_voltage`--------------------------
// Unadapted Ideal Voltage Source.
//
// An adaptor implementing an ideal voltage source within Wave Digital Filter connection trees.
//
// It should be used as the root/top element of the connection tree.
// Can be used for either DC (constant) or AC (signal) voltage sources.
//
// #### Usage
//
// ```
// v1(i) = u_Voltage(i, ein);
// buildtree( v1 : B );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared.
// * `ein` : Voltage/Potential across ideal voltage source in Volts
//
// Note: only usable as the root of a tree.
// The adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.2
//----------------------------------------------------------
declare u_voltage author "Dirk Roosenburg";
declare u_voltage copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_voltage license "MIT-style STK-4.3 license";
u_voltage = 
case{
    (0 , ein) => b0
    with{
        b0(R0, a0) = 2*R0^(rho-1)*ein -a0;
    };
    (1, ein) => !, !; 
    (2, ein) => 0; 
}with{
    rho = 1; 
};


//----------------------`(wd.)u_current`--------------------------
// Unadapted Ideal Current Source.
//
// An unadapted adaptor implementing an ideal current source within Wave Digital Filter connection trees.
//
// It should be used as the root/top element of the connection tree.
// Can be used for either DC (constant) or AC (signal) current sources.
//
// #### Usage
//
// ```
// i1(i) = u_current(i, jin);
// buildtree( i1 : B );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared.
// * `jin` : Current through the ideal current source in Amps
//
// Note: only usable as the root of a tree.
// The adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.3
//----------------------------------------------------------
declare u_current author "Dirk Roosenburg";
declare u_current copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_current license "MIT-style STK-4.3 license";
u_current = 
case{
    (0 , jin) => b0
    with{
        b0(R0, a0) = 2*R0^(rho)*jin + a0;
    };
    (1, jin) => !, !; 
    (2, jin) => 0; 
}with{
    rho = 1; 
};

//----------------------`(wd.)resVoltage`--------------------------
// Adapted Resistive Voltage Source.
//
// An adaptor implementing a resistive voltage source within Wave Digital Filter connection trees.
//
// It should be used as a leaf/terminating element of the connection tree.
// It is comprised of an ideal voltage source in series with a resistor.
// Can be used for either DC (constant) or AC (signal) voltage sources.
//
// #### Usage
//
// ```
// v1(i) = resVoltage(i, R, ein);
// buildtree( A : v1 );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `R` : Resistance/Impedance of the series resistor in Ohms
// * `ein` : Voltage/Potential of the ideal voltage source in Volts
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.4
//----------------------------------------------------------
declare resVoltage author "Dirk Roosenburg";
declare resVoltage copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare resVoltage license "MIT-style STK-4.3 license";
resVoltage = 
case{
    (0, R, ein) => !, R^(1-rho)*ein;
    (1, R, ein) => _; 
    (2, R, ein) => R0
    with {
        R0 = R; 
    };
}with{
    rho = 1; 
}; 

//----------------------`(wd.)resVoltage_Vout`--------------------------
// Adapted Resistive Voltage Source + voltage output.
//
// An adaptor implementing an adapted resistive voltage source within Wave Digital Filter connection trees.
//
// It should be used as a leaf/terminating element of the connection tree.
// It is comprised of an ideal voltage source in series with a resistor.
// Can be used for either DC (constant) or AC (signal) voltage sources.
// The resistive voltage source will also pass the voltage across it as an output of the model.
//
// #### Usage
//
// ```
// vout(i) = resVoltage_Vout(i, R, ein);
// buildtree( A : vout ) : _
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `R` : Resistance/Impedance of the series resistor in Ohms
// * `ein` : Voltage/Potential across ideal voltage source in Volts
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.4
//----------------------------------------------------------
declare resVoltage_Vout author "Dirk Roosenburg";
declare resVoltage_Vout copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare resVoltage_Vout license "MIT-style STK-4.3 license";
resVoltage_Vout = 
case{
    (0, R, ein) => R^(1-rho)*ein, _*.5 + R^(1-rho)*ein*.5;
    (1, R, ein) => _, !; 
    (2, R, ein) => R0
    with {
        R0 = R; 
    };
}with{
    rho = 1; 
}; 

//----------------------`(wd.)u_resVoltage`--------------------------
// Unadapted Resistive Voltage Source.
//
// An unadapted adaptor implementing a resistive voltage source within Wave Digital Filter connection trees.
//
// It should be used as the root/top element of the connection tree.
// It is comprised of an ideal voltage source in series with a resistor.
// Can be used for either DC (constant) or AC (signal) voltage sources.
//
// #### Usage
//
// ```
// v1(i) = u_resVoltage(i, R, ein);
// buildtree( v1 : B );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `R` : Resistance/Impedance of the series resistor in Ohms
// * `ein` : Voltage/Potential across ideal voltage source in Volts
//
// Note: only usable as the root of a tree.
// The adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.4
//----------------------------------------------------------
declare u_resVoltage author "Dirk Roosenburg";
declare u_resVoltage copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_resVoltage license "MIT-style STK-4.3 license";
u_resVoltage =
case {
    (0, R, ein) => b0
    with{
        b0(R0, a0) = a0*(R - R0)/(R+R0) + ein*(2*R0^rho)/(R + R0);
    };
    (1, R, ein) => !, !; 
    (2, R, ein) => 0; 

}with{
    rho = 1; 
};


//----------------------`(wd.)resCurrent`--------------------------
// Adapted Resistive Current Source.
//
// An adaptor implementing a resistive current source within Wave Digital Filter connection trees.
//
// It should be used as a leaf/terminating element of the connection tree.
// It is comprised of an ideal current source in parallel with a resistor.
// Can be used for either DC (constant) or AC (signal) current sources.
//
// #### Usage
//
// ```
// i1(i) = resCurrent(i, R, jin);
// buildtree( A : i1 );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared.
// * `R` : Resistance/Impedance of the parallel resistor in Ohms
// * `jin` : Current through the ideal current source in Amps
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.5
//----------------------------------------------------------
declare resCurrent author "Dirk Roosenburg";
declare resCurrent copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare resCurrent license "MIT-style STK-4.3 license";
resCurrent =
case {
    (0, R, jin) => !, R^(rho)*jin;
    (1, R, jin) => _; 
    (2, R, jin) => R0
    with {
        R0 = R; 
    };
}with{
    rho = 1; //assume voltage waves
}; 

//----------------------`(wd.)u_resCurrent`--------------------------
// Unadapted Resistive Current Source.
//
// An unadapted adaptor implementing a resistive current source within Wave Digital Filter connection trees.
//
// It should be used as the root/top element of the connection tree.
// It is comprised of an ideal current source in parallel with a resistor.
// Can be used for either DC (constant) or AC (signal) current sources.
//
// #### Usage
//
// ```
// i1(i) = u_resCurrent(i, R, jin);
// buildtree( i1 : B );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared.
// * `R` : Resistance/Impedance of the series resistor in Ohms
// * `jin` : Current through the ideal current source in Amps
//
// Note: only usable as the root of a tree.
// The adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.5
//----------------------------------------------------------
declare u_resCurrent author "Dirk Roosenburg";
declare u_resCurrent copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_resCurrent license "MIT-style STK-4.3 license";
u_resCurrent =
case {
    (0, R, jin) => b0
    with{
        b0(R0, a0) = a0*(R - R0)/(R + R0) + jin*(2*R*R0^rho)/(R + R0);
    };
    (1, R, jin) => !, !; 
    (2, R, jin) => 0; 

}with{
    rho = 1; //assume voltage waves
};

//TODO
//add short circuit (1.2.6), add open circuit (1.2.7)

//----------------------`(wd.)u_switch`--------------------------
// Unadapted Ideal Switch.
//
// An unadapted adaptor implementing an ideal switch for Wave Digital Filter connection trees.
//
// It should be used as the root/top element of the connection tree
//
// #### Usage
//
// ```
// s1(i) = u_resCurrent(i, lambda);
// buildtree( s1 : B );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared.
// * `lambda` : switch state control. -1 for closed switch, 1 for open switch.
//
// Note: only usable as the root of a tree.
// The adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.2.8
//----------------------------------------------------------
declare u_switch author "Dirk Roosenburg";
declare u_switch copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_switch license "MIT-style STK-4.3 license";
u_switch = 
case {
    (0, lambda) => b0
    with{
        b0(R0, a0) = a0*lambda; 
    };
    (1, lambda) => !, !; 
    (2, lambda) => 0; 
};

//=============================Reactive One Port Adaptors=================================
//========================================================================================
//TODO - add mobius transform and alpha transform digitizations

//----------------------`(wd.)capacitor`--------------------------
// Adapted Capacitor.
//
// A basic adaptor implementing a capacitor for use within Wave Digital Filter connection trees.
//
// It should be used as a leaf/terminating element of the connection tree.
// This capacitor model was digitized using the bi-linear transform.
//
// #### Usage
//
// ```
// c1(i) = capacitor(i, R);
// buildtree( A : c1 ) : _
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared.
// * `R` : Capacitance/Impedance of the capacitor being modeled in Farads. 
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.3.1
//----------------------------------------------------------
declare capacitor author "Dirk Roosenburg";
declare capacitor copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare capacitor license "MIT-style STK-4.3 license";
capacitor =
case{
    (0, R) => _*1; 
    (1, R) => _; 
    (2, R) => R0
    with {
        R0 = t/(2*R); 
    };
}with{
    t = 1/ma.SR; //sampling interval
};

//----------------------`(wd.)capacitor_Vout`--------------------------
// Adapted Capacitor + voltage out.
//
// A basic adaptor implementing a capacitor for use within Wave Digital Filter connection trees.
//
// It should be used as a leaf/terminating element of the connection tree.
// The capacitor will also pass the voltage across itself as an output of the model.
// This capacitor model was digitized using the bi-linear transform.
//
// #### Usage
//
// ```
// cout(i) = capacitor_Vout(i, R);
// buildtree( A : cout ) : _
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `R` : Capacitance/Impedence of the capacitor being modeled in Farads
//
// Note: the adaptor must be declared as a seperate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.3.1
//----------------------------------------------------------
declare capacitor_Vout author "Dirk Roosenburg";
declare capacitor_Vout copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare capacitor_Vout license "MIT-style STK-4.3 license";
capacitor_Vout = 
case{
    (0, R) => b0
    with{
        b0(a1) = a1*1, a1*.5 + (a1')*.5; 
    };
    (1, R) => _, !; 
    (2, R) => R0
    with {
        R0 = t/(2*R); 
    };
}with{
    t = 1/ma.SR; //sampling interval
};

//----------------------`(wd.)inductor`--------------------------
// Unadapted Inductor.
//
// A basic adaptor implementing an inductor for use within Wave Digital Filter connection trees.
//
// It should be used as a leaf/terminating element of the connection tree.
// This inductor model was digitized using the bi-linear transform.
//
// #### Usage
//
// ```
// l1(i) = inductor(i, R);
// buildtree( A : l1 );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `R` : Inductance/Impedance of the inductor being modeled in Henries
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.3.2
//----------------------------------------------------------
declare inductor author "Dirk Roosenburg";
declare inductor copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare inductor license "MIT-style STK-4.3 license";
inductor =
case{
    (0, R) => _*(-1); 
    (1, R) => _; 
    (2, R) => R0
    with {
        R0 = (2*R)/t; 
    };
}with{
    t = 1/ma.SR; //sampling interval
};

//----------------------`(wd.)inductor_Vout`--------------------------
// Unadapted Inductor + Voltage out.
//
// A basic adaptor implementing an inductor for use within Wave Digital Filter connection trees.
//
// It should be used as a leaf/terminating element of the connection tree.
// The inductor will also pass the voltage across itself as an output of the model.
// This inductor model was digitized using the bi-linear transform.
//
// #### Usage
//
// ```
// lout(i) = inductor_Vout(i, R);
// buildtree( A : lout ) : _
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `R` : Inductance/Impedance of the inductor being modeled in Henries
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.3.2
//----------------------------------------------------------
declare inductor_Vout author "Dirk Roosenburg";
declare inductor_Vout copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare inductor_Vout license "MIT-style STK-4.3 license";
inductor_Vout = 
case{
    (0, R) => b0
    with{
        b0(a1) = a1*(-1), a1*.5 - (a1')*.5; 
    };
    (1, R) => _, !; 
    (2, R) => R0
    with {
        R0 = (2*R)/t; 
    };
}with{
    t = 1/ma.SR; //sampling interval
};

//===============================Nonlinear One Port Adaptors==============================
//========================================================================================

//----------------------`(wd.)u_idealDiode`--------------------------
// Unadapted Ideal Diode.
//
// An unadapted adaptor implementing an ideal diode for Wave Digital Filter connection trees.
//
// It should be used as the root/top element of the connection tree.
//
// #### Usage
//
// ```
// buildtree( u_idealDiode : B );
// ```
//
// Note: only usable as the root of a tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 3.2.3
//----------------------------------------------------------
declare u_idealDiode author "Dirk Roosenburg";
declare u_idealDiode copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_idealDiode license "MIT-style STK-4.3 license";
u_idealDiode =
case{
    (0) => b1
    with{
        b1(R1, a0) = a0 : abs : *(-1);
    };
    (1) => !, !; 
    (2) => 0; 
};

//----------------------`(wd.)u_chua`--------------------------
// Unadapted Chua Diode.
//
// An adaptor implementing the chua diode / non-linear resistor within Wave Digital Filter connection trees.
//
// It should be used as the root/top element of the connection tree.
//
// #### Usage
//
// ```
// chua1(i) = u_chua(i, G1, G2, V0);
// buildtree( chua1 : B );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `G1` : resistance parameter 1 of the chua diode
// * `G2` : resistance parameter 2 of the chua diode
// * `V0` : voltage parameter of the chua diode
//
// Note: only usable as the root of a tree.
// The adaptor must be declared as a separate function before integration into the connection tree.
// Correct implementation is shown above.
//
// #### Reference
//
// Meerkotter and Scholz, "Digital Simulation of Nonlinear Circuits by Wave Digital Filter Principles"
//----------------------------------------------------------
declare u_chua author "Dirk Roosenburg";
declare u_chua copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_chua license "MIT-style STK-4.3 license";
u_chua = 
case{
    (0, G1, G2, V0) => b1
    with{
        b1(R1, a0) = g_1*a0 + 1/2*(g_2 - g_1)*(((a0 + a_0) : abs) - ((a0 - a_0): abs))
        with{
            g_1 = (1-G1*R1)/(1+G1*R1);
            g_2 = (1-G2*R1)/(1+G2*R1);
            a_0 = V0*(1+G2*R1);
        };
    };
    (1, G1, G2, V0) => !, !; 
    (2, G1, G2, V0) => 0; 
};


//----------------------`(wd.)lambert`--------------------------
// An implementation of the lambert function.
// It uses Halley's method of iteration to approximate the output.
// Included in the WD library for use in non-linear diode models.
// Adapted from K M Brigg's c++ lambert function approximation.
//
// #### Usage
//
// ```
// lambert(n, itr) : _
// ```
//
// Where:
// * `n`: value at which the lambert function will be evaluated
// * `itr`: number of iterations before output
//
//----------------------------------------------------------
declare lambert author "Dirk Roosenburg";
declare lambert copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare lambert license "MIT-style STK-4.3 license";
lambert(z, itr) = ba.if((z<(-em1+.0001)), less_approx, greater_approx)
with{
    less_approx = -1.0
     +2.331643981597124203363536062168*r
     -1.812187885639363490240191647568*q
     +1.936631114492359755363277457668*r*q
     -2.353551201881614516821543561516*q2
    with{
        q = z+em1;
        r = sqrt(q);
        q2 = q*q; 
    };
    eps=4.0e-16; 
    em1=0.3678794411714423215955237701614608;
    greater_approx = z : init : seq(i, itr, approx)
    with{
        init(w) = ba.if((z<1), init1, init2)
        with{
            init1 = -1.0+p*(1.0+p*(-0.333333333333333333333+p*0.152777777777777777777777))
            with{
                p = sqrt(2.0*(2.7182818284590452353602874713526625*z+1.0));
            };
            init2 = log(abs(z));
        };
        approx(w) = w-t
        with{
            e = exp(w);
            t = (w*e-z)/(e*p-.5*(p+1.0)*(w*e-z)/p);
            p = w+1; 
        };
    };
};


//----------------------`(wd.)u_diodePair`--------------------------
// Unadapted pair of diodes facing in opposite directions.
//
// An unadapted adaptor implementing two antiparallel diodes for Wave Digital Filter connection trees.
// The behavior is approximated using Schottkey's ideal diode law.
//
// #### Usage
//
// ```
// d1(i) = u_diodePair(i, Is, Vt);
// buildtree( d1 : B );
// ```
//
// Where:
// 
// * `i`: index used by model-building functions. Should never be user declared
// * `Is` : saturation current of the diodes
// * `Vt` : thermal resistances of the diodes
//
// Note: only usable as the root of a tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner et al. "An Improved and Generalized Diode Clipper Model for Wave Digital Filters"
//----------------------------------------------------------
declare u_diodePair author "Dirk Roosenburg";
declare u_diodePair copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_diodePair license "MIT-style STK-4.3 license";
u_diodePair = 
case{
    (0, Is, Vt) => b1
    with{
        b1(R1, a1) = a1 + 2*R1*Is - 2*Vt*lambert((R1*Is/Vt*(((a1+R1*Is)/Vt), 3) : exp));
    };
    (1, Is, Vt) => !, !; 
    (2, Is, Vt) => 0; 
};


//----------------------`(wd.)u_diodeSingle`--------------------------
// Unadapted single diode.
//
// An unadapted adaptor implementing a single diode for Wave Digital Filter connection trees.
// The behavior is approximated using Schottkey's ideal diode law.
//
// #### Usage
//
// ```
// d1(i) = u_diodeSingle(i, Is, Vt);
// buildtree( d1 : B );
// ```
//
// Where:
// 
// * `i`: index used by model-building functions. Should never be user declared
// * `Is` : saturation current of the diodes
// * `Vt` : thermal resistances of the diodes
//
// Note: only usable as the root of a tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner et al. "An Improved and Generalized Diode Clipper Model for Wave Digital Filters"
//----------------------------------------------------------
declare u_diodeSingle author "Dirk Roosenburg";
declare u_diodeSingle copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_diodeSingle license "MIT-style STK-4.3 license";
u_diodeSingle = 
case{
    (0, Is, Vt) => b1
    with{
        b1(R1, a1) = ma.signum(a1)*((a1 : abs) + 2*R1*Is - 2*Vt*(lambert((R1*Is/Vt*((((a1 : abs)+R1*Is)/Vt) : exp)),3) + lambert((-R1*Is/Vt*(((-1*(a1 : abs)+R1*Is)/Vt) : exp)),3)));
    };
    (1, Is, Vt) => !, !; 
    (2, Is, Vt) => 0; 
};

//----------------------`(wd.)u_diodeAntiparallel`--------------------------
// Unadapted set of antiparallel diodes with M diodes facing forwards and N diodes facing backwards.
//
// An unadapted adaptor implementing antiparallel diodes for Wave Digital Filter connection trees.
// The behavior is approximated using Schottkey's ideal diode law.
//
// #### Usage
//
// ```
// d1(i) = u_diodeAntiparallel(i, Is, Vt);
// buildtree( d1 : B );
// ```
//
// Where:
// 
// * `i`: index used by model-building functions. Should never be user declared
// * `Is` : saturation current of the diodes
// * `Vt` : thermal resistances of the diodes
//
// Note: only usable as the root of a tree.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner et al. "An Improved and Generalized Diode Clipper Model for Wave Digital Filters"
//----------------------------------------------------------
declare u_diodeAntiparallel author "Dirk Roosenburg";
declare u_diodeAntiparallel copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_diodeAntiparallel license "MIT-style STK-4.3 license";
u_diodeAntiparallel =
case{
    (0, Is, Vt, M, N) => b1
    with{
        b1(R1, a1) = a1 - 2*lam*Vt*(mu0* lambert(((R1*Is)/(mu0*Vt) * exp((lam*a1)/(mu0*Vt))), 3) + 
                                    mu1* lambert(((-R1*Is)/(mu1*Vt) * exp((-lam*a1)/(mu1*Vt))), 3))
        with{
            lam = ma.signum(a1); 
            mu0 = ba.if((a1 < 0), N, M);
            mu1 = ba.if((a1 > 0), M, N);
        };
    };
    (1, Is, Vt, M, N) => !, !; 
    (2, Is, Vt, M, N) => 0; 
};


//=============================Two Port Adaptors==========================================
//========================================================================================


//----------------------`(wd.)u_parallel2Port`--------------------------
// Unadapted 2-port parallel connection.
//
// An unadapted adaptor implementing a 2-port parallel connection between adaptors for Wave Digital Filter connection trees.
// Elements connected to this adaptor will behave as if connected in parallel in circuit.
//
// #### Usage
//
// ```
// buildtree( u_parallel2Port : (A, B) );
// ```
//
// Note: only usable as the root of a tree.
// This adaptor has no user-accessible parameters. 
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.4.1
//----------------------------------------------------------
declare u_parallel2Port author "Dirk Roosenburg";
declare u_parallel2Port copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_parallel2Port license "MIT-style STK-4.3 license";
u_parallel2Port = 
case{
    (0) => u_par
    with{ 
        u_par = si.bus(4) <: b0, b1;
        b0(R0, R1, a0, a1) = (-a0*(R0-R1) + a1*(2*R0^rho*R1^(1-rho)))/(R0+R1);
        b1(R0, R1, a0, a1) = (a1*(R0-R1) + a0*(2*R0^(1-rho)*R1^rho))/(R0+R1);
    };
    (1) => !, !, !, !;
    (2) => 0; 
}with{
    rho = 1; //assume voltage waves
};


//----------------------`(wd.)parallel2Port`--------------------------
// Adapted 2-port parallel connection.
//
// An adaptor implementing a 2-port parallel connection between adaptors for Wave Digital Filter connection trees.
// Elements connected to this adaptor will behave as if connected in parallel in circuit.
//
// #### Usage
//
// ```
// buildtree( A : parallel2Port : B );
// ```
//
// Note: this adaptor has no user-accessible parameters. 
// It should be used within the connection tree with one previous and one forward adaptor.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.4.1
//----------------------------------------------------------
declare parallel2Port author "Dirk Roosenburg";
declare parallel2Port copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare parallel2Port license "MIT-style STK-4.3 license";
parallel2Port = 
case{
    (0) => par_down
    with{
        par_down = b1; 
        b1(R1, a0, a1) = a0;  
    };
    (1) => par_up
    with{
        par_up = b0; 
        b0(R1, a1) = a1; 
    };
    (2) => R0
    with{
        R0(R1) = R1; 
    };
};

//----------------------`(wd.)u_series2Port`--------------------------
// Unadapted 2-port series connection.
//
// An unadapted adaptor implementing a 2-port series connection between adaptors for Wave Digital Filter connection trees.
// Elements connected to this adaptor will behave as if connected in series in circuit.
//
// #### Usage
//
// ```
// buildtree( u_series2Port : (A, B) );
// ```
//
// Note: only usable as the root of a tree.
// This adaptor has no user-accessible parameters. 
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.4.1
//----------------------------------------------------------
declare u_series2Port author "Dirk Roosenburg";
declare u_series2Port copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_series2Port license "MIT-style STK-4.3 license";
u_series2Port = 
case{
    (0) => u_ser
    with{ 
        u_ser = si.bus(4) <: b0, b1;
        b0(R0, R1, a0, a1) = (-a0*(R0-R1) - a1*(2*R0^rho*R1^(1-rho)))/(R0+R1);
        b1(R0, R1, a0, a1) = (a1*(R0-R1) - a0*(2*R0^(1-rho)*R1^rho))/(R0+R1);
    };
    (1) => !, !, !, !;
    (2) => 0; 
}with{
    rho = 1; //assume voltage waves
};


//----------------------`(wd.)series2Port`--------------------------
// Adapted 2-port series connection.
//
// An adaptor implementing a 2-port series connection between adaptors for Wave Digital Filter connection trees.
// Elements connected to this adaptor will behave as if connected in series in circuit.
//
// #### Usage
//
// ```
// buildtree( A : series2Port : B );
// ```
//
// Note: this adaptor has no user-accessible parameters. 
// It should be used within the connection tree with one previous and one forward adaptor.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.4.1
//----------------------------------------------------------
declare series2Port author "Dirk Roosenburg";
declare series2Port copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare series2Port license "MIT-style STK-4.3 license";
series2Port = 
case{
    (0) => ser_down
    with{
        ser_down = b1; 
        b1(R1, a0, a1) = -a0;  
    };
    (1) => ser_up
    with{
        ser_up = b0; 
        b0(R1, a1) = -a1; 
    };
    (2) => R0
    with{
        R0(R1) = R1; 
    };
};


//----------------------`(wd.)parallelCurrent`--------------------------
// Adapted 2-port parallel connection + ideal current source.
//
// An adaptor implementing a 2-port series connection and internal idealized current source between adaptors for Wave Digital Filter connection trees.
// This adaptor connects the two connected elements and an additional ideal current source in parallel.
//
// #### Usage
//
// ```
// i1(i) = parallelCurrent(i, jin);
// buildtree(A : i1 : B);
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `jin` :  Current through the ideal current source in Amps
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// It should be used within a connection tree with one previous and one forward adaptor.
// Correct implementation is shown above.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.4.2
//----------------------------------------------------------
declare parallelCurrent author "Dirk Roosenburg";
declare parallelCurrent copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare parallelCurrent license "MIT-style STK-4.3 license";
parallelCurrent = 
case{
    (0, jin) => par_current_down
    with{
        par_current_down = b1; 
        b1(R1, a0, a1) = a0 + R1^rho*jin;  
    };
    (1, jin) => par_current_up
    with{
        par_current_up = b0; 
        b0(R1, a1) = a1 + R1^rho*jin; 
    };
    (2, jin) => R0
    with{
        R0(R1) = R1; 
    };
}with{
    rho = 1; //assume voltage waves
};


//----------------------`(wd.)seriesVoltage`--------------------------
// Adapted 2-port series connection + ideal voltage source.
//
// An adaptor implementing a 2-port series connection and internal ideal voltage source between adaptors for Wave Digital Filter connection trees.
// This adaptor connects the two connected adaptors and an additional ideal voltage source in series.
//
// #### Usage
//
// ```
// v1(i) = seriesVoltage(i, vin)
// buildtree( A : v1 : B );
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `vin` :  voltage across the ideal current source in Volts
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// It should be used within the connection tree with one previous and one forward adaptor.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.4.2
//----------------------------------------------------------
declare seriesVoltage author "Dirk Roosenburg";
declare seriesVoltage copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare seriesVoltage license "MIT-style STK-4.3 license";
seriesVoltage = 
case{
    (0, vin) => ser_down
    with{
        ser_down = b1; 
        b1(R1, a0, a1) = -a0 - R1^(rho-1)*vin;  
    };
    (1, vin) => ser_up
    with{
        ser_up = b0; 
        b0(R1, a1) = -a1 - R1^(rho-1)*vin; 
    };
    (2, vin) => R0
    with{
        R0(R1) = R1; 
    };
}with{
    rho = 1; //assume voltage waves
};

//----------------------`(wd.)u_transformer`--------------------------
// Unadapted ideal transformer.
//
// An adaptor implementing an ideal transformer for Wave Digital Filter connection trees.
// The first downward-facing port corresponds to the primary winding connections, and the second downward-facing port to the secondary winding connections.
//
// #### Usage
//
// ```
// t1(i) = u_transformer(i, tr);
// buildtree(t1 : (A , B));
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `tr` :  the turn ratio between the windings on the primary and secondary coils
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// It may only be used as the root of the connection tree with two forward nodes.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.4.3
//----------------------------------------------------------
declare u_transformer author "Dirk Roosenburg";
declare u_transformer copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_transformer license "MIT-style STK-4.3 license";
u_transformer(i, n) = u_genericNode(i, transformer_scatter)
with{
    matrix(M,N,f) = si.bus(N) <: ro.interleave(N,M) : par(n,N, par(m,M,*(f(m+1,n+1)))) :> si.bus(M);

    transformer_scatter(R0, R1) = matrix(2, 2, s)
    with{
        s(1,1) =-1*(R0-n^2*R1)/(R0+n^2*R1);
        s(1,2) = (2*n*R0^rho*R1^(1-rho))/(R0+n^2*R1);
        s(2,1) = (2*n*R0^(1-rho)*R1^rho)/(R0+n^2*R1);
        s(2,2) = (R0-n^2*R1)/(R0+n^2*R1);
        s(i,j) = 10; 

        rho = 1; //assume voltage waves
    };
};

//----------------------`(wd.)transformer`--------------------------
// Adapted ideal transformer.
//
// An adaptor implementing an ideal transformer for Wave Digital Filter connection trees.
// The upward-facing port corresponds to the primary winding connections, and the downward-facing port to the secondary winding connections
//
// #### Usage
//
// ```
// t1(i) = transformer(i, tr);
// buildtree(A : t1 : B);
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `tr` :  the turn ratio between the windings on the primary and secondary coils
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// It should be used within the connection tree with one backward and one forward nodes.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.4.3
//----------------------------------------------------------
declare transformer author "Dirk Roosenburg";
declare transformer copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare transformer license "MIT-style STK-4.3 license";
transformer(i, n) = genericNode(i, transformer_scatter, transformer_upPortRes)
with{
    matrix(M,N,f) = si.bus(N) <: ro.interleave(N,M) : par(n,N, par(m,M,*(f(m+1,n+1)))) :> si.bus(M);

    transformer_upPortRes(R1) = n^2*R1; //equation for upward-facing port resistance

    transformer_scatter(R1) = matrix(2, 2, s)
    with{
        s(1,1) =-1*(R0-n^2*R1)/(R0+n^2*R1);
        s(1,2) = (2*n*R0^rho*R1^(1-rho))/(R0+n^2*R1);
        s(2,1) = (2*n*R0^(1-rho)*R1^rho)/(R0+n^2*R1);
        s(2,2) = (R0-n^2*R1)/(R0+n^2*R1);
        s(i,j) = 10; 

        rho = 1; //assume voltage waves

        R0 = n^2*R1; //adapting condition
    };
};


//----------------------`(wd.)u_transformerActive`--------------------------
// Unadapted ideal active transformer.
//
// An adaptor implementing an ideal transformer for Wave Digital Filter connection trees.
// The first downward-facing port corresponds to the primary winding connections, and the second downward-facing port to the secondary winding connections.
//
// #### Usage
//
// ```
// t1(i) = u_transformerActive(i, gamma1, gamma2);
// buildtree(t1 : (A , B));
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `gamma1` :  the turn ratio describing the voltage relationship between the primary and secondary coils
// * `gamma2` :  the turn ratio describing the current relationship between the primary and secondary coils
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// It may only be used as the root of the connection tree with two forward nodes.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.4.3
//----------------------------------------------------------
declare u_transformerActive author "Dirk Roosenburg";
declare u_transformerActive copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_transformerActive license "MIT-style STK-4.3 license";
u_transformerActive(i, gamma1, gamma2) = u_genericNode(i, transformerActive_scatter)
with{
    matrix(M,N,f) = si.bus(N) <: ro.interleave(N,M) : par(n,N, par(m,M,*(f(m+1,n+1)))) :> si.bus(M);

    transformerActive_scatter(R0, R1) = matrix(2, 2, s)
    with{
        s(1,1) =-1*(R0-gamma1*gamma2*R1)/(R0+gamma1*gamma2*R1);
        s(1,2) = (2*gamma1*R0^rho*R1^(1-rho))/(R0+gamma1*gamma2*R1);
        s(2,1) = (2*gamma2*R0^(1-rho)*R1^rho)/(R0+gamma1*gamma2*R1);
        s(2,2) = (R0-gamma1*gamma2*R1)/(R0+gamma1*gamma2*R1);
        s(i,j) = 10; 

        rho = 1; //assume voltage waves
    };
};


//----------------------`(wd.)transformerActive`--------------------------
// Adapted ideal active transformer.
//
// An adaptor implementing an ideal active transformer for Wave Digital Filter connection trees.
// The upward-facing port corresponds to the primary winding connections, and the downward-facing port to the secondary winding connections
//
// #### Usage
//
// ```
// t1(i) = transformerActive(i, gamma1, gamma2);
// buildtree(A : t1 : B);
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `gamma1` :  the turn ratio describing the voltage relationship between the primary and secondary coils
// * `gamma2` :  the turn ratio describing the current relationship between the primary and secondary coils
//
// Note: the adaptor must be declared as a separate function before integration into the connection tree.
// It should be used within the connection tree with two forward nodes.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.4.3
//----------------------------------------------------------
declare transformerActive author "Dirk Roosenburg";
declare transformerActive copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare transformerActive license "MIT-style STK-4.3 license";
transformerActive(i, gamma1, gamma2) = genericNode(i, transformerActive_scatter, transformerActive_upPortRes)
with{
    matrix(M,N,f) = si.bus(N) <: ro.interleave(N,M) : par(n,N, par(m,M,*(f(m+1,n+1)))) :> si.bus(M);

    transformerActive_upPortRes(R1) = gamma1*gamma2*R1; //equation for upward-facing port resistance

    transformerActive_scatter(R1) = matrix(2, 2, s)
    with{
        s(1,1) =-1*(R0-gamma1*gamma2*R1)/(R0+gamma1*gamma2*R1);
        s(1,2) = (2*gamma1*R0^rho*R1^(1-rho))/(R0+gamma1*gamma2*R1);
        s(2,1) = (2*gamma2*R0^(1-rho)*R1^rho)/(R0+gamma1*gamma2*R1);
        s(2,2) = (R0-gamma1*gamma2*R1)/(R0+gamma1*gamma2*R1);
        s(i,j) = 10; 

        rho = 1; //assume voltage waves

        R0 = gamma1*gamma2*R1; //adapting condition
    };
};


//===============================Three Port Adaptors======================================
//========================================================================================


//----------------------`(wd.)parallel`--------------------------
// Adapted 3-port parallel connection.
//
// An adaptor implementing a 3-port parallel connection between adaptors for Wave Digital Filter connection trees.
// This adaptor is used to connect adaptors simulating components connected in parallel in the circuit.
//
// #### Usage
//
// ```
// buildtree( A : parallel : (B, C) );
// ```
//
// Note: this adaptor has no user-accessible parameters. 
// It should be used within the connection tree with one previous and two forward adaptors.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.5.1
//----------------------------------------------------------
declare parallel author "Dirk Roosenburg";
declare parallel copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare parallel license "MIT-style STK-4.3 license";
parallel= 
case{
    (0) => par_down
    with{
        par_down = si.bus(5) <: b1, b2;
        b1(R1, R2, a0, a1, a2) = a0 +  a1 * -R1/(R1 + R2) + a2 * R1/(R1 + R2);
        b2(R1, R2, a0, a1, a2) = a0 +  a1 * R2/(R1 + R2) + a2 * -R2/(R1 + R2);
    };
    (1) => par_up
    with{
        par_up = b0;
        b0(R1, R2, a1, a2) = a1 * R2/(R1 + R2) + a2 * R1/(R1 + R2);
    };
    (2) => R0
    with{
        R0(R1, R2) = 1/(1/R1+1/R2); 
    };

};


//----------------------`(wd.)series`--------------------------
// Adapted 3-port series connection.
//
// An adaptor implementing a 3-port series connection between adaptors for Wave Digital Filter connection trees.
// This adaptor is used to connect adaptors simulating components connected in series in the circuit.
//
// #### Usage
//
// ```
//
// tree = A : (series : (B, C));
// ```
//
// Note: this adaptor has no user-accessible parameters. 
// It should be used within the connection tree with one previous and two forward adaptors.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 1.5.2
//----------------------------------------------------------
declare series author "Dirk Roosenburg";
declare series copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare series license "MIT-style STK-4.3 license";
series = 
case{

    (0) => ser_down
    with{
        ser_down = si.bus(5)<: b1, b2;
        b1(R1, R2, a0, a1, a2) = a0 * -R1/(R1+R2) + a1 * R2/(R1+R2) +  a2 *-R1/(R1+R2);
        b2(R1, R2, a0, a1, a2) = a0 * -R2/(R1+R2) + a1 * -R2/(R1+R2) + a2 * R1/(R1+R2);
    };
    (1) => ser_up
    with{
        ser_up = b0;
        b0(R1, R2, a1, a2) = -a1 - a2;
    };
    (2) => R0
    with{
        R0(R1, R2) = R1 + R2; 
    };
};

//====================================R-Type Adaptors=====================================
//========================================================================================


//----------------------`(wd.)u_sixportPassive`--------------------------
// Unadapted six-port rigid connection.
//
// An adaptor implementing a six-port passive rigid connection between elements. 
// It implements the simplest possible rigid connection found in the Fender Bassman Tonestack circuit.
// 
//
// #### Usage
//
// ```
//
// tree = u_sixportPassive : (A, B, C, D, E, F));
// ```
//
// Note: this adaptor has no user-accessible parameters. 
// It should be used within the connection tree with six forward adaptors.
//
// #### Reference
//
// K. Werner, "Virtual Analog Modeling of Audio Circuitry Using Wave Digital Filters", 2.1.5
//----------------------------------------------------------
declare u_sixportPassive author "Dirk Roosenburg";
declare u_sixportPassive copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_sixportPassive license "MIT-style STK-4.3 license";
u_sixportPassive(i) = genericNode(i, sixport_scatter)
with{
    sixport_scatter(Ra, Rb, Rc, Rd, Re, Rf) =  matrix(6, 6, mtx)
    with{
        mtx  =
        case{
            (1, 1) => ((-Ra)*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf   + Rd*(Re + Rf)) +   Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (1, 2) => (2*Ra*((Rc + Re)*Rf + Rd*(Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (1, 3) => (2*Ra*(Rb*Rd + Re*Rf + Rd*(Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (1, 4) => (-1)*((2*Ra*(Rb*(Rc + Re) + Rc*(Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (1, 5) => (2*Ra*(Rb*Rd - Rc*Rf))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (1, 6) => (-1)*((2*Ra*(Rc*Re + Rb*(Rc + Rd + Re)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (2, 1) => (2*Rb*((Rc + Re)*Rf + Rd*(Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (2, 2) => (Ra*(Rd*Re - Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) - Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) +   Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (2, 3) => (-1)*((2*Rb*(Ra*Re + Re*Rf + Rd*(Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (2, 4) => (-2*Ra*Rb*Re + 2*Rb*Rc*Rf)/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (2, 5) => (2*Rb*(Ra*(Rc + Rd) + Rc*(Rd + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (2, 6) => (-1)*((2*Rb*(Rc*Rd + Ra*(Rc + Rd + Re)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (3, 1) => (2*Rc*(Rb*Rd + Re*Rf + Rd*(Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (3, 2) => (-1)*((2*Rc*(Ra*Re + Re*Rf + Rd*(Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (3, 3) => 1 - (2*Rc*(Rd*Re + Rd*Rf + Re*Rf + Rb*(Rd + Rf) + Ra*(Rb + Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (3, 4) => (-1)*((2*Rc*(Rb*Rf + Ra*(Rb + Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (3, 5) => (-1)*((2*Rc*(Ra*(Rb + Rf) + Rb*(Rd + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (3, 6) => (2*Rc*(Rb*Rd - Ra*Re))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (4, 1) => (-1)*((2*Rd*(Rb*(Rc + Re) + Rc*(Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (4, 2) => (-2*Ra*Rd*Re + 2*Rc*Rd*Rf)/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (4, 3) => (-1)*((2*Rd*(Rb*Rf + Ra*(Rb + Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (4, 4) => 1 - (2*Rd*(Rc*(Re + Rf) + Ra*(Rb + Re + Rf) + Rb*(Rc + Re + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (4, 5) => (-1)*((2*Rd*((Rb + Rc)*Rf + Ra*(Rb + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (4, 6) => (-1)*((2*Rd*((Ra + Rc)*Re + Rb*(Rc + Re)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (5, 1) => (2*Re*(Rb*Rd - Rc*Rf))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (5, 2) => (2*Re*(Ra*(Rc + Rd) + Rc*(Rd + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (5, 3) => (-1)*((2*Re*(Ra*(Rb + Rf) + Rb*(Rd + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (5, 4) => (-1)*((2*Re*((Rb + Rc)*Rf + Ra*(Rb + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (5, 5) => 1 - (2*Re*((Rb + Rc)*(Rd + Rf) + Ra*(Rb + Rc + Rd + Rf)))/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (5, 6) => (2*((Rb + Rc)*Rd + Ra*(Rc + Rd))*Re)/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (6, 1) => (-1)*((2*(Rc*Re + Rb*(Rc + Rd + Re))*Rf)/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (6, 2) => (-1)*((2*(Rc*Rd + Ra*(Rc + Rd + Re))*Rf)/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (6, 3) => (2*(Rb*Rd - Ra*Re)*Rf)/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (6, 4) => (-1)*((2*((Ra + Rc)*Re + Rb*(Rc + Re))*Rf)/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf))));
            (6, 5) => (2*((Rb + Rc)*Rd + Ra*(Rc + Rd))*Rf)/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (6, 6) => 1 - (2*(Rc*(Rd + Re) + Ra*(Rc + Rd + Re) + Rb*(Rc + Rd + Re))*Rf)/(Ra*(Rd*Re + Rb*(Rc + Rd + Re) + Rd*Rf + Re*Rf + Rc*(Re + Rf)) + Rc*(Re*Rf + Rd*(Re + Rf)) + Rb*(Re*Rf + Rc*(Rd + Rf) + Rd*(Re + Rf)));
            (i, j) => 10;
        };
        matrix(M,N,f) = si.bus(N) <: ro.interleave(N,M) : par(n,N, par(m,M,*(f(m+1,n+1)))) :> si.bus(M);
    };
};

//===============================Node Creating Functions==================================
//========================================================================================

//----------------------`(wd.)genericNode`--------------------------
// Function for generating an adapted node from another faust function or scattering matrix.
//
// This function generates a node which is suitable for use in the connection tree structure. 
// `genericNode` separates the function that it is passed into upward-going and downward-going waves. 
//
// #### Usage
//
// ```
// n1(i) = genericNode(i, scatter, upRes);
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `scatter` : the function which describes the the node's scattering behavior
// * `upRes` : the function which describes the node's upward-facing port-resistance
//
// Note: `scatter` must be a function with n inputs, n outputs, and n-1 parameter inputs. 
//  input/output 1 will be used as the adapted upward-facing port of the node, ports 2 to n will all be downward-facing. 
//  The first input/output pair is assumed to already be adapted - i.e. the output 1 is not dependent on input 1. 
//  The parameter inputs will receive the port resistances of the downward-facing ports.
//
// `upRes` must be a function with n-1 parameter inputs and 1 output.
//  The parameter inputs will receive the port resistances of the downward-facing ports.
//  The output should give the upward-facing port resistance of the node based on the upward-facing port resistances of the input.
//
//  If used on a leaf element (n=1), the model will automatically introduce a one-sample delay. 
//  Thus, the output of the node at sample t based on the input, a[t], should be the output one sample ahead, b[t+1]. 
//  This may require transformation of the output signal. 
//
//----------------------------------------------------------
declare genericNode author "Dirk Roosenburg";
declare genericNode copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare genericNode license "MIT-style STK-4.3 license";
genericNode =
case{
    (0, scatter, upRes) => down(inputs(scatter))
    with{
        down(1) = scatter; //leaf node case
        down(n) = scatter : !, bus(outputs(scatter)-1); //internal node case
    };
    (1, scatter, upRes) => up(inputs(scatter))
    with{
        up(1) = _; //leaf node case
        up(n) = bus(inputs(upRes)), 0 , bus(outputs(scatter)-1) : scatter : _, block(outputs(scatter)-1); //internal node case
    };
    (2, scatter, upRes) => upRes;
}
with{
    bus(0) = 0:!;
    bus(x) = si.bus(x);
    block(0) = 0:!;
    block(x) = si.block(x);
};


//----------------------`(wd.)genericNode_Vout`--------------------------
// Function for generating a terminating/leaf node which gives the voltage across itself as a model output.
//
// This function generates a node which is suitable for use in the connection tree structure. 
// It also calculates the voltage across the element and gives it as a model output.
//
// #### Usage
//
// ```
// n1(i) = genericNode_Vout(i, scatter, upRes);
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `scatter` : the function which describes the the node's scattering behavior
// * `upRes` : the function which describes the node's upward-facing port-resistance
//
// Note: `scatter` must be a function with 1 input and 1 output. 
//  It should give the output from the node based on the incident wave. 
//  
//  The model will automatically introduce a one-sample delay to the output of the function
//  Thus, the output of the node at sample t based on the input, a[t], should be the output one sample ahead, b[t+1]. 
//  This may require transformation of the output signal. 
//
// `upRes` must be a function with no inputs and 1 output.
//  The output should give the upward-facing port resistance of the node.
//
//----------------------------------------------------------
declare genericNode_Vout author "Dirk Roosenburg";
declare genericNode_Vout copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare genericNode_Vout license "MIT-style STK-4.3 license";
genericNode_Vout =
case{
    (0, scatter, upRes) => _ <: b, voltage
    with{
        b(a) = a : scatter;
        voltage(a) = 1/2*(a + b(a)');
    };
    (1, scatter, upRes) => _, !;
    (2, scatter, upRes) => upRes;
};

//----------------------`(wd.)genericNode_Iout`--------------------------
// Function for generating a terminating/leaf node which gives the current through itself as a model output.
//
// This function generates a node which is suitable for use in the connection tree structure. 
// It also calculates the current through the element and gives it as a model output.
//
// #### Usage
//
// ```
// n1(i) = genericNode_Iout(i, scatter, upRes);
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `scatter` : the function which describes the the node's scattering behavior
// * `upRes` : the function which describes the node's upward-facing port-resistance
//
// Note: `scatter` must be a function with 1 input and 1 output. 
//  It should give the output from the node based on the incident wave. 
//  
//  The model will automatically introduce a one-sample delay to the output of the function.
//  Thus, the output of the node at sample t based on the input, a[t], should be the output one sample ahead, b[t+1]. 
//  This may require transformation of the output signal. 
//
// `upRes` must be a function with no inputs and 1 output.
//  The output should give the upward-facing port resistance of the node.
//
//----------------------------------------------------------
declare genericNode_Iout author "Dirk Roosenburg";
declare genericNode_Iout copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare genericNode_Iout license "MIT-style STK-4.3 license";
genericNode_Iout =
case{
    (0, scatter, upRes) => _ <: b, current
    with{
        b(a) = a : scatter;
        current(a) = 1/2/upRes*(a - b(a)');
    };
    (1, scatter, upRes) => _, !;
    (2, scatter, upRes) => upRes;
};


//----------------------`(wd.)u_genericNode`--------------------------
// Function for generating an unadapted node from another Faust function or scattering matrix.
//
// This function generates a node which is suitable for use as the root of the connection tree structure. 
//
// #### Usage
//
// ```
// n1(i) = u_genericNode(i, scatter);
// ```
//
// Where:
//
// * `i`: index used by model-building functions. Should never be user declared
// * `scatter` : the function which describes the the node's scattering behavior
//
// Note: 
// `scatter` must be a function with n inputs, n outputs, and n parameter inputs. 
//  each input/output pair will be used as a downward-facing port of the node
//  the parameter inputs will receive the port resistances of the downward-facing ports.
//
//----------------------------------------------------------
declare u_genericNode author "Dirk Roosenburg";
declare u_genericNode copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare u_genericNode license "MIT-style STK-4.3 license";
u_genericNode =
case{
    (0, scatter) => scatter;
    (1, scatter) => block(inputs(scatter));
    (2, scatter) => 1234;
}
with{
    block(0) = 0:!;
    block(x) = si.block(x);
};


//===============================Model Building Functions=================================
//========================================================================================


//----------------------`(wd.)builddown`--------------------------
// Function for building the structure for calculating waves traveling down the WD connection tree.
//
// It recursively steps through the given tree, parametrizes the adaptors, and builds an algorithm.
// It is used in conjunction with the buildup() function to create a model.
//
// #### Usage
//
// ```
// builddown(A : B)~buildup(A : B);
// ```
//
// Where: 
//  `(A : B)` : is a connection tree composed of WD adaptors
//----------------------------------------------------------
declare builddown author "Dirk Roosenburg";
declare builddown copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare builddown license "MIT-style STK-4.3 license";
builddown(A : As) = ((upPortRes, addins(inputs(A(0)) - outputs(upPortRes))) :  A(0)) , addins(inputs(pardown(As)) - outputs(A(0))) : route(mtxsum(s_mtx(As)), mtxsum(s_mtx(As)), gencross(0, 0, 0, 0, 0, s_mtx(As))) : pardown(As)
with{

    //substitute for si.bus which can accept an argument of 0
    addins = 
    case{
        (0) => 0 : !; 
        (x) => si.bus(x);
    };
    
    //recursively build in parallel
    pardown = 
    case{
        ((Ax, Axx)) => builddown(Ax), pardown(Axx);
        (Ax) => builddown(Ax);
    };
    
    //generate a list of inputs from the next stage down the tree
    s_mtx = 
    case{
        ((Ax, Axx)) => inputs(builddown(Ax)), s_mtx(Axx);
        (Ax) => inputs(builddown(Ax));
    };

    //take the sum of the list
    mtxsum(t_mtx) = sum(i, ba.count(t_mtx), ba.take(i+1, t_mtx));

    upPortRes = parres(As);

    //generate a crossover matrix for the route object based on a list of i/o dimensions
    gencross = 
    case{
        (0, 0, 0, 0, 0, (1, 1)) => 1, 1, 2, 2; 
        (0, 0, 0, 0, 0, (xs, xxs)) => (1, 1), gencross(2, xs+1, ba.count((xs, xxs))-1, 2, mtxsum((xs, xxs)), xxs);

        (0, 0, 0, 0, 0, 0) => 0 : !;
        (0, 0, 0, 0, 0, x) => par(i, x, i+1, i+1);

        //((out, next, norm_index, spec_index, sum), (xs, xxs))

        (msum, msum, count, fcount, msum, xs) => (fcount, msum);  //output is a special output
        (msum, next, count, fcount, msum, xs) => (msum, msum-count); //escape case, reached end of bus

        (out, out, count, fcount, msum, (xs, xxs)) => (fcount, out), gencross(out+1, xs+out, count-1, fcount+1, msum, xxs);
        (out, out, count, fcount, msum, xs) => (fcount, out), gencross(out+1, xs+out, count-1, fcount+1, msum, 0);  //output is a special output

        (out, next, count, fcount, msum, xs) => ((count+out), out), gencross(out+1, next, count, fcount, msum, xs); //output is not a special output
    };
}; 

builddown(A) = A(0); 


//----------------------`(wd.)buildup`--------------------------
// Function for building the structure for calculating waves traveling up the WD connection tree.
//
// It recursively steps through the given tree, parametrizes the adaptors, and builds an algorithm.
// It is used in conjunction with the builddown() function to create a full structure.
//
// #### Usage
//
// ```
// builddown(A : B)~buildup(A : B);
// ```
//
// Where: 
// `(A : B)` : is a connection tree composed of WD adaptors
//----------------------------------------------------------
declare builddown author "Dirk Roosenburg";
declare builddown copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare builddown license "MIT-style STK-4.3 license";
buildup(A : As) = upPortRes, (parup(As) : route(mtxsum(s_mtx(As)), mtxsum(s_mtx(As)), gencross_up(0, 0, 0, 0, 0, s_mtx(As))) : split(s_mtx(As))) : A(1), addins(outputs(split(s_mtx(As))) + outputs(upPortRes) - inputs(A(1))) 
with{

    //substitute for si.bus which can accept an argument of 0
    addins = 
    case{
        (0) => 0 : !; 
        (x) => si.bus(x);
    };

    //recursively build in parallel
    parup =  //<: crossover(out_list(Ap)) : split(out_list(Ap))
    case{
        ((Ax, Axx)) => buildup(Ax), parup(Axx);
        (Ax) => buildup(Ax);
    };

    //generate a list of outputs from the next stage down the tree
    s_mtx = 
    case{
        ((Ax, Axx)) => outputs(buildup(Ax)), s_mtx(Axx);
        (Ax) => outputs(buildup(Ax));
    };
    
    //take the sum of a list
    mtxsum(t_mtx) = sum(i, ba.count(t_mtx), ba.take(i+1, t_mtx));

    //split based on a list of i/o dimensions
    split(inl) = (si.bus(n) <: si.bus(n), si.bus(n)), (addins(s-n))
    with{
        n = ba.count(inl);
        s = inl :> _; 
    };

    //generate a crossover matrix based for the route object based on a list of i/o dimensions
    gencross_up = 
    case{
        //corner case which must be coded manually
        (0, 0, 0, 0, 0, (1, 1)) => 1, 1, 2, 2; 
        //user access function
        (0, 0, 0, 0, 0, (xs, xxs)) => (1, 1), gencross_up(2, xs+1, ba.count((xs, xxs))-1, 2, mtxsum((xs, xxs)), xxs);

        //more corner cases
        (0, 0, 0, 0, 0, 0) => 0: !;
        (0, 0, 0, 0, 0, x) => par(i, x, i+1, i+1);

        //((out, next, norm_index, spec_index, sum), (xs, xxs))

        (msum, msum, count, fcount, msum, xs) => (msum, fcount);  //output is a special output
        (msum, next, count, fcount, msum, xs) => (msum-count, msum); //escape case, reached end of bus

        (out, out, count, fcount, msum, (xs, xxs)) => (out, fcount), gencross_up(out+1, xs+out, count-1, fcount+1, msum, xxs);
        (out, out, count, fcount, msum, xs) => (out, fcount), gencross_up(out+1, xs+out, count-1, fcount+1, msum, 0);  //output is a special output

        (out, next, count, fcount, msum, xs) => (out, (count+out)), gencross_up(out+1, next, count, fcount, msum, xs); //output is not a special output
    };

    upPortRes = parres(As);
};

buildup(A) = A(1);

//----------------------`(wd.)getres`--------------------------
// Function for determining the upward-facing port resistance of a partial WD connection tree.
//
// It recursively steps through the given tree, parametrizes the adaptors, and builds an algorithm.
// It is used by the buildup and builddown functions but is also helpful in testing.
//
// #### Usage
//
// ```
// getres(A : B)~getres(A : B);
// ```
//
// Where: 
// `(A : B)` : is a partial connection tree composed of WD adaptors
//
// Note:
// This function cannot be used on a complete WD tree. When called on an unadapted adaptor (u_ prefix), it will create errors.
//----------------------------------------------------------
declare getres author "Dirk Roosenburg";
declare getres copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare getres license "MIT-style STK-4.3 license";
getres(A: As) = parres(As) : A(2);
getres(A) = A(2); 


//----------------------`(wd.)parres`--------------------------
// Function for determining the upward-facing port resistance of a partial WD connection tree.
//
// It recursively steps through the given tree, parametrizes the adaptors, and builds an algorithm.
// It is used by the buildup and builddown functions but is also helpful in testing.
// This function is a parallelized version of `getres`.
//
// #### Usage
//
// ```
// parres((A , B))~parres((A , B));
// ```
//
// Where: 
// `(A , B)` : is a partial connection tree composed of WD adaptors
//
// Note: this function cannot be used on a complete WD tree. When called on an unadapted adaptor (u_ prefix), it will create errors.
//----------------------------------------------------------
declare parres author "Dirk Roosenburg";
declare parres copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare parres license "MIT-style STK-4.3 license";
parres((Ap1, Ap2)) = getres(Ap1) , parres(Ap2);
parres(Ap) = getres(Ap);


//----------------------`(wd.)buildout`--------------------------
// Function for creating the output matrix for a WD model from a WD connection tree.
//
// It recursively steps through the given tree and creates an output matrix passing only outputs.
//
// #### Usage
//
// ```
// buildout( A : B );
// ```
//
// Where: 
// `(A : B)` : is a connection tree composed of WD adaptors
//
//----------------------------------------------------------
declare buildout author "Dirk Roosenburg";
declare buildout copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare buildout license "MIT-style STK-4.3 license";
buildout(A: As) = parout(As)
with{
    parout((A, Ap)) = buildout(A), parout(Ap);
    parout(A) = buildout(A);
};
buildout(A) = outmtx(outputs(A(0)))
with{
    outmtx(1) = !; 
    outmtx(2) = !, _; 
};


//----------------------`(wd.)buildtree`--------------------------
// Function for building the DSP model from a WD connection tree structure.
//
// It recursively steps through the given tree, parametrizes the adaptors, and builds the algorithm.
//
// #### Usage
//
// ```
// buildtree(A : B);
// ```
//
// Where: 
// `(A : B)` : a connection tree composed of WD adaptors
//----------------------------------------------------------
declare buildtree author "Dirk Roosenburg";
declare buildtree copyright "Copyright (C) 2020 by Dirk Roosenburg <dirk.roosenburg.30@gmail.com>";
declare buildtree license "MIT-style STK-4.3 license";
buildtree((A : B)) = builddown(A : B)~buildup(A : B) : buildout(A : B);


/*******************************************************************************
# Licenses

## STK 4.3 License

Permission is hereby granted, free of charge, to any person obtaining a copy of 
this software and associated documentation files (the "Software"), to deal in 
the Software without restriction, including without limitation the rights to 
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
of the Software, and to permit persons to whom the Software is furnished to do 
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

Any person wishing to distribute modifications to the Software is asked to send 
the modifications to the original developer so that they can be incorporated 
into the canonical version.  For software copyrighted by Dirk Roosenburg, 
email your modifications to <dirk.roosenburg.30@gmail.com>.  This is, however, not a 
binding provision of this license.

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 AND NONINFRINGEMENT.  IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
SOFTWARE.

--------------------------------------------------------------------------------

## LGPL 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.
*******************************************************************************/