Showing posts with label refactoring. Show all posts
Showing posts with label refactoring. Show all posts

Tuesday, October 4, 2011

With You in Mind: Some Romantic-Period ‘Directed’, Uncommissioned Chamber Works

Lesser, Ushioda, Schepkin
W   e should get used to the idea that tones have lives of their own, more independent of the artist’s pen in their vitality than one would dare to believe.”
  —  Heinrich Schenker, 1906.
E njoyed New England Conservatory faculty members’ first ‘First Monday’ concert of the season last night…
  • Dvořák: Terzetto in C major, Op. 74, B.148 ... Miriam Fried, Lucy Chapman, violins; Paul Biss, viola
  • Arensky: Trio ... Masuko Ushioda, violin; Laurence Lesser, cello; Sergey Schepkin, piano
  • Brahms: Quintet in G Major, Op. 111 ... Borromeo String Quartet; Kim Kashkashian, viola
T he Terzetto—with the two upper-register voices and the alto voice (viola)—is an interesting texture that leaves us wondering what the tenor/baritone voice (cello) would do had a part been written. Why did Dvořák choose this unusual orchestration—“string quartet minus one”? Well, said Laurence Lesser in his pre-concert remarks, it was because Dvořák wished to honor a violinist friend and the friend’s violin teacher, both of whom lived in the same boarding house where Dvořák himself lived at the time. Simple. Good enough reason as any!

B esides this Terzetto, there is Dvořák’s String Trio in B-flat, Op. 75a, Kodály’s Szerenád for 2 violins and viola, Op. 12, Sergei Taneyev’s Trio, Op. 21, and Frank Bridge’s Rhapsody Trio, H.176. Probably there are more, but I am traveling and not close to a conservatory library to do a decent job of looking them up. In any case, the literature in this space is not large. This repertoire for 2 violins plus viola is not performed nearly as much as it should be. (And, for that matter, the diversity-enhancing decision to compose for non-standard ensembles is not taken nearly as often as it should be either.)

T he viola’s role as an ‘outer’ (bass) voice in the Terzetto sheds light on differences (compared to violin) in viola bow-arm technic: not some violin-style (with hand, wrist, and arm predominantly above the level of the bowstick), the hand and forearm are lower and the upper arm doesn’t move so much. I sat up close, on one side of Jordan Hall to the right of center-stage, far enough to the right where Biss’s movements were not obscured by the music stand. The viola fingering in the Terzetto also presents more than the usual range of challenges, it seems to me. It was wonderful to be able to observe his technic, see his decisions, hear the results.

T he Arensky trio, written in memory of cellist Karl Davydov, was really good. Unusual timbres and textures… the Adagio (Elegia) third movement … the strings’ mutes on throughout. The ‘accessory’ thematic elements to a memorial piece lend depth and verisimilitude—a sort of ‘I remember when’. Ushioda’s touching remembrances, answered by Lesser’s (Davydov’s) inspired and atmospheric replies, modulated by Schepkin’s brilliant and sensitive arbitration/counsel. These are dramatic meditations on the death of a beloved person and, like all elegies, are poetical—with language and cadence governed by impulses of memory. The elegy form tolls departure and loss, irrevocable going-going-goneness… rapturously, ecstatically... often with more of a pastoral or more serene or idealized or sanitized aspect than the person remembered may have had in real life… which is okay and as it should be. We were touched; we are touched; we will continue to be touched.

T he Brahms piece is not elegiac except for the Adagio. It’s instead optimistic and lighthearted, but it is memoristic nonetheless, inspired by Brahms’s walks in the Vienna Prater. By rights, it’s a viola quintet, full of rich alto sonorities. The first movement, Allegro non troppo ma con brio, is in 9/8. Opens with a cello solo in G major, transitions to G minor, with excursions through various other keys before returning to G major. The second movement, the Adagio, begins with a viola solo. The main theme goes through a sort of ‘versioning’ or software refactoring—reimplementing it on different ‘platforms’ and architectures—pondering and recasting the material and, through each refactoring, discovering new dimensions in it and reaching different conclusions. The third movement, Un poco Allegretto, a cheerful minuet and trio form in 3/4, ends with a short coda. And the fourth movement, Vivace ma non troppo presto, is tremendously buoyant and vivacious. Brahms’s pen—and tones—and the Borromeos plus Ms. Kashkashian—had more vitality than one dares to believe…





Tuesday, April 19, 2011

Save The Music!: Writing Refactorable Compositions and ‘Refactor’ Methods

IRCAM tweetsI n my previous CMT post, I confided a genuine ‘worry’ about the perishability of computer and electroacoustic compositions. And people laugh at this.

N otwithstanding the half-jesting comment above that delights in the fact that computer/electroacoustic works may become unperformable due to technology change, and notwithstanding that some musical works are written deliberately to be topical/of-a-time/perishable. They do not aspire to 200-year or 500-year relevance. Further notwithstanding that some composers’ goal is such prolific runtime indirection and aleatorics that there is no possibility of ‘rehearsals’ in the conventional sense, only performance—and ad hoc ‘thrownness’. Notwithstanding the fact that ‘you-shoulda-been-there!’ installation art and ‘one-time happenings’ may be a legitimate aim for some.

N otwithstanding these things, it is sad that works’ performance life ends needlessly, prematurely. Sad when all that is left of them is a recording or two, and no one will ever again hear them performed ‘live’, interpreted by different performers and realized in different settings than the ones on the recordings. Sad unless the expressive intent is to make an object-lesson of senseless carnage, waste, loss.

S orry, but a major facet of the hideous perishability of present-day computer music has to do with the fact that most musicians and composers do not have—nor do they have much desire to acquire—adequate expertise in engineering and fluency in refactoring code. On the one hand they will spend decades mastering multiple instruments and acquiring skill in orchestration, but on the other hand they will not spend a moment acquiring or maintaining skills in engineering that are needed to support preserving their achievements as computer musicians and composers. Boggles my mind.

S o what kinds of software tools and environments, if any, might be adequate for composer/users who lack technical knowledge in programming and software engineering, to enable their works to be performable ‘live’ 20 or more years from now, on different hardware and software than they were composed on? Or, given that computer and electroacoustic compositions involve multiple, complex, heterogeneous embedded (pervasive, ubiquitous) and parallel computing systems, is it even realistic to think that a ready-made end-user integrated development environment (IDE) is even feasible to create—one that would effectively immunize such musicians and their compositions against the ravages of time and technology obsolescence?

M y answer, as one who has lived for 25+ years as a professional software developer in a U.S. health informatics firm whose current-generation of applications comprise more than 37 million lines of sourcecode, is “I do not think so.” I do not think that any tool can comprehensively automate the porting and refactoring, now or ever.

I nstead, I believe that composers who want their works to remain performed and performable will either (a) have to acquire some skills of a code-refactoring engineer and suck it up and spend a modest part of their creative hours doing actual refactoring work, or (b) outsource those refactoring tasks to service contractors who do have those skills.

I n the (b) case, the composer needs to be knowledgeable enough about refactoring to be able to perform quality-assurance checks, to see that the contractor has done the job right, and to be sure that the new version does accurately reproduce the aesthetic choices of the original. Regression testing!

T he “Oh, yes, it [obsolescence, no refactoring, perishing] is wonderful!” quip on the iIRCAM twitter feed (jpeg above) [backhandedly?] feeds a kind of ego-centrism and sensation-mongering. I would love to think it’s harmless snark, a carefree “Here today, gone tomorrow, fine by me!” answer. Probably, that’s all that it is.

B ut the reality is, there’s a lot of remarkable, beautiful music—the result of countless hours of effort and musicianly skill—that today is being allowed to go headlong toward oblivion, all because nobody cares enough to engineer it in such a way as to prevent that. The book links below provide some useful sources that can guide you—that can enable you to learn how to do refactoring of your own compositions to future performance platforms, or to hire somebody else to do this.

Y es, some composers, by their own choosing, will simply decline to preserve their work, or preserve it only temporarily. Sort of like Damian Hirst and his infamous shark in formaldehyde or rotting copulating cow and bull. “Posterity? Not my problem! I won’t be alive then!” That’s fine. Being a Damian Hirst is not a disgrace. Transience is even an enviable fate. I like the idea of cremation, for example. I understand the wish to become atoms, dust.

B ut if you don’t mean to be a Damian Hirst, though, then implementing your version-to-version ‘uplifts’ changes without having to manually rewrite each and every data structure and interface design requires support by another goal: Clean separation and ‘pluggable’ pattern-based interfacing. If one has a synthesis algorithm that plays a particular soundfile or patch in a certain way and with certain timing and through certain channels, then a refactoring should allow that soundfile or patch to be accurately and consistently rendered in the new configuration, through the same or equivalent channels and with the same or indistinguishably different timing and processing, without having to manually reverse-engineer and manually specify each and every detail on the new config.

A ll of this requires an ontology for mapping synonymy of synths and waveform samples and libraries and channels/layers (and modules fan-ins and fan-outs topology, and inter-platform clock timedivision-resultion, and inter-platform sampling-freq and bit-depth skew, and EQ and reverb and other processing idioms, frequencies and pitch-bends, vocoder and compander FX, attack/decay envelopes, and timing, etc.) on different configs…

M ight be done in OWL/RDF or other environments, but such ontology does not yet exist so far as I am aware. Current-generation mapping paradigms range from 2D graphical ‘wire-patching’ of Max/MSP and Pd, to primitive source-code ‘text-based patching’ as in SuperCollider or ChucK, to WorldofWarcraft (and others’) OpenGLES patching of urMus elements, to Marsyas’s Qt4-based patching.

A s things are right now, you do in-line modding of your sourcecode, encapsulating the syntactic result of your work, but not the behaviors of your work. By contrast, true refactorings capture the behaviors and port those behaviors correctly to the new platform(s), not just the syntactic synonymy.

M any refactors that I do in Java/Eclipse are manual, really tedious. There is a refactor to convert an anonymous datatype to nested, and then nested to top-level, but there is nothing to convert a top-level type to anonymous (or nested). Lots of cut-and-paste required. Ultimately, you write your own source-modifying refactors. Chaining other refactors together into a script is only a start.

T ake Max/MSP, for example. Max is a data-flow procedural programming language in which programs are called “patches” and constructed by connecting “objects” within a “patcher”, the 2D Max/MSP GUI IDE. These objects are dynamically-linked libraries, each of which may receive input (through one or more “inlets”), generate output (through “outlets”), or both. Objects pass messages from their outlets to the inlets of connected objects.

M ax/MSP supports six basic atomic data types that can be transmitted as messages from object to object: int, float, list, symbol, bang, and signal (for MSP audio connections). A number of more complex data structures exist within the program for handling numeric arrays (table data), hash tables (coll data), and XML information (pattr data). An MSP data structure (buffer~) can hold digital audio information within main memory. In addition, the Jitter package adds a scalable, multi-dimensional data structure for handling large sets of numbers for storing video and other datasets (matrix data). Max/MSP is object-oriented and involves libraries of objects that are linked and scheduled and dispatched by a patcher executive. Most objects are non-graphical, consisting only of an object’s name and a number of arguments/attributes (in essence class properties) typed into an object box. Other objects are graphical, including sliders, number boxes, dials, table editors, pull-down menus, buttons, and other objects for running the program interactively. Max/MSP/Jitter comes with hundreds of these objects in the standard package; extensions to the program are written by composers and third-party developers as Max patchers (e.g., by encapsulating some of the functionality of a patcher into a sub-program that is itself a Max patch) or as objects written in C, C++, Java, or JavaScript. And those, too, require refactoring from time to time, just like your compositions do.

Refactored DSP Pd-Max/MSP code, PullUpMembersR efactoring can change program behavior. For example, a ‘PullUpMembers’ refactoring changes this Max DSP method that previously was encapsulated in and extends a class ... pulls it up into the class that was previously its parent: that is the example that the A-to-B refactoring above illustrates.

B ut PullUpMembers refactoring causes concurrency bugs when it mishandles the ‘synchronized’ method. When that happens, methods in the parent and child can be time-interleaved in arbitrary ways by the operating system, different from what was the case in the original composition. It messes up the sound. You don’t want that. You need to take special engineerly steps to prevent it. You can’t just ‘plug-and-play’.

M oveMethod refactor methods can cause deadlock and starvation, with mutex and lock conflicts. Other refactoring can give rise to other sorts of bugs. The up-shots of this are that (a) creating an automated-unsupervised refactoring engine for any of the current-generation computer composition IDEs and the scripts/patches they emit would be incredibly difficult and nobody has yet done it [because there’s not enough money in it to make a viable business-case], and (b) doing it auto/semi-supervised or, worse, manually is a tough slog, mitigated only by some considerable skill and fluency in the tools and coding, hence, my remark above that it ain’t gonna happen unless you become a decent engineer as well as musician.

A   ny program feature without an automated test simply doesn’t exist.”
  —  Kent Beck, Extreme Programming Explained, p. 57.
T he video game Half-Life 2 (HL2) uses realtime sound event calls to Pd as its sound OS. Game events are sent from HL2 to the Open Sound Control (OSC) engine, which triggers the sound by Pd via the network. Pd has the sample data and the specified sound-behaviors in-memory and can be instructed to modify those in realtime (perhaps by other game events and other processing of those) without recompiling. WorldofWarcraft uses Lua and Max/MSP.

T hink about it: if composers who are writing and maintaining video game scores across multiple years’ releases and across various gaming platforms do refactorings of their compositions out of economic necessity, why not you? Is your music any less deserving of future live performances than video game music?

W ould IRCAM or conservatories with computer music curricula please add some courseware by engineers who are knowledgeable about refactoring? Save the Music!

T   he secret to creativity is knowing how to hide your sources [and efficiently refactor them in perpetuum].”
  — Albert Einstein, amateur violinist.





Saturday, January 8, 2011

AntiPatterns: Classical Banjo, Code Refactoring, and Short Time-scale Acoustical Physics

O    ne has merely to hear the banjo’s strings touched, or one double-stop drawn out on the fiddle, to recognize the sense in which the meaning of bluegrass begins simply with what these instruments essentially are: it is the aim of bluegrass style to set forth what the instrument—or for that matter the person playing the instrument—essentially is.”
  —  Robert Cantwell, Bluegrass Breakdown, p. 203.
A  thousand kilometers away, one of my nephews is tackling learning banjo. I give him Bullard’s book (link below) and begin listening to exotic recordings by Bela Fleck and John Bullard and others, in hopes of having mutually fun dialogues with my nephew, via email and face-to-face when I go and visit him.

T he banjo sounds on these recordings remind me of the sound—the ‘interiority’, the ‘earnestness’—of traditional shamisen or samisen (三味線, literally “three-taste strings”) music. Shamisen is similar to banjo in that the dō, the skin-covered box, is a lightly-damped resonator, much like the banjo’s. Both instruments are highly percussive and relatively ‘bright’. Both are plucked with the fingers or with a plectrum.

S o I go looking around to see what spectral analysis studies have been published about banjo or shamisen. I am curious to better understand the reasons that explain the unusual tone or timbre of each. Välimäki and coworkers spent a lot of effort on the matter in the mid-1990s (link below). Unlike guitar and other stringed instruments, for banjo the 5th harmonic (fourth overtone; 2P8+M3) and higher harmonics are rapidly attenuated, except for the 8th harmonic (3P8; 3 octaves above fundamental).

S   olid body electric guitars don’t lose much string energy to the bridge. As a consequence they have a distinctive sound and are very long in sustain. Banjos on the other hand dump energy from the strings very easily to the rest of the instrument, and their characteristic sound is in large part related to that.”
  — Liutaio Mottola.
 Välimäki 1996, Fig. 2
T he directionality of the instrument’s sound radiation has a lot to do with banjo-ness, too, I think. Plucked string instruments have complex sound radiation patterns for various reasons. The resonant-mode frequencies of the box account for most of the radiated sound pressure. And different mode frequencies of the body have their own directional patterns, such as monopoles, dipoles, quadrupoles, and their combinations (see examples at UNSW, Joe Wolfe’s site, link below).

A nother distinctive factor is ‘masking’ caused by occultation of the sound by (and reflections from) the performer’s body. Masking plays an important role in environments where the listener (or the recording microphones) and the sound sources are positioned off-axis from each other or are freely moving with respect to each other.

T he influence of “X” vs. “Y” hand position for passages that involve the right-hand moving up the neck of the instrument is yet another factor, one I must remember to explore with my nephew when I next see him. The “X” position lends a bright timbre, and the “Y” position gives a rounder, darker quality. What the the player does with the right-hand on the head of the banjo also changes the timbre/color a lot.

A nd then there is picking technic. Fleck’s jazz-influenced single-string picking style lends an extra “impulsion” to the banjo timbre—a consequence of sympathetic acoustic coupling to and from the other un-plucked strings? The “impulsion” is one of the qualities that I am most attracted to in these recordings.

O h, the sheer exoticness of them, though! The sound calls into question the locale, the culture and politics, and the epoch of each musical text and of each of the speakers (composer, performer) and hearers. The ‘rurality’ of banjo timbre... the instrument’s architecture preserved even in the most refined, expensive ones of modern manufacture with technical polymer engineered-composite materials and high-tech strings.

T he ‘interiority’ of chamber banjo sound is radically different from the interiority of lute or harpsichord. If our own interiority is an object, then the music embodies that ‘objective’ world. Not ‘mimesis’ or ‘representation’; more like incarnation...

P hysical strings vibrate in both the vertical and the horizontal directions (well, actually, more like a lissajous curve in the plane perpendicular to the string’s length, so the polarization directions are changing and are only intermittently orthogonal to each other). If the effective length of the string is not the same in the two predominant polarization planes, we get mixing of the subsignals of slightly different frequencies, which in turn creates beat-frequency pulsations in the sound. This is a distinctive feature not only in banjo but in the Finnish kantele’s timbre as well, where the mechanism has to do with the peculiar way in which the strings have been terminated on the box.

Lissajous pendulum
V älimäki and colleagues emphasize that distinctive timbral properties of banjo are associated with the “attack”, the early transients in the waveform in the few tens of milliseconds immediately after the string is plucked or frailed. But there are wonderful, deeply banjo-ey aspects in the notes’ “decay” as well. We hear those in the Bullard and Fleck recordings. The ‘openness’ of these transcriptions of baroque, classical, and romantic compositions affords closer examination of those timbral spectral features than would ordinarily be possible to do in, say, idiomatic bluegrass and other banjo repertoire.

I t seems to me that these recordings of Bach and other composers’ works on banjo draw our attention to what neurophysiologists call “event fusion” (the formation of unitary musical events from the micro-evolution of waveforms on a time-scale of tens of miliseconds, too small to exhibit rhythm or voice-leading) and its inter-relationships with harmony and melody and rhythm and larger-scale form.

T hese banjo transcriptions and arrangements are unusual, musically speaking, but they register for me as very familiar in other ways. ‘Refactoring’ and ‘porting’ musical “code” from one performance “platform” to another—in the manner that Bullard and Fleck exemplify—feel to me very much like refactoring and porting computer code from one computing platform/language/operating-system/architecture to another. The process calls into question the [psychological; physical] conditions necessary for making large-scale—that is, ‘formal’—interfaces and system services-stack clear in music, just as the refactoring process does in software. The process in both cases invites or even demands reconsideration of the work’s design constructs and architectural components.

I n both, it vividly reveals the different levels of abstraction that are supported or not-so-well-supported by the different platforms. And it can uncover the essence of our interior selves, by making us pay attention to neural logic-races, multi-timescale communications phenomena, and hard-coded “antiPatterns” that the composer or performer (or listener) might not otherwise have noticed. So even if the target transcribe-to platform (banjo) manifests some antiPatterns of its own, it is still always healthy and illuminating to be outside our “comfort zones” and gleaning what we can from the refactoring process.

T he beauty and elegance of these classical banjo recordings make me want to revisit some of my own code that I have recently [re-]written; improve it; maybe understand it from novel and useful perspectives.

A   ll sounds, all colours, all forms—either because of their preordained energies or because of long association—evoke indefinable and yet precise emotions, or, as I prefer to think, call down among us certain disembodied powers, whose footsteps over our hearts we call emotions.”
  — W.B. Yeats, The Symbolism of Poetry.
H   ow can we know the dancer from the dance?”
  —  W.B. Yeats.




Sunday, March 15, 2009

Tabula recompositoria: Amending/Improving Compositions Resembles Software ‘Refactoring’

W    hile composers were [in earlier Centuries] certainly able to work out music in their minds without recourse to writing, at some point the music had to assume a graphic form so that it could be preserved, transmitted, and performed. The evidence suggests that composers employed two different kinds of surfaces for writing down their music: (1) an ‘erasable tablet’ such as a slate that could be used many times and (2) paper. In the period [1450-1600 C.E.] we are considering, the pencil had not yet been invented, so writing on paper meant using pen and ink. Erasure could only be achieved by scraping the ink from the surface of the paper, often resulting in holes in the paper. Paper was therefore a ‘write-once’ medium. Despite the differences in the properties of the two kinds of writing surfaces, composers seem to have used them both in much the same way for all the written stages of a composition, from the earliest sketches to the final version.”
  —  Jessie Ann Owens, p. 74.
 Mozart K.581 Mvt.3 Trio II, mm. 1-12

    [20-sec clip, Umesh Shankar et al, UC Berkeley, 2003, Mozart, K. 581, Mvt. 3, ‘Trio II’, 0.4MB MP3]

M usical sourcecode (the musical score for a composition) is not sacrosanct: we honor the text in our reading of it, but we also take advantage of the interpretive latitude that it affords.

A nd any composer/arranger performs edits upon edits, to clean-up and perfect a work over a period of days to years. Or you create new versions to suit new and different purposes. It’s matter of what software developers would call ‘emergent design’.

Y ou may want to generate a piano reduction, exploding and imploding sectional structures, changing durations and meters, moving layers, manage instrument doublings, etc. .... Johnson’s book (link at bottom of the CMT post) has a good synopsis of these use-cases for MusicXML.

A lternatively, you may want to programmatically change your orchestration and timbres/sonorities, simplify or obfuscate/complexify the rhythms and horizontal relationships, de-risk the voice-leading to make it more natural to perform or sing, change the key to address the realities with regard to black-key biomechanics on keyboards or string-change biomechanics on stringed instruments. More and more use-cases for arrangers and composers!

S uzanne Clercx was the first to document the use of ‘erasable tablets’ by composers when in 1953 she published the discovery of a slate with six staves on each side [termed a ‘tabula compositoria’, ‘cartella’, ‘palierten schiffer stein’, ‘palimpsestus compositorius’, or ‘ardoyse’, depending on the country and century]. MusicXML is simply a latter-day tabula compositoria, that’s all.

W orking as I do on software in my day-job, I am impressed that compositions are homeomorphic to today’s object-oriented software and today’s data networks, including so-called ‘cloud’ computing or ‘software-as-a-service’ (‘SaaS’). All can be complex and difficult to manage.

I  suggest that the root of these problems lies in the complexity of the control and management planes—the orchestration and voice-leading and quasi-protocols coordinating the musical parts; the software and protocols coordinating the objects and network and distributed-services elements—and particularly the way the decision logic and the distributed-systems issues are inexorably intertwined.

I  am impressed that ‘refactoring’ the functionality can improve a composition just as it can improve a piece of software. There is no great profundity or earth-shattering novelty in such a view. It is just something that naturally occurs to any person who spends her/his days working on both software and music.

I  propose three key principles:

  • network-level objectives,
  • network-wide views, and
  • direct control
that I believe should underlie any [new/refactored] architecture, be it an object-oriented software system or a musical composition.

F ollowing these principles, I identify a design pattern that I call ‘4D’, after the architecture’s four planes: decision, dissemination, discovery, and data. A 4D architecture completely separates a network’s/composition’s decision logic from the compositional protocols and performance-practice/runtime protocols that govern the interactions among the network/musician elements.

I n creating a ‘4D’ design pattern, it’s important to remember that MusicXML score files do not represent ‘presentation-level’ primitives such as pages and staff-systems ... such details of formatting will change based on different paper and display sizes. But MusicXML does represent syntactic and semantic concepts of voices (parts) and synchronization among them, segmented into ‘movements’. In the MusicXML environment, in other words, formatting is handled separately from structure and semantics. The same applies for detailed interpretive performance information. Separate MusicXML supersets could be developed to represent individual printings and performances.

R efactoring of MusicXML can, of course, be done off-line—with generation of printed parts and score ahead of performance runtime. My MusicXML source for K.581 Mvt.3 Trio II is here. This (and several Beethoven string quartets) is what I have been testing my prototype MusicXML refactoring engine with this week.

O r the refactoring of MusicXML can be done in realtime—with refactored parts rendered with streaming MusicXML interpreter to be sight-read by the performers, with (I suppose) considerable surprise for artists who are deeply familiar with the original texts—and for listeners as well.

