-
Notifications
You must be signed in to change notification settings - Fork 0
/
Markov.swift
114 lines (88 loc) · 2.8 KB
/
Markov.swift
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
//
// Markov.swift
//
// Simple Markov Chain for MIDI notes in combination with AudioKit.
//
// Created by Jan den Besten.
//
import AudioKit
class MarkovMatrix {
private var markovChains = [MIDIChannel:Markov]()
func feed( channel: MIDIChannel, noteData:[MIDINoteData]) {
markovChains[channel] = Markov()
markovChains[channel]!.feed(noteData:noteData)
}
func next( channel: MIDIChannel, note:MIDINoteNumber ) -> MIDINoteData {
return markovChains[channel]!.next( note:note )
}
func getEntries( channel: MIDIChannel ) -> [MIDINoteNumber] {
return markovChains[channel]!.getEntries()
}
func getChain( channel: MIDIChannel ) -> [MIDINoteNumber:[MIDINoteData]] {
return markovChains[channel]!.getChain()
}
func getChainOfNotes( channel: MIDIChannel ) -> [MIDINoteNumber:[MIDINoteNumber]] {
return markovChains[channel]!.getChainOfNotes()
}
}
class Markov {
private var notes = [MIDINoteNumber:MIDINoteData]()
private var chain = [MIDINoteNumber:[MIDINoteData]]()
private var entries = [MIDINoteNumber]()
private var last:MIDINoteNumber? = nil
// Feed the chain with notedata, results in filled
func feed( noteData:[MIDINoteData] )
{
var prevNote:MIDINoteNumber?
for data in noteData {
let note = data.noteNumber
notes[note] = data
// If not exists in chain, add it
if (chain[note]==nil) {
chain[note] = [MIDINoteData]()
}
// prev
if let prev = prevNote {
chain[prev]!.append(data)
}
prevNote = note
}
entries = Array(chain.keys)
}
// Get next (random) number from chain
func next( note:MIDINoteNumber ) -> MIDINoteData
{
var nextNote:MIDINoteData
// first note is a random note from the input feed
if last==nil {
nextNote = notes.values.randomElement()!
}
// next just get a random one from the chain
else {
nextNote = chain[last!]!.randomElement()!
}
// remember state
last = note
return nextNote
}
func getNotes() -> [MIDINoteNumber] {
return Array(notes.keys)
}
func getEntries() -> [MIDINoteNumber] {
return entries
}
func getChain() -> [MIDINoteNumber:[MIDINoteData]] {
return chain
}
func getChainOfNotes() -> [MIDINoteNumber:[MIDINoteNumber]] {
var chainOfNotes = [MIDINoteNumber:[MIDINoteNumber]]()
for (note,data) in chain {
var notes = [MIDINoteNumber]()
for item in data {
notes.append(item.noteNumber)
}
chainOfNotes[note] = notes
}
return chainOfNotes
}
}