Skip to content
This repository was archived by the owner on Jun 13, 2025. It is now read-only.
This repository was archived by the owner on Jun 13, 2025. It is now read-only.

more efficient implementation of runMarkov #1068

Closed

Description

@jwaldmann

(will make a PR, just writing down the observation and idea now)

current implemenation is inefficient in several ways (basically, every usage of the list type for storing data for repeated access is questionable)

runMarkov n tp xi seed = reverse -- computes full list before outputting first element
  $ (iterate (markovStep $ renorm) [xi])!! (n-1) where
  markovStep tp' xs = (fromJust
   $ findIndex (r <=) -- linear cost for searching 
 $ scanl1  (+) (tp'!!(head xs) -- linear cost for accessing the matrix
  )) : xs 
 where
    r = timeToRand $ seed + (fromIntegral . length -- computes length each time
  ) xs / fromIntegral n
  renorm = [ map (/ sum x) x | x <- tp ]

of course, this is all quite irrelevant if the set of states is small (e.g., small interval of notes). But perhaps it is not, e.g., if you want to keep previous 2 notes in the state as well.

Ideas for a better implemetation

  • to avoid linear findIndex, use binary search. This only helps when acces by index is fast, so ...
  • instead of [[Double]], use Vector (Vector Double)

My implementation achieves these timings:

tidal> m w = [[ abs(x-y) | y <-[0 .. w-1]] | x <- [0 .. w-1]]

tidal> e = 5 ; w = 10

tidal> drop (10^e) $ runMarkov  (10^e + 10) (m w) 0 0
[6,9,6,3,7,2,7,3,8,3]
(18.34 secs, 162,666,416 bytes)

tidal> drop (10^e) $ runMarkov' (10^e + 10) (m w) 0 0
[6,9,6,3,7,2,7,3,8,3]
(0.18 secs, 87,951,624 bytes)

NB - output also shows that results are identical

Activity

  1. added a commit that references this issue on Jan 28, 2024
  2. sss-create commented on Feb 26, 2025

    @sss-create
    Collaborator

    do you want to make a PR?

  3. added a commit that references this issue on Feb 28, 2025
  4. jwaldmann commented on Mar 7, 2025

    @jwaldmann
    ContributorAuthor

    #1187 not using vector

  5. jwaldmann commented on Mar 12, 2025

    @jwaldmann
    ContributorAuthor

    if this topic comes up again ... a proper solution would be to use Walker's algorithm (for sampling a discrete probability distribution), as implemented in, e.g., https://hackage.haskell.org/package/distribution-1.1.1.0/docs/Data-Distribution-Sample.html (I did no measure performance but it looks like the right thing to do)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions