Log(music) with Undertone

December 26, 2013

Whether you’re a physicist, biologist, economist, data scientist, whatever, the chances are you’ll meet the Markov chains sooner or later. And today we’ll try them on… music!

If you’re not up to the math part, feel free to skip it.

[Originally posted here].

Math

The system states changes are represented with a help of transition matrix, describing the probabilities of possible transitions. This matrix is a key to determine the state of the model after n steps.

The math behind that is very straightforward - we need just a matrix power. Oh, wait - what if it is fractional, for example, when representing time? There’re many ways to compute it, let’s take a look at some of them.

1. Eigen vectors

This method is based on properties of eigen values decomposition:

That’s actually how Matlab mpower function looks like:

 1: [V,D] = eig(M)
2: An = V * (D .^ n) * inv(V) 

We can take advantage of Math.NET matrix decompositions to implement this method:

  1: 2: 3: 4: 5: 6: 7: 8: 9:  open namespaces, define constants /// Matrix power: eigen values decomposition method /// M^p = V * (D .^ p) / V let mpowEig (m: SparseMatrix) p = let evd = m.Evd() let v, d = evd.EigenVectors(), evd.D() mapInPlace (fun x -> x ** p) d v * d * v.Inverse() 

What are the pros/cons?

+ the method is rather efficient
- inverse matrix $V$ might not exist 1

- some matrices cannot be diagonalised:

2. Generator matrices

If we can find a matrix $G$, such as $A = exp(G)$, then (remember series?)

We are interested in finding a generator $G$ with zero row sums and nonnegative off-diagonal entries. So we’ll use Mercator’s series:

In matrix case it’s

The common concern is that the series methods are not very efficient and may be not accurate enough. It’s easy to compare the methods by computing the squared error between the actual and expected values (say, compute $(A^{1/3})^3$).

Another problem is that a generator matrix (and power too) might have negative elements - not really what you want when dealing with probabilities. We can make them non-negative and keep the rows sums equal to zero… but the power properties won’t be preserved. For example, you can find out that $% A^{3.5} * A^{3.5} %]]>$.

  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:  /// generator matrix let genm (a: SparseMatrix) = let size = a.RowCount let mid = constDiag size 1.0 let a_i = a - mid let rec logm (i, qpow: SparseMatrix) res = if i = MAX_ITER then res else let qdiv = qpow.Divide (float i) if sumSq qdiv < PREC then res + qdiv else logm (i+1, -qpow * a_i) (res + qdiv) // find log(A - I) // update negative off-diagonal entries, the row-sum = 0 logm (1, a_i) (zeroCreate size size) |> updateneg /// exp series approximation let expSeries (m: SparseMatrix) = let size = m.RowCount let rec sum (i, k, mpow: SparseMatrix) res = if i = MAX_ITER then res else let mpowi, ki = mpow * m, k * float i let mdiv = mpowi.Divide ki if sumSq mdiv < PREC then res + mdiv else sum (i+1, ki, mpowi) (res + mdiv) let mid = constDiag size 1.0 sum (1, 1.0, mid) mid /// Matrix power: series method let mpowSeries m (p: float) = SparseMatrix.OfMatrix (genm m * p) |> expSeries

+ Works for non-diagonizable matrices
- Not very efficient
- May be not accurate enough or even fail to converge

These are just the most simple algorithms - would be interesting to check the others, but let’s move on.

Music

It’s not a secret, that Markov models are often used for generative music, here’s one of the examples: Programming Instrumental Music From Scratch (there’re also some interesting references in the comments). We’ll do a different thing, though: given notes, we can calculate the transition probabilities and… generate new melodies.

But everything in its time.

We need to somehow define the sequences of notes and play them. And thanks to Undertone that’s pretty easy! First of all, let’s download the piano samples - University of Iowa has a collection of recordings here. You can get them manually or using this script. It’s also ok to generate the notes programmatically - but somewhat a bit more realistic is more fun ^_^

  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:  open namespaces // Size: 2/4 /// 1/16 (semiquaver) [] let Sq = 0.0625 /// 1/8 (quaver) [] let Q1 = 0.125 /// 3/8 [] let Q3 = 0.375 ... /// Mapping between note enum and file name convention let noteToPianoName note = match note with | Note.C -> "C" | Note.Csharp -> "Db" | Note.D -> "D" | Note.Dsharp -> "Eb" | Note.E -> "E" | Note.F -> "F" | Note.Fsharp -> "Gb" | Note.G -> "G" | Note.Gsharp -> "Ab" | Note.A -> "A" | Note.Asharp -> "Bb" | Note.B -> "B" | _ -> failwith "invalid note" /// Read piano note from .aiff file let readPianoNote() = let cache = Dictionary<_,_> HashIdentity.Structural let inline path (noteName, octave) = Path.Combine(dir, "Piano.ff." + noteName + string octave + ".aiff") fun (note, octave) -> let noteKey = noteToPianoName note, octave match cache.TryGetValue noteKey with | true, wave -> wave | _ -> let wave = IO.read (path noteKey) |> Seq.toArray cache.Add(noteKey, wave) wave let makeNote = readPianoNote() let getMelody = Seq.collect (fun (noct, time) -> makeNote noct |> Seq.take (noteValue time)) 

The note is defined with its symbol (C = Do, F# = Fis = Fa-diesis = F sharp), octave and time (♪ - 1/8, ♬ - 2 notes * 1/16). The sequence of notes gives a melody, which can be played and even saved later. Can you guess the following one?

Original

Sounds recognizable, but awkwardly stumbling - makes me feel much better about my piano skills. I’d recommend to watch this performace, it’s amazing! (and that pianist-feeling suddenly goes down again)). I believe there’s a way to make the generated sound smoother and so on, but that’s not the goal now.

  1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13:  Define commonly used notes /// Sample melody let ent = [ D3,Sq; Ds3,Sq E3,Sq; C4,Q1; E3,Sq; C4,Q1; E3,Sq; C4,Q3 C4,Sq; D4,Sq; Ds4,Sq E4,Sq; C4,Sq; D4,Sq; E4,Q1; C4,Sq; D4,Q1 C4,Sq; D3,Sq; Ds3,Sq ... C4,Q3 ] Player.Play (getMelody ent)

(Note, the example above has 3 times faster tempo that the one you’ll get with downloaded notes)

The next thing to do is to calculate the transition probabilities. Consider the following sequence: E3 - 1/16, C4 - 1/8, E3 - 1/16, C4 - 3/8, C4 - 1/16.

The first option is to simply count transitions between notes and then normalize the rows, so the sum are equal to 1:

$% $
$% $

But wait, what about time? There’re different notes, we can take that into account too: if the ‘smallest’ length is 1/16, then we can count, how many such intervals each note takes, multiplying by 162:

E3 - 1/16, C4 - 1/8, E3 - 1/16, C4 - 3/8, C4 - 1/16

$% $ $% $

So, we know the transitions and times when the next note should be played. A uniform random number generator will choose this next note: e.g. if transitions are 0.4 0.2 0.1 0.3 and generated number is 0.65, that’s the 3rd one (this operation is called choose below).
The note at time t, given transition matrix P is

  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:  /// Compute the times and probabilities of transitions between notes let transitions xs = let noteToId = Seq.distinctBy fst xs |> Seq.mapi (fun i (note, _) -> note, i) |> dict // # of unique notes and # of notes in melody let n, m = noteToId.Count, List.length xs let matrix = Array.init n (fun _ -> Array.zeroCreate n) let times = Array.create m 0. // fill the matrix Seq.pairwise xs |> Seq.iteri (fun i ((note1, time1), (note2, _)) -> let n1, n2 = noteToId.[note1], noteToId.[note2] // option #1 - ignore times // matrix.[n1].[n2] <- matrix.[n1].[n2] + 1. // option #2 - add extra probability for transition to the same note // matrix.[n1].[n1] <- matrix.[n1].[n1] + time1 * 16.0 // matrix.[n1].[n2] <- matrix.[n1].[n2] + 1.0 // option #3 - take time into account (scale by 16) let p = time1*16.-1. in if p > 0. then matrix.[n1].[n1] <- matrix.[n1].[n1] + p matrix.[n1].[n2] <- matrix.[n1].[n2] + 1.0 times.[i+1] <- times.[i] + time1) normalizeRows matrix, times, Seq.toArray noteToId.Keys let matrix, times, idToNote = transitions ent /// Find index of the next note given probability let transTo (ps: _[]) = ... /// Generate music from transition matrices in a file let genMusic matricesFileName (fstNote, idToNote: _[]) = // transition matrices and times let ps, ts = readMatrices matricesFileName let n = ps.Count let rand = System.Random() let rec gen i prevInd res = if i >= n-1 then List.rev res else let j = transTo ps.[i].[prevInd] (rand.NextDouble()) let next = idToNote.[j], ts.[i] gen (i+1) j (next::res) gen 0 0 [fstNote] 

I tried to compute the transition matrix - and both method failed! Turns out this is the real-life ‘unlucky’ matrix. To be sure that doesn’t work, checked R’s expm package:

  1: 2: 3: 4: 5: 6: 7: 8:  logm(x, method = "Eigen") Error in logm(x, method = "Eigen") : non diagonalisable matrix logm(x, method = "Higham08") Error in solve.default(X[ii, ii] + X[ij, ij], S[ii, ij] - sumU) : system is computationally singular: reciprocal condition number = 0 In addition: Warning messages: 1: In sqrt(S[ij, ij]) : NaNs produced 2: In sqrt(S[ij, ij]) : NaNs produced 

Fortunately, we don’t need fraction power here: if we count time in 1/16th, it becomes integer! 1/16 is 1, 3/8 is 6 and so on. Good old multiplication saves the situation.

Here’s several examples of generated melodies - there’re only 10 notes are in the game, but the results are already pretty different from the original:

What if we add an ‘extra-probability’ for note to stay in the same state?

E3 - 1/16, C4 - 1/8, E3 - 1/16, C4 - 3/8, C4 - 1/16

$% $ $% $

For this matrix, the generator does exist and we can programmatically compose something like that:

Why stop here? We could define the similar transitions for note length; or add chords - say, generated according to the current tonality; or switch tonalities/modes… Well, there’s a whole ‘musical math’, solfeggio, full of different functions - plenty of space to experiment!

Happy Holidays!

  1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12:  let jingleBells = [ E4,Sq; E4,Sq; E4,Q1 E4,Sq; E4,Sq; E4,Q1 E4,Sq; G4,Sq; C4,Sq; D4,Sq E4,Q1*2.0 F4,Sq; F4,Sq; F4,Sq; F4,Sq F4,Sq; E4,Sq; E4,Sq; E4,Sq E4,Sq; D4,Sq; D4,Sq; E4,Sq D4,Q1; G4,Q1 ] Player.Play (getMelody jingleBells)

open MathNet.Numerics.LinearAlgebra.Double
open MathNet.Numerics.LinearAlgebra.Generic
open Matrix
open SparseMatrix

[<Literal>]
let MAX_ITER = 10000
[<Literal>]
let PREC = 1e-60

val mpowEig : m:SparseMatrix -> p:float -> Matrix<float>

Full name: LogMusic.mpowEig

Matrix power: eigen values decomposition method
M^p = V * (D .^ p) / V

