-
Notifications
You must be signed in to change notification settings - Fork 14
/
fingering_arrangement.py
executable file
·503 lines (392 loc) · 15.4 KB
/
fingering_arrangement.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
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
#!/usr/bin/env python
# encoding: utf-8
"""
Author: Yuan-Ping Chen
Data: 2016/03/15
-------------------------------------------------------------------------------
Fingering arrangement: automatically arrange the guitar fingering.
-------------------------------------------------------------------------------
Args:
input_files: files to be processed.
Only the .expression_style_note files would be considered.
output_dir: Directory for storing the results.
Optional args:
Please refer to --help.
-------------------------------------------------------------------------------
Returns:
Raw melody contour: Text file of estimated melody contour
in Hz with extenion of .raw.melody.
"""
import numpy as np
import os
import networkx as nx
class GuitarEvent(object):
def __init__(self, **kwargs):
# optional timing information
# timestamp start
self.ts_start = kwargs.get('ts_start')
# beat start
self.beat_start = kwargs.get('beat_start')
# beat duration
self.dur = kwargs.get('dur')
class Pluck(GuitarEvent):
def __init__(self, string, fret, **kwargs):
super(Pluck, self).__init__(**kwargs)
self.string = string
self.fret = fret
def distance(self, other):
'''
Get the distance between this pluck with a pluck or strum
'''
if isinstance(other, Pluck):
if self.fret == 0 or other.fret == 0:
distance = 0
else:
distance = self.fret - other.fret
elif isinstance(other, Strum):
other_frets = [p.fret for p in other.plucks]
min_other_frets = min(other_frets)
max_other_frets = max(other_frets)
if self.fret <= min_other_frets:
distance = min_other_frets - self.fret
elif self.fret >= max_other_frets:
distance = self.fret - max_other_frets
else:
distance = self.fret - (min_other_frets + max_other_frets)/2
else:
raise ValueError('Must compare to a pluck or strum')
return abs(distance)
def is_open(self):
'''
True if the pluck is an open string
'''
return self.fret == 0
def __eq__(self, other_pluck):
return self.string == other_pluck.string and self.fret == other_pluck.fret
def __str__(self):
return '<pluck: string: %d, fret: %d>' % (self.string+1, self.fret)
def __repr__(self):
return self.__str__()
class ScoreEvent(object):
def __init__(self, **kwargs):
# optional timing information
# onset timestamp
self.onset_ts = kwargs.get('onset_ts')
# offset timestamp
self.offset_ts = kwargs.get('offset_ts')
# beat start
self.beat_start = kwargs.get('beat_start')
# beat duration
self.dur = kwargs.get('dur')
class Note(ScoreEvent):
pitch_classes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
def __init__(self, pname, oct, **kwargs):
'''
pname {String}: pitch name
oct {Integer}: octave
kwargs is for passing in timing information
'''
super(Note, self).__init__(**kwargs)
# pitch class
if pname.upper() in Note.pitch_classes:
self.pname = pname.upper()
else:
raise ValueError('Invalid pitch name')
# octave
self.oct = oct
def toMidi(self):
'''
Convert the pitch name and octave to a MIDI note number
between 0 and 127
'''
p_ind = Note.pitch_classes.index(self.pname)
num_chroma = len(Note.pitch_classes)
midi = (self.oct-1)*num_chroma + 24 + p_ind
if midi >= 0 and midi <= 127:
return midi
else:
return None
def __add__(self, step):
'''
Add an integer number of semitones to the note
'''
num_chroma = len(Note.pitch_classes)
step_up = True
if step < 0:
step_up = False
note = Note(self.pname, self.oct, self.id)
p_ind = Note.pitch_classes.index(self.pname)
new_p_ind = (p_ind + step) % num_chroma
note.pname = Note.pitch_classes[new_p_ind]
oct_diff = int(step / 12)
note.oct = self.oct + oct_diff
if oct_diff == 0:
if step_up:
if new_p_ind >= 0 and new_p_ind < p_ind:
note.oct += 1
else:
if new_p_ind > p_ind and new_p_ind < num_chroma:
note.oct -= 1
return note
def __sub__(self, step):
'''
Subtract an integer number of semitones to the note
'''
return self.__add__(-step)
def __eq__(self, other_note):
return self.pname == other_note.pname and self.oct == other_note.oct
def __lt__(self, other_note):
return self.oct < other_note.oct or (self.oct == other_note.oct and Note.pitch_classes.index(self.pname) < Note.pitch_classes.index(other_note.pname))
def __le__(self, other_note):
return self.__lt__(other_note) or self.__eq__(other_note)
def __gt__(self, other_note):
return self.oct > other_note.oct or (self.oct == other_note.oct and Note.pitch_classes.index(self.pname) > Note.pitch_classes.index(other_note.pname))
def __ge__(self, other_note):
return self.__gt__(other_note) or self.__eq__(other_note)
def __str__(self):
return "<note@: %s%d>" % (self.pname, self.oct)
def __repr__(self):
return self.__str__()
class Score(object):
def __init__(self, note):
'''
Initialize a score
'''
# musical events occuring in the input score
self.score_events = []
self.doc = None # container for parsed music document
for n in note:
Note = Score.handle_note(n)
self.score_events.append(Note)
def engrave(self):
'''
Call after self.score_events has been populated from file
to print the internal data structure to the terminal.
Mostly used for debugging.
'''
for e in self.score_events:
print e
@staticmethod
def handle_note(note):
'''
Helper function that takes an mei note element
and creates a Note object out of it.
'''
MIDI_num = int(note[0])
pitch_names = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
MIDI_num%12
pname = pitch_names[MIDI_num%12]
oct = int(MIDI_num/12-1)
return Note(pname, oct)
class ArrangeTabAstar(object):
'''
AStar class that forms a graph from a music score
'''
def __init__(self, score, num_frets):
self.score = score
self.num_frets = num_frets
self.graph = None
self.path = None
def gen_tab(self):
"""
Generate array of [string, fret]
"""
self.graph = self._gen_graph()
# run the A* algorithm
self.path = nx.astar_path(self.graph, 1, self.graph.number_of_nodes())
# remove start and end nodes
del self.path[0], self.path[-1]
strums = []
for n in self.path:
n = self.graph.node[n]
guitar_event = n['guitar_event']
score_event = n['score_event']
plucks = []
if isinstance(guitar_event, Pluck):
plucks.append((score_event.pname, score_event.oct, guitar_event))
else:
for pluck, note in zip(guitar_event.plucks, score_event.notes):
plucks.append((note.id, pluck))
strums.append(plucks)
fingering = np.empty([0,2], dtype=int)
for s in strums:
for ss in s:
fingering = np.append(fingering,[[ss[2].string+1, ss[2].fret+1]], axis=0)
return fingering
def _gen_graph(self):
dg = nx.DiGraph()
# start node for the search agent
dg.add_node(1, guitar_event='start')
prev_node_layer = [1]
node_num = 2
num_nodes = len(self.score.score_events)
for i, e in enumerate(self.score.score_events):
# generate all possible fretboard combinations for this event
candidates = self._get_candidates(e)
if len(candidates) == 0:
continue
node_layer = []
for c in candidates:
# each candidate position becomes a node on the graph
dg.add_node(node_num, guitar_event=c, score_event=e)
node_layer.append(node_num)
# form edges between this node and nodes in previous layer
edges = []
for prev_node in prev_node_layer:
# calculate edge weight
w = ArrangeTabAstar.biomechanical_burlet(dg.node[prev_node]['guitar_event'], dg.node[node_num]['guitar_event'])
edges.append((prev_node, node_num, w))
dg.add_weighted_edges_from(edges)
node_num += 1
prev_node_layer = node_layer
# end node for the search agent
dg.add_node(node_num, guitar_event='end')
edges = [(prev_node, node_num, 0) for prev_node in prev_node_layer]
dg.add_weighted_edges_from(edges)
return dg
@staticmethod
def biomechanical_burlet(n1, n2):
'''
Evaluate the biomechanical cost of moving from one node to another.
PARAMETERS
----------
n1: GuitarEvent
n2: following GuitarEvent
'''
distance = 0 # biomechanical distance
w_distance = 2 # distance weight
if n1 != 'start':
# calculate distance between nodes
if not n1.is_open():
distance = n1.distance(n2)
fret_penalty = 0
w_fret_penalty = 1 # fret penalty weight
fret_threshold = 7 # start incurring penalties above fret 7
chord_distance = 0
w_chord_distance = 2
chord_string_distance = 0 # penalty for holes between string strums
w_chord_string_distance = 1
if isinstance(n2, Pluck):
if n2.fret > fret_threshold:
fret_penalty += 1
else:
frets = [p.fret for p in n2.plucks]
if max(frets) > fret_threshold:
fret_penalty += 1
chord_distance = max(frets) - min(frets)
strings = sorted([p.string for p in n2.plucks])
for i in range(len(strings)-1,-1,-1):
if i-1 < 0:
break
s2 = strings[i]
s1 = strings[i-1]
chord_string_distance += (s2-s1)
chord_string_distance -= len(strings)-1
return w_distance*distance + w_fret_penalty*fret_penalty + w_chord_distance*chord_distance + w_chord_string_distance*chord_string_distance
def _get_candidates(self, score_event):
'''
Calculate guitar pluck or strum candidates for a given note or chord event
'''
candidates = []
if isinstance(score_event, Note):
candidates = self._get_candidate_frets(score_event)
return candidates
def _get_candidate_frets(self, note):
'''
Given a note, get all the candidate (string, fret) pairs
where it could be played given the current guitar properties
(number of strings, and tuning).
'''
candidates = []
num_chroma = len(Note.pitch_classes)
strings = [Note('E', 4), Note('B', 3), Note('G', 3), Note('D', 3), Note('A', 2), Note('E', 2)]
# get open string pitches with capo position
open_strings = [n for n in strings]
for i, s in enumerate(open_strings):
# calculate pitch difference from the open string note
oct_diff = note.oct - s.oct
pname_diff = Note.pitch_classes.index(note.pname) - Note.pitch_classes.index(s.pname)
pitch_diff = pname_diff + num_chroma*oct_diff
if pitch_diff >= 0 and pitch_diff <= self.num_frets:
candidates.append(Pluck(i, pitch_diff))
return candidates
def parse_input_files(input_files, ext='.wav'):
"""
Collect all files by given extension and keywords.
:param agrs: class 'argparse.Namespace'.
:param ext: the string of file extension.
:returns: a list of stings of file name.
"""
from os.path import basename, isdir
import fnmatch
import glob
files = []
# check what we have (file/path)
if isdir(input_files):
# use all files with .raw.melody in the given path
files = fnmatch.filter(glob.glob(input_files+'/*'), '*'+ext)
else:
# file was given, append to list
if basename(input_files).find(ext)!=-1:
files.append(input_files)
print ' Input files: '
for f in files: print ' ', f
return files
def parser():
"""
Parses the command line arguments.
:param lgd: use local group delay weighting by default
:param threshold: default value for threshold
"""
import argparse
# define parser
p = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter, description="""
If invoked without any parameters, the software S1 Extract melody contour,
track notes and timestmaps of intersection of ad continuous pitch sequence
inthe given files, the pipeline is as follows,
""")
# general options
p.add_argument('input_files', type=str, metavar='input_files',
help='files to be processed')
p.add_argument('output_dir', type=str, metavar='output_dir',
help='output directory.')
p.add_argument('-fn', '--fret_number', type=int, dest='fn', help="the fret number of guitar finger board.", default=22)
# version
p.add_argument('--version', action='version',
version='%(prog)spec 1.03 (2016-03-30)')
# parse arguments
args = p.parse_args()
# return args
return args
def main(args):
print '================================'
print 'Running fingering arrangement...'
print '================================'
# parse and list files to be processed
files = parse_input_files(args.input_files, ext='.esn')
# create result directory
if not os.path.exists(args.output_dir): os.makedirs(args.output_dir)
print ' Output directory: ', '\n', ' ', args.output_dir
# processing
for f in files:
# parse file name and extension
ext = os.path.basename(f).split('.')[-1]
name = os.path.basename(f).split('.')[0]
# load expression style note
try:
expression_style_note = np.loadtxt(f)
except IOError:
print 'The expression style note of', name, 'doesn\'t exist!'
# extract the pitch, onset and duration
note_nparray = expression_style_note[:,0:3]
# convert numpy array to list
note = np.ndarray.tolist(note_nparray)
# generate the score model
score = Score(note)
astar = ArrangeTabAstar(score, num_frets=args.fn)
fingering = astar.gen_tab()
np.savetxt(args.output_dir+os.sep+name+'.fingering', fingering, fmt='%s')
if __name__ == '__main__':
args = parser()
main(args)