T he realtime MusicXML refactoring works okay so long as the lead-time for the canonical refactoring service is at least one measure ahead of where the musicians are playing. That, to me, seems to be about the minimum for proper scansion and so that phrasing and other effects are not too disrupted.

O f course, this depends on the meter and tempo and the prevailing complexity—things that are making cognitive demands on each performer. If a streaming realtime refactoring is too elaborate, then the aesthetics (and the fun) will undoubtedly suffer.

B eyond this, in principle I suppose one could mike each member of the ensemble and do analog-to-digital conversion of each signal—perform digital signal processing (DSP) and pattern-recognition to impute pitch and interval and rhythm and dynamics deviations from the score—and then use those imputed deviations to drive a refactoring server, to further permute the parts or effect meta-alteration of the downstream score. That’s beyond anything that I’m prepared to attempt right now, but CMT readers with enough studio gear and computational resources may be interested to try it.

    K. 581 Clarinet Quintet (‘Stadler’ Quintet) [1789]
  1. Allegro (A major)
  2. Larghetto (D major)
  3. Menuetto (A major), Trio I (A minor), Trio II (A major)
  4. Allegretto con variazioni (A major)
T he clarinet predominates in K.581 as ‘primus inter pares’ (‘first amongst equals’) as Alfred Einstein once wrote, yet the parts’ roles are more discursive and autonomous than they would be if this were a ‘concertante’ form where the soloist rules.

M y simple experiments initially have dwelt on Mozart’s K. 581, primarily because it is straightforward and familiar. Its interpretive history and performance practice are pretty transparent and well-understood. I wondered, “What if we refactored the Trio II, to render it as an exuberant/obstinate ‘recovery’ from the A-minor Trio I of the 3rd movement?” Okay. Here’s what I get with my canonical XML parser—scanning for and phrase and repeat boundaries in the tokenized MusicXML source.

 Mozart K.581 Mvt.3 Trio II, mm. 1-12
becomes  

 Mozart K.581 Mvt.3 Trio II, mm. 1-12
B asically, my “light” refactoring of K.581 treats every ‘repeat’ structure as a MusicXML ‘class’. You play it through the first time as originally written—that’s the first ‘invocation’ or programmatic ‘call’ to the ‘repeat’ class method with the contents of the bars between the repeat-delimiters as an argument. When you get to the end of the first time through, the method in the ‘main’ class (call it ‘A’) bumps an ‘excursion counter’ and calls the repeat class (call it ‘B’)—with a canonical refactoring argument to dynamically alter the articulation syntax in each part, according to rules I created for my refactoring engine to use.

 DSM Refactoring Engine Architecture
B ut the simple as-written MusicXML source then involves a ‘cycle’ between the ‘main’ class ‘A’ and the ‘repeat’ class ‘B’. If this were a software refactoring, generally we try to eradicate cycles, to localize and manage features and dependencies and to improve reliability and for other reasons. How about doing the same thing in MusicXML, with similar justification? Sure...

 DSM – removing cycles with dependency-inversion DIP
W hat my refactoring of the score does is this:
  • Extract a ‘repeat interface’ BI class from class B. BI contains the methods of class B that are needed by A, to implement the articulations (or other canonical changes that propagate through the quintet’s 5 parts) that we want to be associated with the repeats. The new, refactored class B implements BI.
  • Set all references in class A that aren’t required for object generation from B to BI.
A  simple ‘toy’ example, to be sure, but it is non-trivial—non-trivial in terms of the parser and its embedded logic, and non-trivial in terms of the expressive effects that this has.

I n the end, what we get in this example is a canonical cascading propagation of accents, tenutos, and decrescendos—explicitly amending the expressive sense of the K.581 Trio II. Cool. It works. And it suggests how we could implement other, fancier refactorings and canonical edits.

 Mozart K.581 Mvt.3 Trio II, mm. 1-12 repeat, after canonical XML mark-up with accents, tenutos, diminuendos