val m : SparseMatrix
Multiple items
type SparseMatrix =
inherit Matrix
new : storage:SparseCompressedRowMatrixStorage<float> -> SparseMatrix + 6 overloads
member CreateMatrix : numberOfRows:int * numberOfColumns:int * ?fullyMutable:bool -> Matrix<float>
member CreateVector : size:int * ?fullyMutable:bool -> Vector<float>
member FrobeniusNorm : unit -> float
member IndexedEnumerator : unit -> IEnumerable<Tuple<int, int, float>>
member InfinityNorm : unit -> float
member IsSymmetric : bool
member KroneckerProduct : other:Matrix<float> * result:Matrix<float> -> unit
member LowerTriangle : unit -> Matrix<float> + 1 overload
member NonZerosCount : int
...

Full name: MathNet.Numerics.LinearAlgebra.Double.SparseMatrix

--------------------
SparseMatrix(storage: MathNet.Numerics.LinearAlgebra.Storage.SparseCompressedRowMatrixStorage<float>) : unit
SparseMatrix(order: int) : unit
SparseMatrix(rows: int, columns: int) : unit

val p : float
val evd : Factorization.Evd
Matrix.Evd() : Factorization.Evd
val v : Matrix<float>
val d : Matrix<float>
Factorization.Evd.EigenVectors() : Matrix<float>
Factorization.Evd.D() : Matrix<float>
val mapInPlace : f:(float -> float) -> A:#Matrix<float> -> unit

Full name: MathNet.Numerics.LinearAlgebra.Double.Matrix.mapInPlace

val x : float
Matrix.Inverse() : Matrix<float>
val genm : a:SparseMatrix -> Matrix<float>

Full name: LogMusic.genm

generator matrix

val a : SparseMatrix
val size : int
property Matrix.RowCount: int
val mid : SparseMatrix
val constDiag : n:int -> f:float -> SparseMatrix

Full name: MathNet.Numerics.LinearAlgebra.Double.SparseMatrix.constDiag

val a_i : SparseMatrix
val logm : (int * SparseMatrix -> Matrix<float> -> Matrix<float>)
val i : int
val qpow : SparseMatrix
val res : Matrix<float>
val MAX_ITER : int

Full name: LogMusic.MAX_ITER

val qdiv : Matrix<float>
Matrix.Divide(scalar: float) : Matrix<float>
Matrix.Divide(scalar: float, result: Matrix<float>) : unit
Multiple items
val float : value:'T -> float (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.float

--------------------
type float = System.Double

Full name: Microsoft.FSharp.Core.float

--------------------
type float<'Measure> = float

Full name: Microsoft.FSharp.Core.float<_>

val sumSq : m:Matrix<float> -> float

Full name: LogMusic.sumSq

sum of squares

val PREC : float

Full name: LogMusic.PREC

val zeroCreate : rows:int -> cols:int -> SparseMatrix

Full name: MathNet.Numerics.LinearAlgebra.Double.SparseMatrix.zeroCreate

val updateneg : m:Matrix<float> -> Matrix<float>

Full name: LogMusic.updateneg

update negative

val expSeries : m:SparseMatrix -> Matrix<float>

Full name: LogMusic.expSeries

exp series approximation

val sum : (int * float * SparseMatrix -> Matrix<float> -> Matrix<float>)
val k : float
val mpow : SparseMatrix
val mpowi : SparseMatrix
val ki : float
val mdiv : Matrix<float>
val mpowSeries : m:SparseMatrix -> p:float -> Matrix<float>

Full name: LogMusic.mpowSeries

Matrix power: series method

SparseMatrix.OfMatrix(matrix: Matrix<float>) : SparseMatrix
open System.IO
open System.Collections.Generic
open Undertone
open Undertone.Waves
Multiple items
type LiteralAttribute =
inherit Attribute
new : unit -> LiteralAttribute

Full name: Microsoft.FSharp.Core.LiteralAttribute

--------------------
new : unit -> LiteralAttribute

val Sq : float

Full name: LogMusic.Sq

1/16 (semiquaver)

val Q1 : float

