Looking for advice on architecture of a music program

A few years ago I wrote a Haskell program for translating MusicXML scores (coming from music typesetting software like Sibelius, Dorico, or MuseScore) into MIDI events, in a way that provided custom interpretation of the scores and score objects. I did this to experiment with ways of adding flexible expression to a score that would otherwise sound stiff if played by the typesetting software itself or a DAW.

There are some existing Haskell music packages but none of them allowed me to do enough customization to explore the specific ideas I had in mind, so I wrote from scratch.

I just came back to my program after several years of using it but not looking at the source. It’s pretty dreadful. I need to make some changes and it’s hard to understand how to make them. I think it might be worth rewriting.

Note that one of the simplest ways to express how a score gets translated into MIDI (which is necessarily a pretty complex task) is to define several stages of the translation. In the first stage, we represent a score by a one-to-one representation of objects in the original score. In the second stage, we translate the notes on the score to a kind of pseudonote, which is like a note but has a lot of context added to it and some alterations, perhaps altered in time or pitch. It is also possible that a score note gets translated into 0, 1, or many pseudonotes. In the third stage the pseuonotes are translated into MIDI events, again with a possible many-to-one relationship.

What I’m thinking of doing is using a state monad that stores the entire context and history of the translation. What I’m doing in the existing program is pass around just the needed context. But when I make significant changes to the “model” of what the program is doing (like say, I introduce the idea that notes can be shifted in time by absolute seconds rather than the previous model which was shifting by beats), I find myself frustrated by the need to change what is being passed around.

The algorithms are necessarily complex. What I want to try to do is write easily understood functions. Each function will do some transformations or generations of data following the necessary steps, which will be named as clearly as possible and listed sequentially. All context will be available to read at every stage. As far as generating new data, there will be some Maybe fields which are initialized to Nothing and gradually change to things like Just Stage2 as the sequence of steps is followed.

Another complexity is that I want good error messages. I could perhaps chain an Error monad with my State monad. Also I could put a random generator in the state for those parts of the translation that use randomness.

sounds like trees that grow ( The AST Typing Problem) and things like uniplate ( Control.Lens.Plated) could help

thanks. I need to learn a lot more about generics and trees that grow. I’m not strong in the more abstract parts of Haskell. I’m an advanced beginner. Do you recommend any sources that explain this stuff at my level? I think I might need to start with generics.

I think your data separation notes/pseudonotes/midi is a good and reasonable starting point.

You might want to study the design of other Haskell music libraries like Tidal and their abstractions.

From a design perspective, you might want to make a choice whether transformations and the transformed notes should be conceptually different. Meaning, does a later transformation need to know what parts of the music have been altered, and how? Or is the altered music itself enough evidence for a subsequent transformation to work? Notice that a state monad will not help you there: If m1 :: State s a and m2 :: State s b then in m1 >> m2 there is no way for m2 to learn what m1 has changed in the state. Also note that State s () is the same as Endo s.

In contrast, you could have an algebraic type Change (an EDSL) that acts on pseudonotes:

change :: Change -> Pseudonotes -> Pseudonotes

perhaps with a Semigroup operation such that <> is translated via change into function composition:

change (c1 <> c2) = change c1 . change c2

Then you could have higher-order changes Change -> Change that thereby have access to what other changes did. Is that what you meant by “history”?

My suggestion: do the simplest thing that could possibly work, until you start to notice where you need to add extensions to your AST or annotations to your nodes. Alexis King has a great talk on The Unreasonable Effectiveness of Constructive Data Modelling where she discusses how to get all sorts of safety properties from careful data structure design instead of advanced language features.

If that proves insufficient, my personal experience with Trees That Grow is the full technique in the paper is very boilerplatey. You can get a lot of benefit out of using a single type parameter of kind Phase, where Phase is something you define, like type data Phase = Scored | Annotated | Evented (see -XTypeData if you’re unfamiliar) and consider closed type families where a constructor needs to change payload in each phase.

Another approach is to bake all the variants into a single GADT but use the phase parameter to exclude certain constructors:

type data Phase = One | Two

data Ast (phase :: Phase) where
  CommonToAll :: Ast phase -> Ast phase -> Ast phase
  OnlyInPhaseOne :: Int -> Ast One
  OnlyInPhaseTwo :: Text -> ByteString -> Ast Two

This will cost you the ability to derive a Generic instance for Ast phase, though you might be able to derive instances for specific phases, I forget. It also means that if you use the Plated machinery in lens, you will have to define the instances by hand (but they’re not that bad, in a just-follow-the-types sort of way).

A third thing you might consider looking at is John Wigley’s work on using Recursion Schemes in ADTs for his Nix interpreter. This might be more useful to you if you’re consistently interleaving the same annotations between nodes instead of having to change the payloads of different nodes in different ways.

But Haskell is great for refactoring, so I’d look to get something simple working first and then figure out how to abstract over the common parts of each phase’s AST.

I echo this post. What helped me learn about more advanced techniques was just trying the simple techniques, find what I couldn’t do (or what needed a bunch of hacks) and go from there. It’s harder to read about a novel technique and know how to adapt it for your case, than doing a naive hardcoded version of the technique to solve your problem and realizing how it’s generalized

First, thanks for everyone for the details. I will be thinking about these.

Regarding the idea of starting simple, the current program already passed through stages of simple to complex. I feel like I might be able to spot abstractions right now.

Also, I think I can make the program structure a lot simpler now that it will contain the wisdom of a version 2.0.