M y particular example refactoring of the MusicXML sourcecode for K.581 Trio II is directly analogous to what in the Roock-Lippert software refactoring book is called ‘dependency inversion’ or DIP (see. pp.130-43). Again, I was only exploring here what can be done with current-version MusicXML and refactoring techniques operating on music scores; I am not saying that anything wonderful has been done to K.581 with this attempt. I am only saying that it is interesting, and that it works, and that it may be of interest to you as a composer/arranger or as a music theorist. For CMT readers who are performing artists and avid users of PC-based digital music readers (like Hugh Sung or Nicholas Kitchen) maybe this stuff has interest as well.

T o me, the effort so far seems worthwhile. Yes, MusicXML is not ideal. It’s not a ‘causal encoding format’ and therefore and commands are [must be] used to encode single parts with multiple staves or multiple voices—and so on. While not ideal, MusicXML is the reigning standard that has market-share; it is the ‘bandwagon’ to jump on.

I t’s possible that these refactoring explorations will lead to new MusicXML enhancement-requests or new requirements-specifications for future versions of MusicXML. I’d welcome dialogue with you if you have observations or concerns in that regard. Please email me or comment here if you like. Thanks!

B    rian Foote suggested the name [‘speculative generality’] for a smell to which we are very sensitive. You get this smell when people say, ‘Oh, I think we need the ability to do this kind of thing someday’ and consequently specify all sorts of ‘hooks’ and special-case requirements—to handle things that aren’t in fact required. The result is often harder to understand and maintain. If all this machinery were being used, it would be worth it. But if it isn’t being used, it isn’t [worth it]. The extra machinery [to provide abstract generality] just gets in the way [of clean, effective, testable, maintainable source-code and non-defective solutions] ... Any structure or class that isn’t doing enough to pay for itself should be eliminated ...”
  —  Martin Fowler, p. 83.

A   ndrew Monk and others at University of York in the U.K. It is useful to think about software usability problems as forming a hierarchy with each successive level in the hierarchy requiring more contextualized knowledge. By contextualized knowledge we mean knowledge about a particular user and the goals and priorities which are relevant when the problems are identified. An example of a problem at the bottom of the hierarchy is a user having difficulty in correcting typographical errors because of inadequate delete facilities. This may be a quite general problem independent of the particular user and the task being performed. An example of a problem near the top of the hierarchy is the difficulty that a user might have in understanding how to carry out a database search task on some new system. The problem arises from the user's experience with the system, with other systems and with the task it is being used for and so depends very much on the context. Such problems often have a large impact on usability. By definition, these problems require information about the user's knowledge and beliefs in order to diagnose their cause, and to recommend the changes needed. Work at University of York has attempted to develop methods which elicit increasing amounts of context-sensitive data which can be used to diagnose problems at successively higher levels of this hierarchy and have identified four diagnostic levels. At the first level are problems that can be identified from system logs recorded from unknown users during free use. An approach was developed which identifies problems by isolating redundant user input. These problems can be diagnosed with minimal user-specific or task-specific information. A second level involved the analysis of log data from users completing tasks which have been set by the evaluator of the system. When these tasks are well constrained the system evaluator can use them to gain partial information about the users’ plans and goals when problems occur. This method is not always adequate since strategic differences amongst subjects can make plans and goals difficult to infer. A third level used verbal protocol methods to elicit users’ plans and goals directly. Two methods have been used re-enactment. Re-enactment proved particularly useful for diagnosing problems that could not be diagnosed from log data alone. In this method the user and evaluator discuss problems that the user had experienced during previous sessions.

Techniques that allow for more abstraction
  • Encapsulate Field - force code to access the field with getter and setter methods
  • Generalize Type - create more general types to allow for more code sharing
  • Replace type-checking code with State/Strategy
  • Replace conditional with polymorphism
Techniques for breaking code apart into more logical pieces
  • Extract Method, to turn part of a larger method into a new method. By breaking down code in smaller pieces, it is more easily understandable. This is also applicable to functions
  • Extract Class moves part of the code from an existing class into a new class
Techniques for improving names and location of code
  • Move Method or Move Field - move to a more appropriate Class or source file
  • Rename Method or Rename Field - changing the name into a new one that better reveals its purpose
  • Pull Up - in object-oriented programming (OOP), move to a superclass
  • Push Down - in OOP, move to a subclass
  • Shotgun surgery - in OOP, when a single change affects many classes—all affected code is kept in a single class, so that the change is made only in one place.”