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
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import random, math, copy, operator, sys
import instruments, plusminus, peace
import mx.Number
R = mx.Number.Rational

## define structural variables

target_duration = 1200          # seconds - loop5 event alignment will add about 20%
number_of_layers = 7
events_per_layer = 200 #150
minimum_bar_length = 8          # 8/32, i.e. 2/8
maximum_bar_length = 32         # 32/32, i.e. 8/8
minimum_section_length = 256    # 32nd notes
maximum_section_length = 767
minimum_tempo_variance = 0.12   # minimum tempo variance to actually change tempo
bar_length = 32                 # possible length of first bar
minTuplet = 5                   # 5/32 to 16/32 (minim)
minNoteVal = (0.5 * 6) / 11.0   # i.e. one 64th note under a 11:6 tuplet
negativeness = -4               # how quickly it will die (-1 ... -14)
negativesection = 0.75          # point at which we allow it to die...
negativesectiongap = 50         # pause before negative section

symbol_pages = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
notes_pages_central_pitch = {
    'A': 76, # c''''
    'B': 56, # e''
    'C': 82, # fis''''
    'D': 30, # d
    'E': 87, # b''''
    'F': 73, # a'''
    'G': 60 # aes''
    }
pitchclasses = {
    'c':1, 'cis':2, 'des':2, 'd':3, 'dis':4, 'ees':4, 'e':5, 'f':6, 'fis':7, 'ges':7, 
    'g':8, 'gis':9, 'aes':9, 'a':10, 'ais':11, 'bes':11, 'b':12
    }
event_types = {'-( )':0, '(-)':1, '( )-':2, '-( )-':3, '(-)-':4, '-(-)':5, '-(-)-':6}
etorder = { '-( )': 'bC', '(-)': 'B', '( )-': 'Ca', '-( )-': 'bCa',
        '(-)-': 'Ba', '-(-)': 'bB', '-(-)-': 'bBa' }
# b = accessory before      s = subsidiary before       r = acc+sub before
# C = central sound         v = subsidiary during       R = cs+sub during
# B = central sound + accessory during                  S = cs+acc+sub during
# A = accessory during                                  T = acc+sub during
# a = accessory after       t = subsidiary after        u = acc+sub after
# o = rest
rep = {
    'b': [('b', (0.1, 0.4))] * 5,
    'a': [('a', (0.1, 0.4))] * 5,
    'A': [('A', (0.1, 0.5))] * 5,
    'ba': [('ba', (0.2, 0.5))] * 4,
    'bA': [('bA', (0.2, 0.6))] * 4,
    'Aa': [('Aa', (0.2, 0.6))] * 4,
    'bAa': [('bAa', (0.3, 0.6))] * 3,
    'C': [('C', (0.6, 0.8))] * 3,
    'B': [('B', (0.6, 0.8))] * 3,
    'bC': [('bC', (0.8, 0.95))] * 2,
    'Ca': [('Ca', (0.8, 0.95))] * 2,
    'bB': [('bB', (0.8, 1.0))] * 2,
    'Ba': [('Ba', (0.8, 1.0))] * 2,
    'bCa': [('bCa', (0.85, 1.0))] * 2,
    'bBa': [('bBa', (1.0, 1.0))]
    }
rep6 = []
for v in rep.values():
    rep6 += v
event_type_rep = {
    0: rep['b'] + rep['C'] + rep['bC'],
    1: rep['C'] + rep['A'] + rep['B'],
    2: rep['C'] + rep['a'] + rep['Ca'],
    3: rep['b'] + rep['C'] + rep['a'] + rep['bC'] + rep['Ca'] + rep['ba'],
    4: rep['C'] + rep['B'] + rep['A'] + rep['a'] + rep['Ca'] + rep['Aa'] + rep['Ba'],
    5: rep['b'] + rep['C'] + rep['B'] + rep['A'] + rep['bC'] + rep['bB'] + rep['bA'],
    6: rep6
    }

dynamics = ['pppp', 'ppp', 'pp', 'p', 'mp', 'mf', 'ff', 'fff'] #, 'ffff']
# number of words in each word file
wordfiles = [(1, 1), (2, 17), (3, 8), (4, 25), (5, 127), (6, 376), (7, 956), (8, 1480), 
        (9, 2385), (10, 3044), (11, 4100), (12, 4880), (13, 5952), (14, 7161), (15, 8333), 
        (16, 9099), (17, 8674), (18, 7798), (19, 5800), (20, 4304), (21, 2872), (22, 1791), 
        (23, 1012), (24, 462), (25, 261), (26, 75), (27, 58), (28, 33)]

'''
sum of pm flags by event type
SELECT `event_type` , SUM( `flag_plus` ) , SUM( `flag_minus` ) FROM `symbols` GROUP BY `event_type`
              +      -
    -( )      14     13    1
     (-)      14     16   -2
     ( )-     12     13   -1
    -( )-     16     12    4
     (-)-     15     12    3
    -(-)      13     11    2
    -(-)-     16     15    1
'''

def flatten(iterable, ltypes=(list, tuple)):
    for e in iter(iterable):
        if isinstance(e, ltypes):
            for f in flatten(e, ltypes):
                yield f
        else:
            yield e

def loadformulafile(parameter):
    """ parse the formula file for the given parameter (str)
        returns a list of coefficients """
    try:
        formulafile = open('%s.formula' % parameter, 'r')
    except IOError:
        print 'Formula file for %s not found!' % parameter
        return False
    while True:
        formula = formulafile.readline()
        # formula is first uncommented line
        if not formula[0] == '#': break
    formulafile.close()
    # apply replaces
    replaces = [('+', ' '), ('e-', 'eminus'), ('-', ' -'), ('eminus', 'e-'), ('*', ''), ('x', ''), ('\n', '')]
    for r in replaces:
        formula = formula.replace(r[0], r[1])
    coefficients = []
    for f in formula.split():
        coefficients.append(float(f.split('^')[0]))
    return coefficients

coefficients = {
    'activity_absolute': None,
    'activity_relative': None,
    'consonance_inter': None,
    'consonance_intra': None,
    'durations': None,
    'dynamic_absolute': None,
    'dynamic_relative': None,
    'register_absolute': None,
    'register_relative': None,
}
for f in coefficients.keys():
    coefficients[f] = loadformulafile(f)

## generate initial plus-minus values
def generate_pm_values(minmin, minmax, maxmin, maxmax):
    array = []
    for event_type in range(7):
        min = random.randint(minmin, minmax)
        max = random.randint(maxmin, maxmax)
        array.append(random.randint(min, max))
    return array

def plusminusvalue(elapsed_proportion, currentvalue, flags):
    """ return pm flag for event 
        elapsed_proportion (float),
        currentvalue (int)
        flags (tuple) (flag_plus (int), flag_minus (int)) """
    if flags[0] is None and flags[1] is None:
        return 0
    elif flags[0] is None:
        return flags[1] * -1
    elif flags[1] is None:
        return flags[0]
    # if we have to choose, prefer flag that heads in the right direction
    if elapsed_proportion < negativesection:
        if currentvalue + flags[0] >= 9:
            return flags[0]
        elif currentvalue - flags[1] >= 0:
            return flags[1] * -1
        else:
            return flags[0]
    else:
        return flags[1] * negativeness