As an example of evolving complexity, initially it treated every instrument independently, so the functions that did the translation had signatures like Instrument -> [PseudoNote] Then later, it became necessary for the kinds of expression I wanted for multiple staves to interact so I needed [Instrument] -> Instrument -> [PseudoNote] or something sort of like that. It seems simpler to pass around the entire original score and all the configuration. At least it would reduce the number of parameters.

Regarding the need to store history: Take alterations of note begin and end times. There are four reasons for these. The notes pass through a series of steps at which each of those alterations is possibly applied, a lot of steps (9 total). To aid in debugging, I store the history of what each step does. So when there’s something strange in the sound, I can write that note to a file and study it.

Anyway this is all great stuff.

I work on a program which is similar in that it is taking high level score to low level MIDI or lilypond or audio, but different in that the source score is not a predefined staff notation format, but its own format, which is effectively a little language that gets evaluated. So it’s different in that the source score is all “dynamic” in that there is no fixed list of notations but they are expressions, but you could see staff notation as simply a subset where the input vocabulary is fixed.

That means I made no attempt to say enumerate ornaments or pitches, but it’s structured as an interpreter. The input is simple score level events, which are (start, dur :: ScoreTime, text :: Text), where interpretation evaluates the text expression. Evaluation happens in a dynamic scoped context, where part of it is a “warp” which is just a function from ScoreTime to RealTime, and the “IR” is a generic Event { start, dur :: RealTime, controls :: Map Control Signal }. Because the warp is available in dynamic scope of the interpreter, things like a “trill” ornament can work in either ScoreTime or RealTime, and e.g. decide to maintain a certain speed by adding cycles, or maintain number of cycles but stretch them. Since warps compose (function composition), fragments of score can be combined under tempo curves and ornaments respond appropriately (or in more elaborate ways, e.g. some may change playing technique depending on tempo, which is the derivative of the warp). Controls are also not just signals, there are e.g. sets of attributes so you can apply pizz or sul pont or something over a region, and it’s the backend’s job to interpret that into keyswitches or other signals or what have you.

Then there are a set of transformations which go [Event] -> [Event], they work in RealTime and are for things like instrument techniques that can work in RealTime and may need to know the future (e.g. position shifts, damping, string tensioning).

Then there are backends that would take medium level [Event] to e.g. low level [MidiEvent]. An optional pitch is also a curve inside controls. I have an elaborate format where they’re abstract and can be transposed diatonically, chromatically, or any number of other ways before lowering to a raw frequency, but if you are in 12TET exclusively you don’t need that. Oh right, and instrument is available at interpretation time because it can make notation available or override it (idiomatic trill varies), but does the same dynamic scoping thing so Event retain it and the backend can then use it to know about about stuff like MIDI channel allocation, pitch bend range, etc.

Anyway, it is indeed complicated, and there are awkward corners to do with order of evaluation (e.g. a performer level notation needs to work abstractly at ScoreTime but then also needs to leave behind some lower level annotations for a postprocessing step). But it’s extensible and has no complicated ASTs or types. The equivalent of type safety is pretty much a non-issue, because a music score is interpreted once, all the way through, and the interesting internal invariants can’t be captured anyway (e.g. that events remain sorted, that they don’t look too far into the future and spoil streaming, etc.).

The basic structure is an interpreter monad which has dynamic scope (ReaderT). The output is basically [Either Error Event], and exceptions are limited to the note level, so the whole output can remain streaming. Since they’re time sorted, you can merge multiple streams of them. The streaming-ness means the whole pipeline is lazy so e.g. the MIDI backend can force it incrementally. You probably don’t need that if you are doing batch realization, but it’s still useful if e.g. a note 5m in crashes, you still get the rest of the output, rather than just a single Left "oh no". I also have a few pure text score → [Event] pipelines, and they use the same [Either Error Thing] pipeline style. I use a type with various utilities like a mapAccumL and zips, etc.

Anyway maybe this is just a big complicated way to say, consider structuring as an interpreter. You will likely have the same problem, which is that some notations need to work abstractly and some concretely. If you work purely with concrete data, you may have lost the ability for ornaments to respond abstractly to their environment. In addition your data structures may get hairy when you realize there are actually maybe 8 kinds of trills, or percussion doesn’t have pitch or duration, or wait some percussion does, or wait some percussion has certain pitched strokes but unpitched other ones, etc. The other thing is because an interpreter can start simple, you could start with plain note in → MIDI event out with no (initial) need to model tempo or ornaments or whatever, and not get tangled in ASTs.

Oh right, and WRT “history”, Events also have logs to attach for notes, and a stack, which represents their call stack in the context of the score (which is hierarchical, with a flat score you would just need a ScoreTime or measure:beat type thing), which then can be clicked on in an error to highlight the offending original note. So yeah I also like this idea. You need provenance to debug complicated transformations.

Also, for randomness, I derive it from a seed which comes from the stack, or can be declared. The idea is the same thing in the same place of the score will be random in the same way every time, because you want it to be deterministic, and also you may want to manually nail down something you liked.

Also, just randomly, I watched the talk and she had a “time extent” example, and in fact I do use (start, dur) but also have negative durations. Ultimately because some ornaments start at a time and e.g. take their pitch from the start of that time, while others are leading to a time, and take their pitch from the arrival rather than the departure, and are better thought of as extending backwards rather than forwards. I believe European music doesn’t really use this concept very systematically so you probably don’t have to worry about it, but you could model certain things this way, such as grace notes or appoggiatura. Just another example how music can break all the invariants you thought you had.