Full name: LogMusic.Q1

1/8 (quaver)

val Q3 : float

Full name: LogMusic.Q3

3/8

let inline noteValue time = Time.noteValue 15. time

/// Note samples directory
[<Literal>]
let dir = @"C:\samples"

val noteToPianoName : note:Note -> string

Full name: LogMusic.noteToPianoName

Mapping between note enum and file name convention

val note : Note
type Note =
| Cflat = -1
| C = 0
| Csharp = 1
| Dflat = 1
| D = 2
| Dsharp = 3
| Eflat = 3
| E = 4
| Fflat = 4
| Esharp = 5
| F = 5
| Fsharp = 6
| Gflat = 6
| G = 7
| Gsharp = 8
| Aflat = 8
| A = 9
| Asharp = 10
| Bflat = 10
| B = 11
| Bsharp = 12

Full name: Undertone.Note

Note.C: Note = 0
Note.Csharp: Note = 1
Note.D: Note = 2
Note.Dsharp: Note = 3
Note.E: Note = 4
Note.F: Note = 5
Note.Fsharp: Note = 6
Note.G: Note = 7
Note.Gsharp: Note = 8
Note.A: Note = 9
Note.Asharp: Note = 10
Note.B: Note = 11
val failwith : message:string -> 'T

Full name: Microsoft.FSharp.Core.Operators.failwith

val readPianoNote : unit -> (Note * int -> float [])

Read piano note from .aiff file

val cache : Dictionary<(string * int),float []>
Multiple items
type Dictionary<'TKey,'TValue> =
new : unit -> Dictionary<'TKey, 'TValue> + 5 overloads
member Add : key:'TKey * value:'TValue -> unit
member Clear : unit -> unit
member Comparer : IEqualityComparer<'TKey>
member ContainsKey : key:'TKey -> bool
member ContainsValue : value:'TValue -> bool
member Count : int
member GetEnumerator : unit -> Enumerator<'TKey, 'TValue>
member GetObjectData : info:SerializationInfo * context:StreamingContext -> unit
member Item : 'TKey -> 'TValue with get, set
...
nested type Enumerator
nested type KeyCollection
nested type ValueCollection

Full name: System.Collections.Generic.Dictionary<_,_>

