def test_not_equal_decorations(self): for tone_1 in chord.ALLOWED_TONES: for tone_2 in chord.ALLOWED_TONES: for decoration_1 in [None, ["m", "7", "5"], ["5", "M7", "/A"]]: for decoration_2 in [None, ["5", "M7", "/A"], ["7", "5", "m"]]: if tone_1 != tone_2: self.assertNotEqual(chord.Chord(tone_1, decoration_1), chord.Chord(tone_2, decoration_2))
def rule_13(s: stave.Stave): """Lorsque la dominante du ton se trouve à la partie inférieure - et qu'elle a été précédée de l'accord du premier degré - il faut éviter de la combiner avec une sixte car cela donnerait le sentiment d'un accord de quarte et sixte, ce qui est défendu. Si elle permet de sous-entendre un autre accord, on peut l'employer""" """There is maybe a problem here: if the main scale is major, every switch to the relative minor will install it as the main scale and the program will never consider that the swith is finished since not pitch of the major is outside of the minor. Maybe we should consider that we return to the major scale each measure. WARNING""" current_scale = s.scale previous_chord = None for bar in s.barIter(): # change scale if necessary if bar[0].pitch not in current_scale or bar[ 1].pitch not in current_scale: current_scale = current_scale.relative(scale.Mode.m_full) notes = [scalenote.NoteScale(current_scale, n) for n in bar] n1, n2 = notes # generate chord first = chord.Chord(1, current_scale) # is it the first degree chord? if notes in first: previous_chord = notes continue if previous_chord is not None: # is it the dominant in the bass and an interval of sixth? low, high = (n1, n2) if n1 < n2 else (n2, n1) if low.isDominant and low.note.isInterval(6).With(high.note): raise error.CompositionError( "It is forbidden to use a tonic chord followed by a dominant at the bass and a sixth with the dominant", previous_chord, bar) # clean-up previous_chord = None
def merge_voices_to_chords(self): """Fügt Töne mit gleicher Länge, gleichem Offset und ohne Haltebogen zu einem Akkord zusammen""" unique_offsets_with_sustains = self.get_unique_offsets_with_sustains() for sustain, offset in unique_offsets_with_sustains: possible_chord = [] for ind_voice, voice1 in enumerate(self.voices): for ind_note, note1 in enumerate(voice1.notes_chords_rests): if self.previous_measure is None and note1.sustain == sustain and note1.offset == offset and note1.tie == '' and isinstance( note1, note.Note): possible_chord.append(note1) if len(possible_chord) == 1: swap_index = (ind_voice, ind_note) elif len(possible_chord) > 1: voice1.notes_chords_rests[ind_note] = rest.Rest( sustain) elif note1.sustain == sustain and note1.offset == offset and note1.tie == '' and isinstance( note1, note.Note) and not ( ind_note == 0 and self.previous_measure.voices[ind_voice]. notes_chords_rests[-1].tie == 'start'): possible_chord.append(note1) if len(possible_chord) == 1: swap_index = (ind_voice, ind_note) elif len(possible_chord) > 1: voice1.notes_chords_rests[ind_note] = rest.Rest( sustain) if len(possible_chord) > 1: merged_chord = chord.Chord(possible_chord, sustain) self.voices[swap_index[0]].notes_chords_rests[ swap_index[1]] = merged_chord
def main(): parser = argparse.ArgumentParser( description='RNNとかで曲生成したい!') parser.add_argument('--resume', '-r', type=str, default="result/lstm/snapshot_iter_900", help='保存済みデータの名前') parser.add_argument('--vec', '-v', type=int, default=32, help='中間層の次元') parser.add_argument('--layer', '-l', type=int, default=2, help='レイヤーの層') parser.add_argument('--gpu', '-g', type=int, default=-1, help='GPU ID (negative value indicates CPU)') parser.add_argument('--model', '-model', default='LSTM', choices=['Word2Vec'], help='Name of encoder model type.') args = parser.parse_args() print(json.dumps(args.__dict__, indent=2)) model = getattr(mymodel, args.model)(481, args.vec, args.layer) # GPUで動かせるのならば動かす if args.gpu >= 0: chainer.cuda.get_device_from_id(args.gpu).use() model.to_gpu() # 学習済みデータの読み込み設定 if args.resume: try: chainer.serializers.load_npz(args.resume, model, path='updater/model:main/') # なぜかpathを外すと読み込めなくなってしまった 原因不明 except Exception as e: print(e) chainer.serializers.load_npz(args.resume, model) # なぜかpathを外すと読み込めなくなってしまった 原因不明 while 1: try: str_ = input("\n何を予測する? 空白区切りで入れてください\n") if str_ == "": break strs = str_.split(" ") if strs[-1] == "": strs = strs[:-1] chords = [] for i in strs: c = chord.Chord(i) note = 1 + len(QUALITY_DICT) * NOTE_VAL_DICT[c.root] + \ dict([(j, i) for i, j in list(enumerate(QUALITY_DICT.keys()))])[c.quality.quality] chords.append(note) indata = np.reshape(np.array(chords, dtype=np.int32), [1, len(chords)]) y = model(indata) y = y.data[0] y = list(enumerate(y)) y.sort(key=lambda x: x[1]) y.reverse() y = [(chord.tochord(i[0]), i[1]) for i in y[:10]] for num, i in enumerate(y): print("No.{:<2} {:<4}: {}".format(num+1, i[0], i[1])) except Exception as e: print("Error") print(e)
def test_neutral(self): """The Chord is neutral.""" n = note.Note('F#4', True) c = chord.Chord(n) c.remove_notes('major 7') self.assertEqual(c.notes, [])
def rule_23(s: stave.Stave): """La première et la dernière mesure sont obligatoirement harmonisées par l'accord de tonique à l'état fondamental""" c = chord.Chord(1, s.scale) for bar in (s.getBar(0), s.getBar(-1)): if not c.isInversion([*bar], 0): raise error.CompositionError( "First and last bar must be at the root position of the chord of the first degree", bar)
def test_1_note_keep(self): """The Chord has 1 note that is NOT removed.""" n = note.Note('A#4', True) c = chord.Chord(n) c.build_chord('major', 1) c.remove_notes('perfect 5') self.assertEqual(c.notes, [n])
def test_1_note_remove(self): """The Chord has 1 note that is removed.""" n = note.Note('Bb2', True) c = chord.Chord(n) c.build_chord('minor', 1) c.remove_notes('perfect 1') self.assertEqual(c.notes, [])
def test_neutral(self): """The Chord is neutral.""" n = note.Note('G#4', True) c = chord.Chord(n) actual = c.is_crunchy() expected = False self.assertEqual(actual, expected)
def test_many_notes_middle(self): """self.notes has more than 2 notes and a Note with tone add_tone should be added after the first pair.""" n = note.Note('C#3', True) c = chord.Chord(n) c.build_chord('diminished', 4) actual = c.correct_location(0, 'F#') expected = 2 self.assertEqual(actual, expected)
def test_2_notes_middle(self): """self.notes has 2 notes and a Note with tone add_tone should be added in between the 2 notes.""" n = note.Note('B2', True) c = chord.Chord(n) c.build_chord('major', 2) actual = c.correct_location(0, 'C#') expected = 1 self.assertEqual(actual, expected)
def test_one_note(self): """self.notes contains 1 note.""" n = note.Note('G3', True) c = chord.Chord(n) c.build_chord('minor', 1) actual = c.correct_location(0, 'C') expected = 1 self.assertEqual(actual, expected)
def test_already_exists(self): """Notes with argument tone already exist in a Chord.""" n = note.Note('C3', True) c = chord.Chord(n) c.build_chord('major', 5) actual = c.correct_location(0, 'G') expected = 5 self.assertEqual(actual, expected)
def test_not_in_key(self): """add_tone is not in the Chord's key.""" n = note.Note('G3', True) c = chord.Chord(n) c.build_chord('major') actual = c.correct_location(0, 'Bbb') expected = 1 self.assertEqual(actual, expected)
def get_chord(self): iset = self.getIntervalSet() qualityandinversion = iset.is_chord() if (qualityandinversion): import chord quality = qualityandinversion[0] pitch = self.pitches[qualityandinversion[1]] return chord.Chord(pitch, quality) else: return False
def test_start_at_end(self): """Start searching from the last index in the Chord.""" n = note.Note('Ab3', True) c = chord.Chord(n) c.build_chord('minor', 6) actual = c.correct_location(5, 'G') expected = 6 self.assertEqual(actual, expected)
def test_many_notes_no_crunch(self): """The Chord contains more than 1 note and none are dissonant with each other.""" n = note.Note('Gb3', True) c = chord.Chord(n) c.build_chord('minor', 7) actual = c.is_crunchy() expected = False self.assertEqual(actual, expected)
def test_2_notes_no_crunch(self): """The Chord contains 2 notes that are NOT dissonant.""" n = note.Note('Fx4', True) c = chord.Chord(n) c.build_chord('augmented', 2) actual = c.is_crunchy() expected = False self.assertEqual(actual, expected)
def test_many_notes_crunch(self): """The Chord contains more than 1 note and at least 2 are dissonant with each other.""" n = note.Note('C3', True) c = chord.Chord(n) c.build_chord('major suspended 4') actual = c.is_crunchy() expected = True self.assertEqual(actual, expected)
def test_one_note(self): """The Chord contains one note.""" n = note.Note('Ab3', True) c = chord.Chord(n) c.build_chord('major suspended 2', 1) actual = c.is_crunchy() expected = False self.assertEqual(actual, expected)
def test_2_notes_crunch(self): """The Chord contains 2 notes that are dissonant.""" n = note.Note('G3', True) c = chord.Chord(n) c.build_chord('major suspended 2', 2) actual = c.is_crunchy() expected = True self.assertEqual(actual, expected)
def test_fill_no_octave(self): """The Chord contains more than 1 non-root note, but only 1 root octave.""" n = note.Note('Bb3', True) c = chord.Chord(n) c.build_chord('augmented', 3) actual = c.is_rich() expected = False self.assertEqual(actual, expected)
def test_rich(self): """The Chord contains multiple octaves with 2 or more notes in between.""" n = note.Note('A#4', True) c = chord.Chord(n) c.build_chord('major suspended 24', 6) actual = c.is_rich() expected = True self.assertEqual(actual, expected)
def test_one_note(self): """The Chord has one note.""" n = note.Note('Fx4', True) c = chord.Chord(n) c.build_chord('major', 1) actual = c.is_rich() expected = False self.assertEqual(actual, expected)
def test_end_crunch_2(self): """The Chord contains a dissonance between the 10th tone and 1st or 2nd tone in the key.""" n = note.Note('C280', True) c = chord.Chord(n) c.build_chord('major', 5) c.add_notes('minor 7') actual = c.is_crunchy() expected = True self.assertEqual(actual, expected)
def test_octave_no_fill(self): """The Chord contains a whole octave, but less than 2 notes in between.""" n = note.Note('Gb1', True) c = chord.Chord(n) c.build_chord('major', 12) c.remove_notes('major 3') actual = c.is_rich() expected = False self.assertEqual(actual, expected)
def rule_26(s: stave.Stave): """La première et la dernière mesure sont obligatoirement harmonisées par l'accord de tonique à l'état fondamental""" tonic = chord.Chord(1, s.scale) for measure in (s.getBar(0), s.getBar(-1)): is_error = False try: if not tonic.isInversion([*measure], 0): is_error = True except ValueError: is_error = True if is_error: raise error.CompositionError( f"In {s.title}, the first bar or the last bar is not the tonic chord at root position", measure)
def main(): # retrieve list of episode files fileList = os.listdir('episodes/') lineList = [] # extract the lines from files in episode list for f in fileList: with open('episodes/' + f) as fOb: for line in fOb: lineList.append(line.strip()) # set up the lists used codeList = ['a', 'k', 's', 't', 'z', 'i', 'az', 'o', 'm', 'ty', 'su'] names = [ 'Aang', 'Katara', 'Sokka', 'Toph', 'Zuko', 'Iroh', 'Azula', 'Ozai', 'Mai', 'Ty Lee', 'Suki' ] colorList = [ '#fff81f', '#6eddff', '#1690b5', '#0dd610', '#ff0000', '#ffaa00', '#590069', '#804f00', '#1c0000', '#ed009a', '#80ff00' ] matrix = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] # parse over the list of lines, filling the matrix for line in lineList: chars = line.split(',') matrix[codeList.index(chars[0])][codeList.index(chars[1])] += 1 matrix[codeList.index(chars[1])][codeList.index(chars[0])] += 1 # yay we're done #printMatrix(matrix, names) chord.Chord(matrix, names, wrap_labels=0, colors=colorList).to_html()
def get_pc_sets(base, keys): pc_sets = {} base_harm = base.keys() inversions = ['', 'b', 'c', 'd'] for key in keys: for inversion in inversions: for harm in base_harm: harmstr = '{}:{}{}'.format(key, harm, inversion) if inversion == 'd': if harm != 'Gn' and harm != 'Fr' and not '7' in harm: continue c = chord.Chord(harmstr) logger.debug('{} | {} {} | {} | inversion {} | bass {} | {}'.format(c.harmstr, c.key, 'minor' if c.key.islower() else 'major', c.harm, c.inversion, c.bass, c.pitch_classes)) pc_set = pc_sets.get(c.pitch_classes, []) pc_set.append(c) pc_sets[c.pitch_classes] = pc_set return pc_sets
def test_parse_str(self): strings = ["C-M7", "D#-sus2-sus4", "E-sus4", "d-7", "f#", "G"] chords = [chord.Chord("C", ["M7"]), chord.Chord("D#", ["sus2", "sus4"]), chord.Chord("E", ["sus4"]), chord.Chord("D", ["m", "7"]), chord.Chord("F#", ["m"]), chord.Chord("G")] for chord_string, chord_object in zip(strings, chords): self.assertEqual(chord.parse(chord_string), chord_object) self.assertEqual(chord_string, str(chord_object))