## functions for dealing with pitches
def freq(pitchnumber):
    """ return the frequency of a pitchnumber """
    reffreq = 440
    # I think this is nominal, since I'm only using frequency ratios
    refpitchnumber = 49 # middle A
    return reffreq * 2 ** ( (pitchnumber - refpitchnumber) / 12.0 )

def intervalratio(pitch1, pitch2):
    """ return the ratio between two pitches
        accepts either tuples: pitch1(pitchclass, octave), pitch2(pitchclass, octave)
        or integers: pitchnumber1, pitchnumber2 """
    try:
        p1, p2 = int(pitch1), int(pitch2)
    except TypeError:
        p1 = pitch2number(pitch1[0], pitch1[1])
        p2 = pitch2number(pitch2[0], pitch2[1])
    return freq(max(p1, p2)) / freq(min(p1, p2))

consonancedict = {
        0: 1.00, # unison
        7: 0.87, # perfect fifth
        5: 0.82, # perfect fourth
        4: 0.70, # major third
        8: 0.64, # minor sixth
        9: 0.55, # major sixth
        3: 0.45, # minor third
        6: 0.17, # augmented fourth
        11: 0.50, # major seventh
        2: 0.24, # major second
        10: 0.20, # minor seventh
        1: 0.10  # minor second
        }
"""
This data (partially) informed by Figure 6 in Skovenborg, Esben & Neilsen, Søren
H., "Measuring Sensory Consonance by Auditory Modelling", Proceeds of the 5th
International Conference on Digital Audio Effects (DAFX-02): DAFX-256, 2002
"""

def consonance(pitch1, pitch2):
    """ (objectively) score consonance levels between two pitches """
    # this is a cheat method relying on my instinct to score the intervals
    interval = abs(pitch1 - pitch2) % 12
    return consonancedict[interval]

def pitch2number(pitchclass, octave):
    """ pitch is str(pitchclass), int(octave) """
    pitchnumber = pitchclasses[pitchclass] + ( 12 * ( octave + 2 ) ) + 3
    return pitchnumber

def number2pitch(pitchnumber, sharp_or_flat='is'):
    """ convert a pitchnumber to a pitch tuple(pitchclass, octave)
        pitchnumber (int), sharp_or_flat='is' (str) """
    if sharp_or_flat is None: sharp_or_flat = 'is'
    octave = ( ( pitchnumber - 4 ) // 12 ) - 2
    pitchclass = ( pitchnumber - 3 ) - ( 12 * ( octave + 2 ) )
    for pn, pc in pitchclasses.items():
        if pc == pitchclass:
            if len(pn) > 2:
                if pn[1:3] == sharp_or_flat:
                    pitch = (pn, octave)
            else:
                pitch = (pn, octave)
    return pitch

def nextnote(pitchclass, p, direction):
    """ returns the pitchnumber of the closest pitch of class pitchclass in
        a specified direction
        pitchclass (str), p pitchnumber(int), direction (int) 1|-1 """
    while pitchclass not in (number2pitch(p)[0], number2pitch(p, 'es')[0]):
        p += direction
    return p

def lily2pitches(pitch):
    """ converts a lily pitchstring (or chord) to pitchnumbers """
    # remove chord brackets
    pitch = pitch.replace('<', '').replace('>', '')
    pitches = pitch.split()
    pitchnumbers = []
    for p in pitches:
        octavedown = p.count(',')
        octaveup = p.count("'")
        pc = p.replace(',', '').replace("'", '')
        pitchnumbers.append(pitch2number(pc, octaveup - octavedown))
    return pitchnumbers

def pitch2lily(pitchclass, octave=None):
    """ convert a pitch to lilypond notation
        accepts pitchnumber (int), sharp_or_flat='is' (str)
        or pitchclass (string), octave (int) """
    if isinstance(pitchclass, int):
        pitchclass, octave = number2pitch(pitchclass, octave)
    if octave <= 0:
        pitchstring = pitchclass + ',' * abs(octave) # + '!'
        return pitchstring
    elif octave > 0:
        pitchstring = pitchclass + "'" * octave # + '!'
        return pitchstring

def pitches2lilychord(pitchlist):
    """ convert a list of pitches to lilypond notation """
    # remove duplicates, sort
    pitchlist = list(set(pitchlist))
    pitchlist.sort()
    out = '<' + pitch2lily(pitchlist[0])
    for p in pitchlist[1:]:
        out += ' ' + pitch2lily(p)
    return out + '>'

def transposepitch(pitchnumber, steps, lb, ub):
    """ transpose a pitch within bounds
        pitchnumber (int), steps (int), lowerbound (int), upperbound (int) """
    if pitchnumber + steps > ub:
        newpitchnumber = lb + pitchnumber + steps - ub
    elif pitchnumber + steps < lb:
        newpitchnumber = ub + pitchnumber + steps - lb
    else:
        newpitchnumber = pitchnumber + steps
    return newpitchnumber

def checkref(ref, lb, ub):
    """ check pitch to make sure it is within bounds """
    if ref < lb:
        ref = nextnote(number2pitch(ref)[0], ub, -1)
    elif ref > ub:
        ref = nextnote(number2pitch(ref)[0], lb, 1)
    return ref

def transposechord(chord, lastchord, steps, lb, ub):
    """ transpose a central sound chord with reference to the last chord
        chord, lastchord (sorted lists of tuples (pitchnumber, articulation)),
        steps (int), lb (int), ub (int)
        distance between lb and ub must be at least one octave (11) """
    # lastchord must be at least two notes
    if lastchord is None:
        raise TypeError
    if len(lastchord) < 2:
        lastchord.append((lastchord[0][0] + 6, lastchord[0][1]))
    if len(chord) < 2:
        chord.append((chord[0][0] + 12, chord[0][1]))
    timpano = False
    if (ub - lb) < 11:
        # special case for timpano
        timpano = True
        ub = lb + 14
    # expand lastchord if it's not big enough for steps
    if len(lastchord) <= steps:
        # expand up
        for i, lc in enumerate(lastchord):
            lastchord.append((lastchord[-1][0] + (lastchord[i+1][0] - lc[0]), None))
            if len(lastchord) > steps:
                break
    elif len(lastchord) <= (steps * -1):
        # expand down
        lastchord.sort(reverse=True)
        for i, lc in enumerate(lastchord):
            lastchord.append((lastchord[-1][0] - (lc[0] - lastchord[i+1][0]), None))
            if len(lastchord) > (steps * -1):
                lastchord.sort()
                break
    # get reference pitch
    ref = (checkref(lastchord[steps][0], lb, ub), lastchord[steps][1])
    # translate chord into series of intervals
    intervals = []
    for i, c in enumerate(chord[:-1]):
        intervals.append((c[1], chord[i+1][0] - c[0], chord[i+1][1]))
    # make new chord
    newchord = [(ref[0], intervals[0][0])]
    for int in intervals:
        ref = (checkref(ref[0] + int[1], lb, ub), int[2])
        newchord.append(ref)
    newchord.sort()
    # check range
    if newchord[-1][0] > ub or newchord[0][0] < lb:
        print chord, lastchord, steps, lb, ub
    if timpano:
        # squash into proper range
        def f(p):
            return lb + ((p - lb) / 2)
        newchord = [(f(p), a) for p, a in newchord]
    return newchord

def transposesubsidiaries(s1, s2, previouschord, notespage, steps, lb, ub):
    """ transpose subsidiary pair with reference to previous events' chord
        s1, s2 (pitchnumbers), previouschord (sorted list of pitchnumbers),
        notespage (str), steps (int), lb (int), ub (int)
        s2 may be None """
    # previouschord must be at least two notes
    if len(previouschord) < 2:
        return False
    timpano = False
    if (ub - lb) < 11:
        # special case for timpano
        timpano = True
        ub = lb + 14
    # expand previouschord if it's not big enough for steps
    if len(previouschord) <= steps:
        # expand up
        for i, lc in enumerate(previouschord):
            previouschord.append(previouschord[-1] + previouschord[i+1] - lc)
            if len(previouschord) > steps:
                break
    elif len(previouschord) <= (steps * -1):
        # expand down
        previouschord.sort(reverse=True)
        for i, lc in enumerate(previouschord):
            previouschord.append(previouschord[-1] - (lc - previouschord[i+1]))
            if len(previouschord) > (steps * -1):
                previouschord.sort()
                break
    # get reference pitches
    ref = checkref(previouschord[steps], lb, ub)
    centralpitch = notes_pages_central_pitch[notespage]
    s1 = checkref(s1 - centralpitch + ref, lb, ub)
    # squash timpano notes into proper range
    def f(p):
        return lb + ((p - lb) / 2)
    if s2 is None:
        if timpano:
            return f(s1), None
        return s1, None
    elif s2 is not None:
        s2 = checkref(s2 - centralpitch + ref, lb, ub)
        if timpano:
            return f(s1), f(s2)
        return s1, s2

def instrumentrange(instrument, register):
    """ return range of instrument (tuple: lo, hi)
        instrument (Instrument), register (float) """
    if isinstance(instrument.range, list):
        # percussion instrument shouldn't be passed
        print 'Percussion passed to instrumentrange()'
        return False, False
    ilo = pitch2number(instrument.range[0][0], instrument.range[0][1])
    ihi = pitch2number(instrument.range[1][0], instrument.range[1][1])
    irange = ihi - ilo
    urange = int(math.sqrt(irange) * 2.5)
    if urange < 12:
        # do nothing with small ranges (timpano, crotales)
        return ilo, ihi
    olo = int((irange - urange) * register) + ilo
    ohi = olo + urange
    return olo, ohi

def electronicspitches(etype):
    """ return pitch for electronics staff """
    elecpitches = ["g", "a", "b", "c'", "d'", "e'", "f'"]
    return elecpitches[event_types[etype]]

def percussionpitches(components, pitches, register):
    """ assign pitches for percussion staff
        components (list of Notes), pitches (list of pitches),
        register (float) """
    # narrow pitches according to register
    if len(pitches) > 5 and register >= 0.66:
        pitches = pitches[-3:]
    elif len(pitches) > 5 and (0.33 < register < 0.66):
        pitches = pitches[1:4]
    elif len(pitches) > 5 and register < 0.33:
        pitches = pitches[:3]
    elif len(pitches) > 3 and register >= 0.5:
        pitches = pitches[-3:]
    elif len(pitches) > 3 and register < 0.5:
        pitches = pitches[:3]
    wastied = False
    todelete = []
    for i, note in enumerate(components):
        if note.ctype == 'rest':
            continue
        elif note.ctype == 'o':
            note.pitch = 'r'
        if wastied:
            note.pitch = 'r'
        else:
            pitch = random.choice(pitches)
            note.pitch = pitch2lily(pitch)
        if note.tied:
            # don't tie percussion
            note.tied = False
            wastied = True
        else:
            wastied = False
    todelete.sort(reverse=True)
    for td in todelete:
        del components[td]
    return components

def rellocation(location, negative):
    """ adjust location within positive or negative sections """
    if negative:
        location = (location - negativesection) / (1 - negativesection) 
    else:
        location = location / negativesection
    return min(1, location)

def picktimbre(timbre, instrument, location, negative):
    """ return timbre tuple for this event """
    location = rellocation(location, negative)
    # get timbre list
    if timbre == 'free':
        timbre = random.choice(['hard sound',
            'soft sound', 'hard noise', 'soft noise',
            'hard sound-noise', 'soft sound-noise'])
    tlist = instrument.timbre[timbre]
    tt = int((len(tlist) - 1) * location)
    if len(tlist) > 0:
        return tlist[tt]
    else:
        return ('', '', '', '', '')

def pickquality(quality, instrument, location, negative):
    """ return quality tuple for this event """
    location = rellocation(location, negative)
    # get quality list
    if quality is None:
        return ('', '', '', '', '')
    elif quality == 'combination':
        quality = random.choice(['muted', 'accent', 'accent reverb',
            'periodic', 'aperiodic'])
    qlist = instrument.quality[quality]
    qq = int((len(qlist) - 1) * location)
    if len(qlist) > 0:
        return qlist[qq]
    else:
        return ('', '', '', '', '')

def lyrics(timbre, length):
    if length == 0:
        return ''
    if timbre == 'free':
        timbre = random.choice(['hard sound',
            'soft sound', 'hard noise', 'soft noise',
            'hard sound-noise', 'soft sound-noise'])
    syllable = random.choice(peace.syllables[timbre])
    return syllable + ' '

def percsticks(hsf):
    """ hard or soft sticks """
    if hsf not in ['hard', 'soft']:
        hsf = random.choice(['hard', 'soft'])
    return '^\\%ssticks' % hsf

def gtrtone(timbre):
    """ guitar tone """
    if timbre == 'free':
        timbre = random.choice(['hard sound',
            'soft sound', 'hard noise', 'soft noise',
            'hard sound-noise', 'soft sound-noise'])
    if timbre in ['hard sound', 'soft sound']:
        return '^\\gtrnorm'
    elif timbre in ['hard noise', 'soft noise']:
        return '^\\gtrharsh'
    else:
        return '^\\gtrsmooth'

def perctimbrequality(timbre, quality, components, location, negative, ilist):
    """ apply timbre and quality to percussion components """
    location = rellocation(location, negative)
    if timbre == 'free':
        timbre = random.choice(['hard sound',
            'soft sound', 'hard noise', 'soft noise',
            'hard sound-noise', 'soft sound-noise'])
    wastied = False
    for i, nn in enumerate(components):
        if nn.pitch == 'r' or wastied:
            wastied = nn.tied
            continue
        if quality == 'combination':
            quality = random.choice(['muted', 'accent', 'accent reverb',
                'periodic', 'aperiodic'])
        for instrument in ilist:
            if lily2pitches(nn.pitch)[0] in instrument.range:
                tlist = instrument.timbre[timbre]
                if quality is None:
                    qlist = []
                else:
                    qlist = instrument.quality[quality]
        tt = int((len(tlist) - 1) * location)
        qq = int((len(qlist) - 1) * location)
        if len(tlist) > 0:
            nn.articulation += tlist[tt][2]
        if len(qlist) > 0:
            nn.articulation += qlist[qq][2]
        wastied = nn.tied
    return components

def accessorypitches(csorder, register, lo, hi):
    """ return list of possible pitches for accessories along with
        altered order of events (if no suitable pitches available
        csorder (str), location (float), register (float),
        lo (int), hi (int) """
    if not set(csorder) & set('brBSATau'):
        # no accessories required for this event
        return csorder, None
    if set(csorder) & set('rBSTu'):
        pass
    absreg = int((register * 79) + 10)
    if lo > absreg or hi < absreg - 9:
        # remove accessories from csorder
        csorder = csorder.replace('b', '').replace('r', 's')
        csorder = csorder.replace('B', 'C').replace('S', 'R')
        csorder = csorder.replace('A', '').replace('T', 'v')
        csorder = csorder.replace('a', '').replace('u', 't')
        return csorder, None
    pitches = range(max(lo, absreg - 9), min(hi, absreg) + 1)
    return csorder, pitches

## functions for dealing with beats, durations, rhythms
def divideevent(beats, duration):
    """ allocate beats proportionally to an event and its rest
        beats (int), duration tuple(event (float), rest (float)) """
    e_duration, r_duration = duration
    if r_duration == 0:
        # if rest duration is zero, allocate all beats to event
        return (beats, 0)
    if beats == 1:
        # can't subdivide further, pick which to allocate to
        if e_duration > r_duration:
            return (beats, 0)
        elif e_duration < r_duration:
            return (0, beats)
        else:
            return random.choice(((beats, 0), (0, beats)))
    e_prop = e_duration / sum(duration)
    e_beats = int(round(beats * e_prop))
    r_beats = beats - e_beats
    return (e_beats, r_beats)

def barlinescrossed(start, length, bars):
    """ returns a list of barlines crossed from start beat
        start (int) - starting beat
        length (int) - number of beats
        bars (list) - score.bars """
    barlines = []
    beginsbar = False
    for b in bars:
        if b.start > start:
            # bar starts after event starts
            if b.start > ( start + length ):
                # bar starts after event ends
                break
            else:
                # bar ends during event
                barlines.append(b.start)
        elif b.start == start:
            # if the event starts a bar
            beginsbar = True
    return barlines, beginsbar

def beats2noteval(start, length, bars):
    """ convert 32nd beats to lilypond note value
        start (int) - starting beat
        length (int) - number of beats
        bars (list) - score.bars """
    notevals = []
    # make list of barlines that the event crosses
    barlines, beginsbar = barlinescrossed(start, length, bars)
    # add end of event to barline list
    barlines.append(start + length)
    wndict = {64:'\\breve',
            56:'1..', 48:'1.', 32:'1',
            28:'2..', 24:'2.', 16:'2',
            14:'4..', 12:'4.', 8:'4',
            7:'8..', 6:'8.', 4:'8',
            3:'16.', 2:'16', 1:'32'}
    wn = wndict.keys()
    wn.sort(reverse=True)
    for bl in barlines:
        beats = bl - start
        start += beats
        components = []
        # use up all of the beats to the next barline with wn values
        while beats > 0:
            for w in wn:
                if beats >= w:
                    components.append(w)
                    beats -= w
        # beats should never become negative
        if beats != 0:
            print 'Barlines: %s (%s), components: %s, start: %s' % \
                    (barlines, bl, components, start)
            raise 'This shouldn\'t happen!'
        if beginsbar:
            # at start of bar sort downwards - long notes first
            pass
        else:
            # in middle of bar sort upwards - short notes first
            components.sort()
            # reset to start of bar as we've reached a barline
            beginsbar = True
        for c in components:
            notevals.append((R(c), wndict[c]))
    return notevals

def eventtempo(current_tempo, elapsed_proportion):
    """ calculate an ideal tempo for this event
        current_tempo (int), elapsed_proportion (float) """
    tempo_coefficient = eventduration_f(elapsed_proportion)
    tempo = int((((1 - tempo_coefficient) * 72) + 72) / 4 ) * 4
    # test that tempo varies enough
    try:
        tempo_variance = abs((current_tempo / float(tempo)) - 1)
        if tempo_variance <= minimum_tempo_variance:
            tempo = current_tempo
    except ZeroDivisionError:
        pass
    # check that tempo is in range 70-140
    if tempo < 72:
        tempo = 72
    elif tempo > 140:
        tempo = 140
    return tempo

def seconds2beats(tempo, duration):
    """ approximate a duration in beats at given tempo
        tempo (int) quavers per minute, duration (float) seconds """
    # convert tempo to 32nd notes per second
    tempo = tempo * 4 / float(60)
    beats = int(round(tempo * duration))
    if beats == 0:
        beats = 1
    return beats

def beats2seconds(tempo, beats):
    """ convert beats to elapsed time at given tempo
        tempo (int) quavers per minute, beats (int) 32nd notes """
    # convert tempo to 32nd notes per second
    tempo = tempo * 4 / float(60)
    return beats / tempo

def beatelapsed(beat, bars, sections):
    """ calculate elapsed time of a specific beat """
    et = 0
    # sum et of bars prior to beat
    for b in bars:
        b_tempo = sections[b.section].tempo
        if b.start + b.length < beat:
            # if bar ends before this beat, add duration of whole bar
            et += beats2seconds(b_tempo, b.length)
        else:
            # just add the beats in this bar and stop
            et += beats2seconds(b_tempo, beat - b.start)
            break
    return et

def concurrentevents(beat, score):
    """ return list of event numbers in each layer that occur at a given point """
    evs = []
    for l in score.layers:
        # add the last event in the layer
        evs.append(len(l.events) - 1)
        for e in l.events:
            if e.start > beat:
                # if we find an event that starts after this beat, replace with
                # the event number of the event before it
                evs[l.layernumber] = e.index - 1
                break
    return evs

## convert irrational to lilypond tuplet - accepts a tuple(num, den)
def irrational2lily(irrational):
    # get first power of 2 <= denominator
    i = 6 # fastest notes 256ths!
    while i >= 0:
        beat_length = 2 ** i
        if beat_length <= irrational[1]: break
        i = i - 1
    note_values = 2 ** ( i + 2 )
    if irrational[1] > 2:
        note_lyvalue = ['\\times ' + str(beat_length) + '/' + str(irrational[1])]
    else:
        note_lyvalue = [0]
    # how many?
    if irrational[0] == 1:
        note_lyvalue.append(str(note_values))
    elif irrational[0] == 2:
        note_lyvalue.append(str( note_values / 2 ))
    elif irrational[0] == 3:
        note_lyvalue.append(str( note_values / 2 ) + '.')
    elif irrational[0] == 4:
        note_lyvalue.append(str( note_values / 4 ))
    elif irrational[0] == 5:
        note_lyvalue.extend([str( note_values / 4 ), str(note_values)])
    elif irrational[0] == 6:
        note_lyvalue.append(str( note_values / 4 ) + '.')
    elif irrational[0] == 7:
        note_lyvalue.append(str( note_values / 4 ) + '..')
    elif irrational[0] == 8:
        note_lyvalue.append(str( note_values / 8 ))
    elif irrational[0] == 9:
        note_lyvalue.extend([str( note_values / 8 ), str(note_values)])
    elif irrational[0] == 10:
        note_lyvalue.extend([str( note_values / 8 ), str( note_values / 2 )])
    else:
        print "Problem!!"
    return note_lyvalue

def eventscoremultiplier(change_duration, relative_duration, pmvalue):
    """ calculate event's duration multiplier from its degree of change and
        the rest following it """
    # vary by degree of change
    # normally in the range -4 to 4; occasionally -14 to 14
    # return a multiplier to alter event by up to 5 times longer or shorter (i.e. 0.2->5)
    # [-14:0:14] = [0.2:1:5] - using two linear equations
    if change_duration < 0:
        m = 1.0 / 14.0 #0.8 / 14.0
        b = 1
    elif change_duration >= 0:
        m = 2.5 / 14.0 #4.0 / 14.0
        b = 1
    scoremultiplier = m * change_duration + b
    # add rest, if any
    if relative_duration == 'long rest':
        restmultiplier = random.uniform(0.6, 0.9)
    elif relative_duration == 'medium rest':
        restmultiplier = random.uniform(0.3, 0.6)
    elif relative_duration == 'short rest':
        restmultiplier = random.uniform(0.0, 0.3)
    else:
        restmultiplier = 0
    return scoremultiplier, restmultiplier 

def eventduration_f(elapsed_proportion):
    """ returns relative event length as a function of location in the piece """
    # f(x) = ax^0 + bx^1 + cx^2 + dx^3 + ex^4 + fx^5 + gx^6 ...
    # cropping: multiply proportion by cc to compensate for cropping in loop7
    evdur = 0
    power = 0
    cc = 1.10
    for coefficient in coefficients['durations']:
        evdur += coefficient * ( ( elapsed_proportion * cc ) ** power )
        power += 1
    #evdur = abs(evdur)
    # fit in bounds [0.1:1]
    #evdur = ( evdur * 0.9 ) + 0.1
    if evdur < 0.1: evdur = 0.1
    elif evdur > 0.9999: evdur = 0.9999
    return evdur

def eventduration(position, layerduration, scoremultiplier, restmultiplier):
    """ calculate an event's duration in seconds """
    dur = eventduration_f( position / layerduration ) \
            * scoremultiplier * (1 + restmultiplier)
    dur = ( dur * target_duration ) / layerduration
    Rduration = dur - ( dur / ( 1 + restmultiplier ) )
    Eduration = dur - Rduration
    return Eduration, Rduration

def eventdynamic(elapsed_proportion, change):
    """ returns dynamic as a function of location in the piece """
    # calculate absolute dynamic
    dyn = 0
    power = 0
    for coefficient in coefficients['dynamic_absolute']:
        dyn += coefficient * ( elapsed_proportion ** power )
        power += 1
    # alter by degree of change
    dyn += change / 14.0
    # calculate dynamic spread
    spread = 0
    power = 0
    for coefficient in coefficients['dynamic_relative']:
        spread += coefficient * ( elapsed_proportion ** power )
        power += 1
    # select float from available range
    dyn = random.uniform(dyn - spread / 2.5, dyn + spread / 2.5)
    # keep within bounds
    if dyn < 0:
        dyn = 0
    elif dyn >= 1:
        dyn = 0.99
    return dyn

def eventregister(elapsed_proportion):
    """ returns register as a function of location in piece """
    # calculate absolute register
    reg = 0
    power = 0
    for coefficient in coefficients['register_absolute']:
        reg += coefficient * ( elapsed_proportion ** power )
        power += 1
    # calculate register spread
    spread = 0
    power = 0
    for coefficient in coefficients['register_relative']:
        spread += coefficient * ( elapsed_proportion ** power )
        power += 1
    # select float from available range
    reg = random.uniform(reg - spread / 2.5, reg + spread / 2.5)
    # keep within bounds
    if reg < 0:
        reg = 0
    elif reg >= 1:
        reg = 0.99
    return reg

def eventactivity(elapsed_proportion):
    """ return activity as a function of location in piece """
    # calculate absolute activity
    act = 0
    power = 0
    for coefficient in coefficients['activity_absolute']:
        act += coefficient * ( elapsed_proportion ** power )
        power += 1
    # calculate activity spread
    spread = 0
    power = 0
    for coefficient in coefficients['activity_relative']:
        spread += coefficient * ( elapsed_proportion ** power )
        power += 1
    # select float from available range
    act = random.uniform(act - spread / 2.5, act + spread / 2.5)
    # keep within bounds
    if act < 0:
        act = 0
    elif act >= 1:
        act = 0.99
    return act

def eventconsonance(elapsed_proportion, type='inter'):
    """ return consonance score as a function of location in piece """
    cfs = coefficients['consonance_%s' % type]
    # calculate score
    cons = 0
    power = 0
    for coefficient in cfs:
        cons += coefficient * ( elapsed_proportion ** power )
        power += 1
    # keep within bounds
    if cons < 0:
        cons = 0
    elif cons >= 1:
        cons = 0.99
    return cons

def eventwords(elapsed_proportion, startletter, vowel):
    """ pick words for an event
        elapsed_proportion (float) [0:1],
        startletter (str) one character lowercase
        vowel (str) one character lowercase """
    # progression from the least common to most common
    f = int((1 - elapsed_proportion) * 27) + 1
    wfile = open('words/pmwords_%s' % f, 'r')
    wlines = wfile.readlines() # have to read it all as we may go backwards
    # find lines either side of start letter
    slindex = ord(startletter)
    sline, eline = 0, 0
    for i, line in enumerate(wlines):
        if ord(line[0]) < slindex:
            sline = i # - 1
            eline = i # + 1
        elif ord(line[0]) > slindex:
            eline = i #+ 1
            break
    if eline == sline: eline += 1
    words = []
    for line in wlines[sline:eline]:
        for word in line.split():
            words.append((word.count(vowel), word))
    words.sort(reverse=True)
    if len(words) > 10:
        words = words[:10]
    #return words, f, sline, eline 
    return [w for _, w in words]

def factorial(x):
    """ returns the factorial of x (int) """
    if x < 2:
        return 1
    return reduce(operator.mul, xrange(2, x+1))

def permutations(items, n=False):
    """ generate permutations of length n from items """
    if n is False:
        n = len(items)
    if n == 0:
        yield []
    else:
        for i in xrange(len(items)):
            for pp in permutations(items[:i] + items[i + 1:], n - 1):
                yield [items[i]] + pp

def combinations(items, n=False):
    """ generate combinations of length n from items """
    if n is False:
        n = len(items)
    if n == 0:
        yield []
    else:
        for i in xrange(len(items)):
            for cc in combinations(items[i + 1:], n - 1):
                yield [items[i]] + cc

def cartesianproduct(items, n=False):
    """ generate cartesian product of length n from items """
    if n is False:
        n = len(items)
    if n == 0:
        yield []
    else:
        for i in xrange(len(items)):
            for cp in cartesianproduct(items, n - 1):
                yield [items[i]] + cp

## list irrational ranges
def irrationalranges(denominators):
    # list fractions
    fractions = []
    for denominator in denominators:
        i = 1
        while i < denominator:
            f = i / float(denominator)    # force floating-point numbers!
            fractions.append([f, i, denominator])
            i += 1
    fractions.append([1, 1, 1])
    fractions.append([0, 0, 1])
    fractions.sort(cmp)
    # calculate irrational ranges
    # [(max, num, den), ...]
    irrational_ranges = []
    i = 0
    while i < len(fractions):
        try:
            max_bound = ( fractions[i][0] + fractions[i+1][0] ) / float(2)
        except:
            max_bound = ( fractions[i][0] + 1 ) / float(2)
        irrational_ranges.append([max_bound, fractions[i][1], fractions[i][2]])
        i += 1
    return irrational_ranges

## allocate degrees of change to parameters: register, dynamic, duration
def allocatechange(symbols):
    page = symbols['page']
    number = symbols['number']
    change_1 = symbols['change_1']
    change_2 = symbols['change_2']
    # add a zero for the third unchanged parameter
    changes = [change_1, change_2, 0]
    # additional rules from symbols pages
    if page == 'A':
        # no additional rules
        pass
    elif page == 'B':
        if number == 8 or number == 9 or number == 13 or number == 39 or number == 41:
            # add 7 and -7 to possible changes
            changes.extend([-7, 7])
    elif page == 'C':
        if change_1 == 2 or change_2 == 2:
            # "two <2s may be replaced by <14,"
            # there are 21 <2s
            # so we add 18 <2s and 2 <14s (1 + 18 + 2 = 21)
            changes.extend([2] * 18 + [14] * 2)
            # "but if so, the degree of change of the following event refers to the symbols previous to the <14"
            # no idea how I can implement this rule!
    elif page == 'D':
        if change_1 == 1 or change_2 == 1:
            # "<1 may be replaced once by <7 or <14"
            # there are 8 <1s
            seven_or_fourteen = random.choice((7, 14))
            changes.extend([1] * 6 + [seven_or_fourteen])
    elif page == 'E':
        if change_1 == -3 or change_2 == -3:
            # "3> may be replaced twice by 7>"
            # there are 21 3>s
            changes.extend([-3] * 18 + [-7] * 2)
        if change_1 == 1 or change_2 == 1:
            # "<1 may be replaced once by <7"
            # there are 13 <1s
            changes.extend([1] * 11 + [7])
    elif page == 'F':
        if change_1 == 3 or change_2 == 3:
            # "one <3 may be replaced by <9"
            # there are 21 <3s
            changes.extend([3] * 19 + [9])
        if change_1 == -4 or change_2 == -4:
            # "one 4> may be replaced by 12>"
            # there are 13 >4s
            changes.extend([-4] * 11 + [-12])
        if change_1 == 3 or change_2 == 3:
            # "one <4 may be replaced by <12"
            # there are 13 <4s
            changes.extend([4] * 11 + [12])
    elif page == 'G':
        if number == 5 or number == 27 or number == 47:
            # "<1 may be replaced by <7 or <14"
            changes.extend([7] + [14] + [1] * 3)
        if number == 6 or number == 28 or number == 48:
            # "1> may be replaced by 7> or 14>"
            changes.extend([-7] + [-14] + [-1] * 3)
    # shuffle
    random.shuffle(changes)
    # trim to three items and return as tuple(change_register, change_dynamic, change_duration)
    return tuple(changes[:3])

## select events to fill empty events
def fillempty(event_number, event_page, EVENT_LIST, symbol_pages):
    # get previous and next pages
    for p in range(0, len(symbol_pages)):
        if symbol_pages[p] == event_page:
            event_page = p
            page_before = symbol_pages[p - 1]
            try:
                page_after = symbol_pages[p + 1]
            except IndexError:
                page_after = symbol_pages[p + 1 - 7]
            continue
    # decide whether to do a replacement
    replace = random.choice((True, False))
    if replace:
        # get bold events from pages before and after
        replacement_possibilities = []
        event_number = 0
        for EVENT in EVENT_LIST:
            try:
                if (EVENT.symbols['bold'] == 'bold' and
                        (EVENT.symbols['page'] == page_before or 
                        EVENT.symbols['page'] == page_after)):
                    replacement_possibilities.append(event_number)
            except AttributeError:
                print EVENT.symbols
            event_number += 1
        # choose one of the possibilities
        random.shuffle(replacement_possibilities)
        try:
            replace = replacement_possibilities[0]
        except IndexError:
            replace = False
    return replace

def randomlayer(currentlayer):
    """ choose a random layer other than the current layer """
    layers = range(number_of_layers)
    layers.remove(currentlayer)
    return random.choice(layers)

def findnextevent(beat, layer, layers):
    """ find the next event in another layer
        beat (int) - point to start looking
        layer (int) - don't look in this layer
        layers (list) """
    found = False
    foundevents = []
    for l in layers:
        if l.layernumber == layer:
            continue
        for e in l.events:
            try:
                if e.start >= beat and (e.start - beat) < 20:
                    foundevents.append((e.start, e.length))
                    found = True
            except AttributeError:
                break
    # sort found events to get first one
    foundevents.sort()
    if found:
        return foundevents[0]
    else:
        return found

def notearticulation(articulation):
    if articulation in ['accent', 'accent_slur']:
        return '->'
    elif articulation in ['accent_staccato', 'accent_from_slur']:
        return '-.->'
    else:
        return ''

def subsidiaryposition(csorder, subpos, instrumentname):
    """ fit subsidiary notes into event component order """
    # instrument special cases
    if instrumentname in ['speaker', 'electronics']:
        # play only central sounds
        csorder = csorder.replace('b', 'o').replace('B', 'C')
        csorder = csorder.replace('A', 'o').replace('a', 'o')
        subpos = None
    # fit subsidiaries
    if subpos == 'before':
        if 'b' in csorder:
            csorder = csorder.replace('b', 'r')
        else:
            csorder = 's' + csorder
    elif subpos == 'during':
        if 'C' in csorder:
            csorder = csorder.replace('C', 'R')
        elif 'B' in csorder:
            csorder = csorder.replace('B', 'S')
        elif 'A' in csorder:
            csorder = csorder.replace('A', 'T')
    elif subpos == 'after':
        if 'a' in csorder:
            csorder = csorder.replace('a', 'u')
        else:
            csorder += 't'
    return csorder

def allocateattacks(attacknumber, csorder, snum):
    """ parse the component order, accessories length,
        and subsidiary notes contour and allocate the attacks to each component
        attacknumber (int), csorder (str), snum (int) """
    # assign proportions to components
    raw, tot, slen = [], 0, False
    # component weighting:
    for z in csorder:
        # rest                              0.8-1.2
        if z == 'o':
            alen = random.uniform(0.8, 1.2)
            raw.append((z, alen))
            tot += alen
        # accessory alone                   1.0-1.3
        elif z in 'bAa':
            alen = random.uniform(1.0, 1.3)
            raw.append((z, alen))
            tot += alen
        # subsidiary alone, or with acc     1-3.63 y=((x-1)/1.9)+1
        elif z in 'srTtuv':
            slen = ((snum - 1) / 1.9) + 1
            raw.append((z, slen))
            tot += slen
        # central sound alone, or with acc  3.1
        elif z in 'CB':
            raw.append((z, 3.1))
            tot += 3.1
        # central sound + sub and/or acc    subs + 2.1
        elif z in 'RS':
            if z == 'R': z, zsub = 'C', 'v'
            if z == 'S': z, zsub = 'B', 'v'
            cslen1 = random.uniform(0.1, 2.0)
            cslen2 = 2.1 - cslen1
            slen = ((snum - 1) / 1.9) + 1
            raw.append((z, cslen1))
            raw.append((zsub, slen))
            raw.append((z, cslen2))
            tot += slen + cslen1 + cslen2
    # now divide by cumulative total and multiply by number of attacks
    allocation, tattacks = [], 0
    missed_out = []
    for z, Z in raw:
        att = int(round((Z / float(tot)) * attacknumber))
        if att == 0: missed_out.append(Z)
        allocation.append((z, att, Z))
        tattacks += att
    if tattacks < attacknumber and len(missed_out) > 0:
        # rounding error down, assign difference to longest component that
        # missed out
        missed_out.sort(reverse=True)
        tdiff = attacknumber - tattacks
        for z, r in enumerate(allocation):
            if r[2] == missed_out[0]:
                allocation[z] = (r[0], r[1] + tdiff, r[2])
                break
    elif tattacks > attacknumber:
        # rounding error up, remove shortest attacks
        killlist = [(raw, z, r) for z, r, raw in allocation]
        killlist.sort()
        tdiff = tattacks - attacknumber
        for raw, z, r in killlist:
            a = allocation.index((z, r, raw))
            if r > tdiff:
                # subtract difference
                allocation[a] = (z, r - tdiff, raw - tdiff)
                break
            elif r == tdiff:
                del allocation[a]
                break
            elif r < tdiff:
                del allocation[a]
                tdiff -= r
    allocation = [(z, r) for z, r, _ in allocation]
    return allocation

def attackproportions(location, component, attacks, subscontour, quality):
    """ calculate proportional durations for each attack in the event
        location (float), component (str), attacks (int), 
        subscontour (str), quality (str) """
    periodicy = False
    # allocate duration weight
    if subscontour is not None:
        snum = len(subscontour)
    subs = False
    if component == 'o': # rest
        dur = 2 # weight rests
    elif component in 'bAa': # accessory alone
        # accessories get proportionally longer throughout the piece
        dur = (location * 1.8) + 1
    elif component in 'srtu': # subsidiary, or sub+acc before, after
        dur = (snum - 1)/1.9 + 1
        subs = True
    elif component in 'vT': # subsidiary, or sub+acc during
        dur = (snum - 1)/1.8 + 1
        subs = True
    elif component in 'CB': # cs, or cs+acc
        dur = 3.5
        if quality == 'periodic' and attacks < 3: 
            periodicy = 1
        elif quality == 'periodic' and attacks < 5:
            periodicy = 2
        elif quality == 'periodic':
            periodicy = 3
    elif component in 'RS': # cs+sub, cs+acc+sub
        raise 'Components R and S should not be here!'
    if subs:
        return subsidiarycontour(dur, component, attacks, subscontour)
    # calculate complexity value:
    # 0-0.25: cos(2πx)/2 + 0.5
    # 0.25-1: sin(2πx + 3π/2)/2 + 0.5
    if location <= 0.25 and periodicy != 1:
        complexity = math.cos(2 * math.pi * location) / 2.0 + 0.5
        dmax, dmin = 1 + complexity, 1 - complexity
    elif periodicy != 1:
        complexity = math.sin(2 * math.pi * location + (3 * math.pi) / 2.0 ) / 2.0 + 0.5
        dmax, dmin = 1 + complexity, 1 - complexity
    # complexity controls difference in possible rhythmic values: 
    # 0=uniform, 1=very different
    proplist = []
    for a in xrange(attacks):
        if periodicy == 1:
            prop = dur / float(attacks)
        elif periodicy == 2 or periodicy == 3:
            if a % periodicy == 0:
                prop = (dmin * dur) / float(attacks)
            elif a % periodicy == 1:
                prop = (dmax * dur) / float(attacks)
            elif a % periodicy == 2:
                prop = dur / float(attacks)
        else:
            prop = (random.uniform(dmin, dmax) * dur) / float(attacks)
        proplist.append((component, prop))
    # shouldn't return empty list
    return proplist

def subsidiarycontour(dur, component, attacks, subscontour):
    """ calculate relative durations of subsidiary notes according to contour
        in score. dur (float), component (str), attacks (int), subscontour (str) """
    subsc = [int(s) for s in subscontour]
    smin, smax = min(subsc), max(subsc)
    span = float(smax - smin)
    if span == 0:
        subsc = [1.0 for s in subsc]
    else:
        subsc = [((9 - s) / span) * 2 + 1 for s in subsc]
    if attacks < len(subscontour):
        notes = len(subscontour)
    else:
        notes = attacks
    snotes = []
    for n in xrange(notes):
        d = subsc[int(n*len(subscontour)/notes)]
        snotes.append((d, n))
    # assign gracenotes, if any
    if attacks < len(subscontour):
        snotes.sort()
        for n in xrange(len(subscontour) - attacks):
            try:
                snotes[n] = (0, snotes[n][1])
            except IndexError:
                print snotes, subscontour, attacks
                raise 'Stop'
    tot = sum([n for n, _ in snotes])
    # calculate final relative durations and reorder
    snotesdur = [(component, 0)] * len(snotes)
    if tot > 0:
        for n, i in snotes:
            snotesdur[i] = (component, (n * dur) / float(tot))
    return snotesdur

def denominators(numerator):
    """ make a list of tuplets denominators for a given numerator """
    # all tuplets will be in 32nd notes, 8:6 can be simplified later to 4:3
    denominators = []
    if numerator < 5:
        return denominators
    elif numerator < 11 or (numerator < 17 and numerator % 2 == 0):
        denominator = numerator + 1
        while denominator < numerator * 2:
            if denominator <= 12 or \
                    (denominator <= 22 and denominator % 2 == 0) or \
                    (denominator % 3 == 0 and numerator % 3 == 0) or \
                    (denominator % 4 == 0 and numerator % 4 == 0):
                denominators.append(denominator)
            denominator += 1
    return denominators

def notevallist(currentTuplet=None, maxTuplet=16):
    """ make a sorted list of all available beat lengths
        from minNoteVal to maxNoteVal """
    if currentTuplet is None:
        tupletlist = [(1, 1)]
        for numerator in xrange(minTuplet, int(float(maxTuplet)) + 1):
            denoms = denominators(numerator)
            if denoms:
                for d in denoms:
                    tupletlist.append((numerator, d))
    else:
        tupletlist = [(currentTuplet.numerator, currentTuplet.denominator)]
    notevals = []
    for num, den in tupletlist:
        for x in [xx for xx in xrange(1, 33)]:
            if x <= den * 2 or den == 1:
                len = R((x * num), den * 2)
                if len <= maxTuplet:
                    notevals.append((len, x, num, den))
    notevals.sort()
    return notevals

def quantizerhythm(start, attacklengths, activity, bars, maxgrace):
    """ quantize a list of attacks into rhythmic values, returns a
        list of Note instances
        start (int) - start beat
        attacklengths (list) - ctype (str), length (float)
        activity (float), bars (list) - score.bars """
    # get barlines
    tlength = int(round(sum([l for c, l in attacklengths]), 4))
    eventend = start + tlength
    barlines, startsbar = barlinescrossed(start, tlength, bars)
    # we need to add the end of the event to the barline list enough times
    # for all the attacks to be gracenotes
    barlines += [eventend] * len(attacklengths)
    gracesallowed = min(int((activity * 3) + 0.5), maxgrace)
    quantnotes = []
    tuplet = None
    cursor = R(start)
    nextbarline = barlines.pop(0)
    minnoteval = minNoteVal
    component, length = attacklengths.pop(0)
    while True:
        # deal with gracenotes first
        if length < minnoteval / 2.0 or cursor + minnoteval / 2.0 > eventend:
            quantnotes.append(plusminus.Note(component, cursor, 0, 'g', tuplet=tuplet))
            if len(attacklengths) > 0:
                attacklengths = spreaderror(attacklengths, length)
            try:
                component, length = attacklengths.pop(0)
            except IndexError:
                break
            continue
        space = nextbarline - cursor
        notevals = notevallist(tuplet, space)
        closest = 1000000
        for noteval in notevals:
            diff = abs(length - noteval[0])
            if diff < closest:
                closest = diff
                closestnoteval = noteval
            elif diff > closest:
                break
        # is chosen match a new tuplet?
        if tuplet is None and closestnoteval[3] != 1:
            tuplet = plusminus.Tuplet(cursor, closestnoteval[2], closestnoteval[3])
            tupletremaining = closestnoteval[3] * 2
            startsbar = True
            # end of tuplet is effectively next barline
            if nextbarline > cursor + closestnoteval[2]:
                barlines.insert(0, nextbarline)
                nextbarline = cursor + closestnoteval[2]
        # will this attack finish the current tuplet?
        minnoteval = 0.5
        # how much of the attack has been used?
        remain = length - closestnoteval[0]
        if remain < minnoteval / 2.0:
            # length (effectively) used up - we don't want to tie to a gracenote
            tied = False
        else:
            tied = True
        # make note
        wndict = {64:'1', 58:'2...', 56:'2..', 48:'2.', 32:'2', 
                30:'4...', 28:'4..', 24:'4.', 16:'4',
                15:'8...', 14:'8..', 12:'8.', 8:'8',
                7:'16..', 6:'16.', 4:'16', 
                3:'32.', 2:'32', 1:'64'}
        wn = wndict.keys()
        wn.sort(reverse=True)
        value = closestnoteval[1]
        values = []
        while value > 0:
            for w in wn:
                if value >= w:
                    values.append(w)
                    value -= w
        if startsbar is False:
            # at start of bar sort downwards - long notes first
            # in middle of bar sort upwards - short notes first
            values.sort()
        value = [(R(v, 2), wndict[v]) for v in values]
        qcursor = cursor
        ties = [True] * (len(values) - 1) + [tied]
        for i, v in enumerate(value):
            notelength = v[0] * R(closestnoteval[2], closestnoteval[3])
            quantnotes.append(plusminus.Note( \
                    component, qcursor, notelength, v[1], tuplet, ties[i]))
            qcursor += notelength
        # check tuplet
        if tuplet is not None:
            tupletremaining -= closestnoteval[1]
            if tupletremaining == 0:
                # if used up then reset
                tuplet = None
                del tupletremaining
                #print 'tuplet ended'
        if remain < minnoteval / 2.0 and len(attacklengths) > 0:
            # spread the difference across the rest of the attacks
            attacklengths = spreaderror(attacklengths, remain)
            try:
                component, length = attacklengths.pop(0)
            except IndexError:
                break
        elif remain >= minnoteval / 2.0:
            length = remain
        elif len(attacklengths) == 0:
            break
        # move cursor forwards    
        cursor = cursor + closestnoteval[0]
        if cursor == nextbarline:
            nextbarline = barlines.pop(0)
            startsbar = True
        else:
            startsbar = False
    # check number of gracenotes
    graces = []
    for i, n in enumerate(quantnotes):
        if n.length == 0:
            graces.append(i)
    if len(graces) > gracesallowed:
        todelete = random.sample(graces, len(graces) - gracesallowed)
        todelete.sort(reverse=True)
        for td in todelete:
            del quantnotes[td]
    return quantnotes

def spreaderror(attacklengths, remainder):
    divider = float(len(attacklengths))
    diff = remainder / divider
    newattacklengths = []
    for c, v in attacklengths:
        if v + diff > 0:
            v += diff
        else:
            v = 0
        newattacklengths.append((c, v))
    return newattacklengths

def silence(event, message):
    """ silence an event by converting it to a rest """
    event.rlength += event.elength
    event.elength = 0
    event.repetition = False
    event.subsnotes = False
    event.debug += message

def prettify(string):
    """ remove multiple spaces and newlines from a string """
    while '\n\n' in string:
        string = string.replace('\n\n', '\n')
    while '  ' in string:
        string = string.replace('  ', ' ')
    while ' \n' in string:
        string = string.replace(' \n', '\n')
    return string