As mentioned in closing the last post, I did not yet complete all the refactorings I had on my to‑do list. A few of those being repeating small step sequences, allowing a step sequence to run into the next measure, and dealing with incidentals in the scale. But I may leave those items for the time being and play a little more with the movement within a step sequence. Something I have been ruminating over for a while now.
Step Sequence Movement
Currently I feel the code in the wrtMldySteps() steps method tends to make the sequence too directional. Whether that be up or down. And perhaps that the code in getStepDir() tends to overly favour “up” for the antecedent phrase. Haven’t confirmed but expect it will overly favour “down” in the consequent phrase. To start, I am going to play with getting a more varied movement in a step sequence.
Time to Play
The current approach essentially uses rng.choice to select from two options for movement direction, then two options for movement size. The code uses a probability of 80% for the general direction of movement and 90% for a single tone step. I want to play with those probabilities. But I am going to combine the choice of direction and size in a single value.
For now I am only going to look at generating and displaying step sequences using various probability combinations and see what I get. Will only look at using the ideas to generate step sequences if I think they add something of value to the generation of a melody. So, let’s play.
To help out, I added two functions. The first generates the step sequence using the current rules. The second uses a passed list of probabilities to sort out a sequence of steps. Then I loop through a subset of the possible sequence lengths and some test probability combinations. Hopefully that gives me some idea of how each probability combination affects the sequence generated. A fair bit of code given it may never be used. But experimentation is, in the context of this project, likely valuable in its own right. And, its not like I don’t usually have some spare time available for playing about.
if __name__ == '__main__':
@dataclass
class StepProbability:
# figure out probabilities for current step sequence method
# s_szs = rng.choice([1, 2], s_nbr - 1, [.8, .2])
# t_dir = rng.choice([s_dir, o_dir], s_nbr - 1, p=[.9, .1])
# [.1, .1, 0, .9, .9] -> [.02, .08, 0, .72, .18]
# old + new test probabilities
s_prbs = [
[.02, .08, 0, .72, .18],
[0.05, 0.25, 0.05, 0.60, 0.05],
[0.1, 0.2, 0.1, 0.5, 0.1],
[0.075, 0.325, 0.075, 0.45, 0.075],
[0.2, 0.25, 0.1, 0.25, 0.2],
# [0.2, 0.3, 0.0, 0.3, 0.2],
[0.15, 0.3, 0.1, 0.3, 0.15],
]
def base_step_sequence(s_dir, s_nbr):
ss_stps = [] # for dev tracks step direction and size
o_dir = "down" if s_dir == "up" else "up"
# determine first note in the series
# how many steps from previous note, I am assuming up to 2 tones, not semitones
s2nt = rng.choice([1, 2])
ss_stps.append(f"{s_dir} {s2nt}")
# let's get the rest of the notes
# 1st determine the step size for each note in sequence, 1 or 2
s_szs = rng.choice([1, 2], s_nbr - 1, [.8, .2])
t_dir = rng.choice([s_dir, o_dir], s_nbr - 1, p=[.9, .1])
# want first one of this series going in the chosen direction
t_dir[0] = s_dir
for i in range(s_nbr - 1):
ss_stps.append(f"{t_dir[i]} {s_szs[i]}")
return ss_stps
def getStepSeq(s_dir, s_nbr, use_p=[]):
ss_stps = []
s2nt = rng.choice([1, 2])
ss_stps.append(f"{s_dir} {s2nt}")
s_chcs = [-2, -1, 0, 1, 2]
if not use_p:
use_p = [0.05, 0.25, 0.05, 0.60, 0.05]
s_stps = rng.choice(s_chcs, s_nbr-1, p=use_p)
o_dir = "down" if s_dir == "up" else "up"
for x in s_stps:
ss_stps.append(f"{o_dir if x < 0 else s_dir} {abs(x)}")
return ss_stps
mldy_cfg = MelodyConfig(t_sig=(4, 4), r_oct=5, dbg=False)
print(f"\n{mldy_cfg}")
r_nt, s_qual = "A", "major"
mldy = Melody(r_nt, s_qual, mldy_cfg)
print(f"\nscale: {mldy.s_nts}")
# play with step sequence movement
if True:
# get dicts to allow switching between scale notes and their
# roman numeral equivalents
t_n2r, t_r2n = mldy.rn2nts()
# initialize melody framework
mldy.sortInitFW(t_r2n)
# initialize step direction
s_dir = rng.choice(["down", "up"])
# get test probability combinations
sp = StepProbability()
pi_mx = len(sp.s_prbs)
for sl in [3, 5, 6, 8]:
print(f"\nstep sequences of length {sl}:")
s_dir = "up" if s_dir == "down" else "down"
t_stps = base_step_sequence(s_dir, sl)
s_lbl = "base/old sequence"
l_spc = " " * (37 - len(s_lbl))
print(f"\t{s_lbl}:{l_spc}{t_stps}")
for pi in range(1, pi_mx):
# longest label 36 chr
l_spc = " " * (35 - len(str(sp.s_prbs[pi])))
t_stps = getStepSeq(s_dir, sl, use_p=sp.s_prbs[pi])
print(f"\tp={sp.s_prbs[pi]}:{l_spc}{t_stps}")
And a test run. I have manually added the sum of the steps in the different directions for each sequence. Thought that might give me a measure of the volatility of the various probability combinations. But, probability being what it is, not sure I got much information based on one test run.
PS R:\learn\e_m_311> uv run tst_melody.py
MelodyConfig(pd_len=8, r_oct=5, t_sig=(4, 4), s_bt=0.5, dbg=False)
scale: ['A5', 'B5', 'C#5', 'D5', 'E5', 'F#5', 'G#5']
step sequences of length 3:
base/old sequence: ['down 2', 'down 2', 'down 1'] (+5)
p=[0.05, 0.25, 0.05, 0.6, 0.05]: ['down 2', 'down 1', 'up 1'] (+4)
p=[0.1, 0.2, 0.1, 0.5, 0.1]: ['down 1', 'down 1', 'down 0'] (+2)
p=[0.075, 0.325, 0.075, 0.45, 0.075]: ['down 2', 'down 1', 'up 1'] (+2)
p=[0.2, 0.25, 0.1, 0.25, 0.2]: ['down 2', 'up 1', 'down 2'] (+3)
p=[0.15, 0.3, 0.1, 0.3, 0.15]: ['down 1', 'down 1', 'down 2'] (+4)
step sequences of length 5:
base/old sequence: ['up 2', 'up 1', 'up 1', 'up 2', 'up 2'] (+8)
p=[0.05, 0.25, 0.05, 0.6, 0.05]: ['up 2', 'up 1', 'down 1', 'up 1', 'up 1'] (+4)
p=[0.1, 0.2, 0.1, 0.5, 0.1]: ['up 1', 'down 1', 'up 1', 'down 2', 'up 1'] (0)
p=[0.075, 0.325, 0.075, 0.45, 0.075]: ['up 2', 'down 1', 'up 1', 'down 1', 'up 1'] (+2)
p=[0.2, 0.25, 0.1, 0.25, 0.2]: ['up 2', 'up 2', 'up 1', 'up 2', 'up 0'] (+7)
p=[0.15, 0.3, 0.1, 0.3, 0.15]: ['up 1', 'up 2', 'up 2', 'up 2', 'down 1'] (+6)
step sequences of length 6:
base/old sequence: ['down 2', 'down 2', 'up 2', 'up 2', 'down 2', 'down 1'] (+3)
p=[0.05, 0.25, 0.05, 0.6, 0.05]: ['down 1', 'up 2', 'up 1', 'down 1', 'down 2', 'up 1'] (+2)
p=[0.1, 0.2, 0.1, 0.5, 0.1]: ['down 1', 'down 1', 'down 1', 'down 2', 'down 1', 'up 2'] (+4)
p=[0.075, 0.325, 0.075, 0.45, 0.075]: ['down 2', 'down 1', 'down 1', 'up 1', 'down 1', 'down 0'] (+4)
p=[0.2, 0.25, 0.1, 0.25, 0.2]: ['down 1', 'up 1', 'up 1', 'down 0', 'down 1', 'down 2'] (+2)
p=[0.15, 0.3, 0.1, 0.3, 0.15]: ['down 1', 'up 2', 'down 0', 'down 2', 'up 2', 'down 2'] (+1)
step sequences of length 8:
base/old sequence: ['up 1', 'up 1', 'up 2', 'up 2', 'up 2', 'up 2', 'up 2', 'up 1'] (+13)
p=[0.05, 0.25, 0.05, 0.6, 0.05]: ['up 2', 'up 1', 'up 1', 'down 1', 'down 2', 'up 2', 'up 1', 'up 1'] (+5)
p=[0.1, 0.2, 0.1, 0.5, 0.1]: ['up 1', 'up 1', 'up 1', 'up 2', 'up 0', 'down 2', 'up 1', 'up 1'] (+5)
p=[0.075, 0.325, 0.075, 0.45, 0.075]: ['up 2', 'down 1', 'up 1', 'up 2', 'up 0', 'up 1', 'up 1', 'up 2'] (+8)
p=[0.2, 0.25, 0.1, 0.25, 0.2]: ['up 2', 'down 2', 'down 1', 'down 1', 'down 1', 'down 2', 'up 2', 'up 1'] (-2)
p=[0.15, 0.3, 0.1, 0.3, 0.15]: ['up 1', 'down 1', 'down 1', 'up 1', 'down 2', 'up 2', 'up 1', 'down 2'] (-1)
Definitely unsure what the above data tells me. But, it does seem to me, that the latter probabilities do generate a more energetic step sequence. Especially for longer sequences. Though I’m not sure about those down/up 0 cases.
Make Music
I think what I will do now is convert those step sequences into actual musical sequences. I.E. real notes and durations. Then perhaps I will create a score with the variations running in sequence and have a listen.
For now I plan to ignore the step sequence range limitations that are in place in the current version of the Melody class. This is after all experimentation. But, that may mean writing a new function or two. We shall see.
... ...
def bldNtSeq(mldy, seq_sz, ss_stps, st_nt, n_bts):
ss_nts = []
nx_nt = st_nt
s_durs = mldy.getStepDurs(seq_sz, n_bts=n_bts)
for x, stp in enumerate(ss_stps):
s_dir, s_sz = stp.split(" ")
nx_nt = mldy.getNtSteps(int(s_sz), s_dir, prv_nt=nx_nt)
ss_nts.append((nx_nt, s_durs[x], mldy.n_durs.n_dur[s_durs[x]]))
return ss_nts
... ...
for pi in range(pi_mx):
... ...
s_nts = bldNtSeq(mldy, sl, t_stps, st_nts[x], n_bts)
ss_nts.append(s_nts)
print(f"\n\t{ss_nts}")
The modified code generates the note sequences and prints to the terminal. The terminal output follows; just the note sequences being shown.
PS R:\learn\e_m_311> uv run tst_melody.py
... ...
step sequences of length 3:
... ...
[[('F4', 'hlf', 1.0), ('D4', 'qtr', 0.5), ('C4', 'qtr', 0.5)], [('F4', 'qtr', 0.5), ('E4', 'hlf', 1.0), ('F4', 'qtr', 0.5)], [('G4', 'qtr', 0.5), ('F4', 'hlf', 1.0), ('F4', 'qtr', 0.5)], [('F4', 'qtr', 0.5), ('E4', 'qtr', 0.5), ('F4', 'hlf', 1.0)], [('F4', 'hlf', 1.0), ('G4', 'qtr', 0.5), ('E4', 'qtr', 0.5)], [('G4', 'qtr', 0.5), ('F4', 'hlf', 1.0), ('D4', 'qtr', 0.5)]]
step sequences of length 5:
... ...
[[('E5', 'qtr', 0.5), ('F5', 'qtr', 0.5), ('G5', '8th', 0.25), ('B6', '8th', 0.25), ('D6', 'qtr', 0.5)], [('E5', 'qtr', 0.5), ('F5', 'qtr', 0.5), ('E5', '8th', 0.25), ('F5', 'qtr', 0.5), ('G5', '8th', 0.25)], [('D5', 'qtr', 0.5), ('C5', '8th', 0.25), ('D5', '8th', 0.25), ('B5', 'qtr', 0.5), ('C5', 'qtr', 0.5)], [('E5', 'qtr', 0.5), ('D5', 'qtr', 0.5), ('E5', '8th', 0.25), ('D5', '8th', 0.25), ('E5', 'qtr', 0.5)], [('E5', 'qtr', 0.5), ('G5', '8th', 0.25), ('A6', 'qtr', 0.5), ('C6', '8th', 0.25), ('C6', 'qtr', 0.5)], [('D5', 'qtr', 0.5), ('F5', 'qtr', 0.5), ('A6', '8th', 0.25), ('C6', 'qtr', 0.5), ('B6', '8th', 0.25)]]
step sequences of length 6:
... ...
[[('C5', '8th', 0.25), ('A5', '8th', 0.25), ('C5', '8th', 0.25), ('E5', '8th', 0.25), ('C5', 'qtr', 0.5), ('B5', 'qtr', 0.5)], [('D5', '8th', 0.25), ('F5', '8th', 0.25), ('G5', 'qtr', 0.5), ('F5', '8th', 0.25), ('D5', '8th', 0.25), ('E5', 'qtr', 0.5)], [('D5', 'qtr', 0.5), ('C5', '8th', 0.25), ('B5', '8th', 0.25), ('G4', '8th', 0.25), ('F4', '8th', 0.25), ('A5', 'qtr', 0.5)], [('C5', 'qtr', 0.5), ('B5', '8th', 0.25), ('A5', '8th', 0.25), ('B5', 'qtr', 0.5), ('A5', '8th', 0.25), ('A5', '8th', 0.25)], [('D5', '8th', 0.25), ('E5', 'qtr', 0.5), ('F5', '8th', 0.25), ('F5', '8th', 0.25), ('E5', '8th', 0.25), ('C5', 'qtr', 0.5)], [('D5', '8th', 0.25), ('F5', '8th', 0.25), ('F5', '8th', 0.25), ('D5', '8th', 0.25), ('F5', 'qtr', 0.5), ('D5', 'qtr', 0.5)]]
step sequences of length 8:
... ...
[[('G5', '8th', 0.25), ('A6', '8th', 0.25), ('C6', '8th', 0.25), ('E6', '8th', 0.25), ('G6', '8th', 0.25), ('B7', '8th', 0.25), ('D7', '8th', 0.25), ('E7', '8th', 0.25)], [('A6', '8th', 0.25), ('B6', '8th', 0.25), ('C6', '8th', 0.25), ('B6', '8th', 0.25), ('G5', '8th', 0.25), ('B6', '8th', 0.25), ('C6', '8th', 0.25), ('D6', '8th', 0.25)], [('G5', '8th', 0.25), ('A6', '8th', 0.25), ('B6', '8th', 0.25), ('D6', '8th', 0.25), ('D6', '8th', 0.25), ('B6', '8th', 0.25), ('C6', '8th', 0.25), ('D6', '8th', 0.25)], [('A6', '8th', 0.25), ('G5', '8th', 0.25), ('A6', '8th', 0.25), ('C6', '8th', 0.25), ('C6', '8th', 0.25), ('D6', '8th', 0.25), ('E6', '8th', 0.25), ('G6', '8th', 0.25)], [('A6', '8th', 0.25), ('F5', '8th', 0.25), ('E5', '8th', 0.25), ('D5', '8th', 0.25), ('C5', '8th', 0.25), ('A5', '8th', 0.25), ('C5', '8th', 0.25), ('D5', '8th', 0.25)], [('G5', '8th', 0.25), ('F5', '8th', 0.25), ('E5', '8th', 0.25), ('F5', '8th', 0.25), ('D5', '8th', 0.25), ('F5', '8th', 0.25), ('G5', '8th', 0.25), ('E5', '8th', 0.25)]]
Score of Test Sequences
I opened a new score in MuseScore and set the key signature to A Major. So those C, F, and Gs in the above note sequences will in fact become sharps. The use of incidentals in the key signature is not something I have yet sorted out when generating step sequences. For each group, based on sequence size, I added the sequences in consecutive measures with an empty measure between groups. Here’s what the score looks like.

One of the first things I noticed was, that for each step sequence size, the notes used in each measure were the same in duration and number. Different orders perhaps but otherwise more or less the same to my eyes and ears. Not really what I want to see in gnerated music down the road. Something to add to my refactoring to-do list.
And, pretty clearly, the current step generation code really tends to just go up or down. Though, exhibiting an infrequent change of direction during the occasional sequence.
The score sounds like this.
Statistics?
I decided to try to take a statistical look at how much step variability those different probability combos create. I plan to use the sum of the integer step values as a proxy for the measure of variability. My thinking is for any given sequence length, the smaller that sum, the more movement there was in the sequence in both directions. Random selection being what it is, the integer sequence for any given probability combination can match another. But, I am hoping a reasonable sample size will show a trend if it exists.
Now, not being at all well versed in statistics, I have no idea if what I am going to do is at all reasonable or correct. That said…
I am going to for a single step sequence size, 5, generate a sample for each of the six probabilities we have been looking at. Then plot the normal distribution for each sample. As usual, there will likely also be some terminal output (useful or otherwise).
if True:
# let's get some stats for the probability combinations
# well at least one or two
# get probabilities
sp = StepProbability()
# set some parameters
s_nbr = 500 # sample size for each probability
sd_cnts = [] # counts by sample sums by prob combo
c_mus, c_sigs = [], [] # mean and standard deviation for each sample
sq_dir = "up"
sq_sz = 5 # number of steps in each sequence
mx_sp = len(sp.s_prbs) # maximum index for prob combo list
# curiosity, how long sample generation takes
stm = time.process_time()
for sp_i in range(mx_sp):
s_sums = []
for _ in range(s_nbr):
t_stps, t_ints = getStepSeq(sq_dir, sq_sz, use_p=sp.s_prbs[sp_i])
s_sums.append(sum(t_ints))
cs = Counter(s_sums)
d_cs = dict(cs)
d_cs = dict(sorted(d_cs.items()))
sd_cnts.append(d_cs)
c_mus.append(np.mean(s_sums))
c_sigs.append(np.std(s_sums))
etm = time.process_time()
print(f"\ntook {(etm - stm):.2f} sec")
print(f"\ncounts:")
for sx, d_cs in enumerate(sd_cnts):
print(f" prob {sx} ({len(d_cs)}, {c_mus[sx]:.1f}):\n {d_cs}")
# plot normal probabilty distribution for each sample
plt.figure(figsize=(8, 6))
for p_i, d_cs in enumerate(sd_cnts):
cs_st = list(d_cs.keys())
cs_tn = list(d_cs.values())
mu = c_mus[p_i]
sig = c_sigs[p_i]
p_lbl = f"p{p_i}: {mu:.1f} \U000000B1 {sig:.1f}"
x = np.linspace(mu - 4*sig, mu + 4*sig, 50)
y = norm.pdf(x, mu, sig)
plt.plot(x, y, label=p_lbl)
plt.legend()
plt.savefig(f"img/seq_var_s{sq_sz}_1.png")
plt.show()
exit(0)
Here’s the terminal output for a sample run.
PS R:\learn\e_m_311> uv run tst_melody.py
MelodyConfig(pd_len=8, r_oct=5, t_sig=(4, 4), s_bt=0.5, dbg=False)
scale: ['A5', 'B5', 'C#5', 'D5', 'E5', 'F#5', 'G#5']
took 0.50 sec
counts:
prob 0 (10, 15.4):
{9: 1, 11: 7, 12: 9, 13: 55, 14: 55, 15: 111, 16: 124, 17: 98, 18: 36, 19: 4}
prob 1 (14, 12.9):
{6: 1, 7: 1, 8: 8, 9: 30, 10: 36, 11: 59, 12: 69, 13: 82, 14: 85, 15: 63, 16: 50, 17: 12, 18: 3, 19: 1}
prob 2 (14, 12.6):
{6: 1, 7: 13, 8: 12, 9: 25, 10: 48, 11: 62, 12: 62, 13: 88, 14: 67, 15: 73, 16: 34, 17: 11, 18: 3, 19: 1}
prob 3 (14, 12.0):
{5: 6, 6: 3, 7: 9, 8: 22, 9: 42, 10: 55, 11: 72, 12: 69, 13: 66, 14: 78, 15: 44, 16: 24, 17: 9, 18: 1}
prob 4 (17, 11.5):
{4: 4, 5: 4, 6: 15, 7: 18, 8: 28, 9: 56, 10: 62, 11: 63, 12: 67, 13: 55, 14: 46, 15: 35, 16: 26, 17: 11, 18: 7, 19: 2, 20: 1}
prob 5 (16, 11.7):
{3: 1, 5: 1, 6: 6, 7: 24, 8: 31, 9: 38, 10: 73, 11: 65, 12: 75, 13: 63, 14: 56, 15: 26, 16: 20, 17: 12, 18: 6, 19: 3}
And, here’s the plot of the probability distribution for each probability combination.

Now to me, I think the above does indicate that there is a more or less consistent increase in sequence variability as we go down the list of available probability combinations to generate step sequences. Though in a goodly number of test runs, the 2nd last probability had a slightly higher variability than the last one. Another indicator, I believe, is the total number of unique sums (first number in brackets in the terminal output) in each sample. The larger the number the more likely a probability of more variability for that probability combination. At least that’s how it looks to me.
As I felt there was likely a connection between the length of a sequence and the potential for step variability I ran the code for sequences of size 3 and 8. Here’s the plots for those two (no terminal output).

And, I would say the degree of variability is definitely influenced by the step sequence’s length. Perhaps more so than the probabiltiy combination being used.
This One Done
You know, lots of directions I could go. Definitely more to sort out. More to think and talk about. But, I feel this post has covered a thought and the related experiment in a reasonable fashion. Starting on a new or, perhaps, modified topic seems inappropriate.
And, yes, I know I haven’t decided what I am going to do about or with this little experiment. Don’t believe there is quite yet a rush to sort that out.
Until next time, my you find peace and pleasure in whatever the future brings.