-
Notifications
You must be signed in to change notification settings - Fork 0
/
counterPoint.py
469 lines (372 loc) · 14.3 KB
/
counterPoint.py
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
import random
from scoreMaker import scoreMaker
import math
#Create Fringe list
fringe = []
def formatter():
#Get cantus firmus from user
def userInput():
print("Enter a Cantus Firmus as notes seperated by commas")
userInput = input('>>>')
for note in userInput.split(","):
cantusFirmus.append(int(note))
cantusFirmus.printCantus()
userInput()
#-------------------------------------------------------------------------------
class Problem(object):
def __init__(self, initial, goal=None):
"""The constructor specifies the initial state, and possibly a goal
state, if there is a unique goal. Your subclass's constructor can add
other arguments."""
self.initial = initial; self.goal = goal
def result(self, state, mvmt=None):
self.state = state
state = state + 1
return state
def actions(self, state, interval, nodePath):
CanNote = cantusFirmus.cantusFirmus[state]
parentNode = nodePath[len(nodePath)-1]
self.interval = interval
intervals = []
if state == 0:
melodicPossibilities = [0,7,12,19,24]
for n in melodicPossibilities:
"test for in range"
if problem.in_range(CanNote, n):
intervals.append(n)
elif state <= 3:
melodicPossibilities = [3,4,7,8,9,12]
for n in melodicPossibilities:
"test for in range"
if problem.in_range(CanNote, n):
"test for parallel perfect intervals"
if problem.motion(parentNode, CanNote, n):
intervals.append(n)
elif state == len(cantusFirmus.cantusFirmus) - 1:
melodicPossibilities = [0,12,24]
for n in melodicPossibilities:
"test for in range"
if problem.in_range(CanNote, n):
intervals.append(n)
elif state == len(cantusFirmus.cantusFirmus) - 2:
melodicPossibilities = [4,9]
for n in melodicPossibilities:
"test for in range"
if problem.in_range(CanNote, n):
intervals.append(n)
else:
melodicPossibilities = [3,4,7,8,9,12]
for n in melodicPossibilities:
"test for in range"
if problem.in_range(cantusFirmus.getNote(state-1), n):
"test for parallel perfect intervals"
if problem.motion(parentNode, CanNote, n):
intervals.append(n)
return intervals
def goal_test(self, node):
"""Return True if the state is a goal. The default method compares the
state to self.goal, as specified in the constructor. Override this
method if checking against a single self.goal is not enough."""
if node.state >= cantusFirmus.size():
notes = []
for tempNode in node.path():
notes.append(tempNode.note)
if (notes.count(max(notes)) == 1):
return True
else:
return False
#---Counterpoint tests here
def highest_melody_test(self):
return True
def in_range(self, cantusNote, n):
if (n + cantusNote) <= 81:
return True
else:
return False
def consecutive_ns(self, interval, n):
gPNn = parentNode.interval
if n == gPNn:
return False
else:
return True
def motion(self, parentNode, canNote, n):
note = (canNote + n)
can = canNote
pNote = parentNode.note
pCan = parentNode.cantus
melodyMotion = (note - pNote)
cantusMotion = (can - pCan)
perfectNs = [0,7,12,19,24]
if cantusMotion < 0 and melodyMotion > 0:
return "contrary"
elif cantusMotion > 0 and melodyMotion < 0:
return "contrary"
elif cantusMotion == 0 and melodyMotion != 0:
return "oblique"
elif cantusMotion !=0 and melodyMotion == 0:
return "oblique"
elif cantusMotion > 0 and melodyMotion > 0:
"parallel"
if n in perfectNs:
return False
else:
return True
elif cantusMotion < 0 and melodyMotion < 0:
"parallel"
if n in perfectNs:
return False
else:
return True
#-------------------------------------------------------------------------------
class CantusFirmus(object):
def __init__(self, x):
self.name = x
self.cantusFirmus = []
self.minorSecond = None
self.majorSecond = None
self.minorThird = None
self.majorThird = None
self.perfectFourth = None
self.augmentedFourth = None
self.minorSixth = None
self.majorSixth = None
self.minorSeventh = None
self.majorSeventh = None
def append(self, note):
self.cantusFirmus.append(int(note))
def setCantus(self, cantusFirmus):
self.cantusFirmus = cantusFirmus
def printCantus(self):
print(self.cantusFirmus)
def getNote(self, i):
return self.cantusFirmus[i]
def size(self):
return len(self.cantusFirmus)
def find_qualities(self):
self.tonic = self.cantusFirmus[-1]
self.snd = self.cantusFirmus[-2]
#Find minor Third
for i in range(-21, 16, 12):
if ((self.tonic + i) in self.cantusFirmus):
self.minorThird = True
#Find major Third
for i in range(-20, 17, 12):
if ((self.tonic + i) in self.cantusFirmus):
self.majorThird = True
# If minor Third Exists
if self.minorThird:
# find m2
for i in range(-23, 14, 12):
if ((self.tonic + i) in self.cantusFirmus):
self.minorSecond = True
# find M2
for i in range(-22, 15, 12):
if ((self.tonic + i) in self.cantusFirmus):
self.majorSecond = True
self.find_seventh()
self.find_sixth()
# If major Third Exists
if self.majorThird:
# find P4
for i in range(-19, 18, 12):
if ((self.tonic + i) in self.cantusFirmus):
self.perfectFourth = True
# find +4
for i in range(-18, 19, 12):
if ((self.tonic + i) in self.cantusFirmus):
self.augmentedFourth = True
self.find_seventh()
self.find_sixth()
def find_seventh(self):
# find m7
for i in range(-14, 23, 12):
if ((self.tonic + i) in self.cantusFirmus):
self.minorSeventh = True
# find m7
for i in range(-13, 24, 12):
if ((self.tonic + i) in self.cantusFirmus):
self.majorSeventh = True
def find_sixth(self):
# find m6
for i in range(-16, 21, 12):
if ((self.tonic + i) in self.cantusFirmus):
self.minorSixth = True
# find m6
for i in range(-15, 22, 12):
if ((self.tonic + i) in self.cantusFirmus):
self.majorSixth = True
def find_mode(self):
self.modes = ['ionian', 'lydian', 'mixolydian', 'phrygian', 'minor', 'dorian', 'aeolian']
if self.minorThird:
self.modes.remove('ionian')
self.modes.remove('lydian')
self.modes.remove('mixolydian')
if self.minorSecond:
self.modes.remove('minor')
self.modes.remove('dorian')
self.modes.remove('aeolian')
elif self.majorSecond:
self.modes.remove('phrygian')
elif self.minorSeventh:
self.modes.remove('minor')
ww
if self.majorSixth:
self.modes.remove('dorian')
elif self.majorThird:
self.modes.remove('dorian')
self.modes.remove('phrygian')
self.modes.remove('aeolian')
self.modes.remove('minor')
if self.perfectFourth:
self.modes.remove('lydian')
if self.majorSeventh:
self.modes.remove('mixolydian')
elif self.minorSeventh:
self.modes.remove('ionian')
elif self.augmentedFourth:
self.modes.remove('ionian')
self.modes.remove('mixolydian')
elif self.minorSeventh:
self.modes.remove('ionian')
self.modes.remove('lydian')
#-------------------------------------------------------------------------------
class Node(object):
def __init__(self, state, interval=0, parent=None):
self.state = state
self.parent = parent
self.interval = interval
if (state == 0):
self.cantus = 0
self.note = 0
else:
self.cantus = cantusFirmus.getNote(self.state-1)
self.note = cantusFirmus.getNote(self.state-1) + interval
if parent:
self.depth = parent.depth + 1
else:
self.depth = 0
def __repr__(self):
return "<node " + repr(self.state) + "," + repr(self.cantus) + "," + repr(self.note) + "," + repr(self.interval) + ">"
def expand(self, problem):
"List the nodes reachable in one step from this node."
return [self.child_node(problem, action)
for action in problem.actions(self.state, self.interval, Node.path(self))]
def child_node(self, problem, action):
"Fig. 3.10"
next = problem.result(self.state)
return Node(next, action, self)
def path(self):
"Return a list of nodes forming the path from the root to this node."
node, path_back = self, []
while node:
path_back.append(node)
node = node.parent
return list(reversed(path_back))
def prettyCantus(self):
"return cantus firmus for lilypond"
return int((repr(self.cantus)))
def prettyCounter(self):
"return Counter Point for lilypond"
return int((repr(self.note)))
def Output(self, node):
"make local copy node path"
exercise = node.path()
"remove root node"
del exercise[0]
formatter = scoreMaker
for i in exercise:
z = (i.prettyCantus())
formatter.appendCantus(1, z)
for i in exercise:
z = (i.prettyCounter())
formatter.appendCounter(1, z)
formatter.write()
#______________________________________________________________________________
# Uninformed Search algorithms
def tree_search(problem, frontier):
"""Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
Don't worry about repeated paths to a state. [Fig. 3.7]"""
frontier.append(Node(problem.initial))
while frontier:
node = frontier.pop()
if problem.goal_test(node):
return node
print(node)
frontier.extend(node.expand(problem))
return None
def breadth_first_tree_search(problem):
"Search the shallowest nodes in the search tree first."
return tree_search(problem, FIFOQueue())
def depth_first_tree_search(problem):
"Search the deepest nodes in the search tree first."
return tree_search(problem, Stack())
#-------------------------------------------------------------------------------
class Queue:
"""Queue is an abstract class/interface. There are three types:
Stack(): A Last In First Out Queue.
FIFOQueue(): A First In First Out Queue.
PriorityQueue(order, f): Queue in sorted order (default min-first).
Each type supports the following methods and functions:
q.append(item) -- add an item to the queue
q.extend(items) -- equivalent to: for item in items: q.append(item)
q.pop() -- return the top item from the queue
len(q) -- number of items in q (also q.__len())
item in q -- does q contain item?
Note that isinstance(Stack(), Queue) is false, because we implement stacks
as lists. If Python ever gets interfaces, Queue will be an interface."""
def __init__(self):
abstract
def extend(self, items):
for item in items: self.append(item)
def Stack():
"""Return an empty list, suitable as a Last-In-First-Out Queue."""
return []
class FIFOQueue(Queue):
"""A First-In-First-Out Queue."""
def __init__(self):
self.A = []; self.start = 0
def append(self, item):
self.A.append(item)
def __len__(self):
return len(self.A) - self.start
def extend(self, items):
self.A.extend(items)
def pop(self):
e = self.A[self.start]
self.start += 1
if self.start > 5 and self.start > len(self.A)/2:
self.A = self.A[self.start:]
self.start = 0
return e
def __contains__(self, item):
return item in self.A[self.start:]
class PriorityQueue(Queue):
"""A queue in which the minimum (or maximum) element (as determined by f and
order) is returned first. If order is min, the item with minimum f(x) is
returned first; if order is max, then it is the item with maximum f(x).
Also supports dict-like lookup."""
def __init__(self, order=min, f=lambda x: x):
update(self, A=[], order=order, f=f)
def append(self, item):
bisect.insort(self.A, (self.f(item), item))
def __len__(self):
return len(self.A)
def pop(self):
if self.order == min:
return self.A.pop(0)[1]
else:
return self.A.pop()[1]
def __get__getitem__item__(self, key):
for _, item in self.A:
if item == key:
return item
def __delitem__(self, key):
for i, (value, item) in enumerate(self.A):
if item == key:
self.A.pop(i)
return
#Create CantusfFirmus Object
cantusFirmus = CantusFirmus('x')
problem = Problem(0)
formatter()