--------------------
Dictionary() : unit
Dictionary(capacity: int) : unit
Dictionary(comparer: IEqualityComparer<'TKey>) : unit
Dictionary(dictionary: IDictionary<'TKey,'TValue>) : unit
Dictionary(capacity: int, comparer: IEqualityComparer<'TKey>) : unit
Dictionary(dictionary: IDictionary<'TKey,'TValue>, comparer: IEqualityComparer<'TKey>) : unit

module HashIdentity

from Microsoft.FSharp.Collections

val Structural<'T (requires equality)> : IEqualityComparer<'T> (requires equality)

Full name: Microsoft.FSharp.Collections.HashIdentity.Structural

val path : (string * 'a -> string)
val noteName : string
val octave : 'a
type Path =
static val DirectorySeparatorChar : char
static val AltDirectorySeparatorChar : char
static val VolumeSeparatorChar : char
static val InvalidPathChars : char[]
static val PathSeparator : char
static member ChangeExtension : path:string * extension:string -> string
static member Combine : params paths:string[] -> string + 3 overloads
static member GetDirectoryName : path:string -> string
static member GetExtension : path:string -> string
static member GetFileName : path:string -> string
...

Full name: System.IO.Path

Path.Combine(params paths: string []) : string
Path.Combine(path1: string, path2: string) : string
Path.Combine(path1: string, path2: string, path3: string) : string
Path.Combine(path1: string, path2: string, path3: string, path4: string) : string
val dir : string

Full name: LogMusic.dir

Note samples directory

Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string

val octave : int
val noteKey : string * int
Dictionary.TryGetValue(key: string * int, value: byref<float []>) : bool
val wave : float []
module IO

from Undertone

val read : file:string -> seq<float>

module Seq

from Microsoft.FSharp.Collections

val toArray : source:seq<'T> -> 'T []

Full name: Microsoft.FSharp.Collections.Seq.toArray

Dictionary.Add(key: string * int, value: float []) : unit
val makeNote : (Note * int -> float [])

Full name: LogMusic.makeNote

val getMelody : (((Note * int) * float) list -> seq<float>)

Full name: LogMusic.getMelody

val collect : mapping:('T -> #seq<'U>) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.collect

val noct : Note * int
val time : float
val take : count:int -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.take

val noteValue : time:float -> int

Full name: LogMusic.noteValue

let D3 = Note.D, 3
let Ds3 = Note.Dsharp, 3
let E3 = Note.E, 3
let Fs3 = Note.Fsharp, 3
let G3 = Note.G, 3
let A3 = Note.A, 3
let C4 = Note.C, 4
let D4 = Note.D, 4
let Ds4 = Note.Dsharp, 4
let E4 = Note.E, 4

let G4 = Note.G, 4
let F4 = Note.F, 4

val ent : ((Note * int) * float) list

Full name: LogMusic.ent

Sample melody

val D3 : Note * int

Full name: LogMusic.D3

val Ds3 : Note * int

Full name: LogMusic.Ds3

val E3 : Note * int

Full name: LogMusic.E3

val C4 : Note * int

Full name: LogMusic.C4

val D4 : Note * int

Full name: LogMusic.D4

val Ds4 : Note * int

Full name: LogMusic.Ds4

val E4 : Note * int

Full name: LogMusic.E4

E3,Sq; C4,Q1; E3,Sq; C4,Q1; E3,Sq; C4,Q3
A3,Sq; G3,Sq
Fs3,Sq; A3,Sq; C4,Sq; E4,Q1; D4,Sq; C4,Sq; A3,Sq
D4,Q3; D3,Sq; Ds3,Sq
E3,Sq; C4,Q1; E3,Sq; C4,Q1; E3,Sq; C4,Q3
C4,Sq; D4,Sq; Ds4,Sq
E4,Sq; C4,Sq; D4,Sq; E4,Q1; C4,Sq; D4,Q1
C4,Q3; D4,Sq; Ds4,Sq
E4,Sq; C4,Sq; D4,Sq; E4,Q1; C4,Sq; D4,Sq; C4,Sq
E4,Sq; C4,Sq; D4,Sq; E4,Q1; C4,Sq; D4,Sq; C4,Sq
E4,Sq; C4,Sq; D4,Sq; E4,Q1; C4,Sq; D4,Q1
type Player =
private new : unit -> Player
static member Play : sampleSource:seq<float> -> IPlayer

Full name: Undertone.Player

static member Player.Play : sampleSource:seq<float> -> IPlayer
val transitions : xs:('a * float) list -> float [] [] * float [] * 'a [] (requires equality)

Full name: LogMusic.transitions

Compute the times and probabilities of transitions between notes

val xs : ('a * float) list (requires equality)
val noteToId : IDictionary<'a,int> (requires equality)
val distinctBy : projection:('T -> 'Key) -> source:seq<'T> -> seq<'T> (requires equality)

Full name: Microsoft.FSharp.Collections.Seq.distinctBy

val fst : tuple:('T1 * 'T2) -> 'T1

Full name: Microsoft.FSharp.Core.Operators.fst

val mapi : mapping:(int -> 'T -> 'U) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.mapi

val note : 'a (requires equality)
val dict : keyValuePairs:seq<'Key * 'Value> -> IDictionary<'Key,'Value> (requires equality)

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.dict

val n : int
val m : int
property ICollection.Count: int
Multiple items
type List<'T> =
new : unit -> List<'T> + 2 overloads
member Add : item:'T -> unit
member AddRange : collection:IEnumerable<'T> -> unit
member BinarySearch : item:'T -> int + 2 overloads
member Capacity : int with get, set
member Clear : unit -> unit
member Contains : item:'T -> bool
member ConvertAll<'TOutput> : converter:Converter<'T, 'TOutput> -> List<'TOutput>
member CopyTo : array:'T[] -> unit + 2 overloads
...
nested type Enumerator

Full name: System.Collections.Generic.List<_>

--------------------
List() : unit
List(capacity: int) : unit
List(collection: IEnumerable<'T>) : unit

val length : list:'T list -> int

Full name: Microsoft.FSharp.Collections.List.length

val matrix : float [] []
module Array

from Microsoft.FSharp.Collections

val init : count:int -> initializer:(int -> 'T) -> 'T []

Full name: Microsoft.FSharp.Collections.Array.init

val zeroCreate : count:int -> 'T []

Full name: Microsoft.FSharp.Collections.Array.zeroCreate

val times : float []
val create : count:int -> value:'T -> 'T []

Full name: Microsoft.FSharp.Collections.Array.create

val pairwise : source:seq<'T> -> seq<'T * 'T>

Full name: Microsoft.FSharp.Collections.Seq.pairwise

val iteri : action:(int -> 'T -> unit) -> source:seq<'T> -> unit

Full name: Microsoft.FSharp.Collections.Seq.iteri

val note1 : 'a (requires equality)
val time1 : float
val note2 : 'a (requires equality)
val n1 : int
val n2 : int
val normalizeRows : m:float [] [] -> float [] []

Full name: LogMusic.normalizeRows

Normalize rows, so the row-sums are equal to 1

property IDictionary.Keys: ICollection<'a>
val matrix : float [] []

Full name: LogMusic.matrix

val times : float []

Full name: LogMusic.times

val idToNote : (Note * int) []

Full name: LogMusic.idToNote

val transTo : ps:float [] -> (float -> int)

Full name: LogMusic.transTo

Find index of the next note given probability

val ps : float []
let last = ps.Length-1
let rec findj j v =
if ps.[j] >= v || j = last then j
else findj (j+1) (v - ps.[j])
findj 0
val genMusic : matricesFileName:string -> fstNote:('a * float) * idToNote:'a [] -> ('a * float) list

Full name: LogMusic.genMusic

Generate music from transition matrices in a file

val matricesFileName : string
val fstNote : 'a * float
val idToNote : 'a []
val ps : List<ResizeArray<float []>>
val ts : float []
val readMatrices : path:string -> List<ResizeArray<float []>> * float []

property List.Count: int
val rand : System.Random
namespace System
Multiple items
type Random =
new : unit -> Random + 1 overload
member Next : unit -> int + 2 overloads
member NextBytes : buffer:byte[] -> unit
member NextDouble : unit -> float

Full name: System.Random

--------------------
System.Random() : unit
System.Random(Seed: int) : unit

val gen : (int -> int -> ('a * float) list -> ('a * float) list)
val prevInd : int
val res : ('a * float) list
val rev : list:'T list -> 'T list

Full name: Microsoft.FSharp.Collections.List.rev

val j : int
System.Random.NextDouble() : float
val next : 'a * float
val jingleBells : ((Note * int) * float) list

Full name: LogMusic.jingleBells

val G4 : Note * int

Full name: LogMusic.G4

val F4 : Note * int

Full name: LogMusic.F4

1. the example matrix isn’t actually a transition matrix - the row sums should be equal to 1 - it’s here just to demonstrate a possible problem.

2. the sequence C4 - 1/8, E3 - 1/16 is almost the same as C4 - 1/16, C4 - 1/16, E3 - 1/16. That gives us 50/50 transitions: after each period of time C4 can either stay as C4 or transform to E3.

How to Name a Cat

A fun conversation about mountains, monads, types and heels reminded me about the first University years and one of our favourite math jo...… Continue reading

Keywords Mix

Published on March 15, 2016