step weights and hd alts now implemented

dev
mwinter 2 years ago
parent c79b8832b2
commit 97d0a7f940

@ -65,7 +65,10 @@
"fallback": "", "fallback": "",
"props": { "props": {
"variables": { "variables": {
"grandparent": "@{parent.id}" "grandparent": "@{parent.id}",
"min": 0,
"max": 5,
"decimals": 2
} }
}, },
"address": "auto", "address": "auto",

@ -1,5 +1,5 @@
{ {
"version": "1.22.0", "version": "1.24.0",
"createdWith": "Open Stage Control", "createdWith": "Open Stage Control",
"type": "fragment", "type": "fragment",
"content": { "content": {
@ -33,7 +33,6 @@
"contain": true, "contain": true,
"scroll": true, "scroll": true,
"innerPadding": true, "innerPadding": true,
"verticalTabs": false,
"variables": "@{parent.variables}", "variables": "@{parent.variables}",
"traversing": false, "traversing": false,
"value": "", "value": "",
@ -220,18 +219,12 @@
"snap": true, "snap": true,
"spring": false, "spring": false,
"doubleTap": false, "doubleTap": false,
"range": { "range": "{\n \"min\": @{parent.variables.min},\n \"max\": @{parent.variables.max}\n}",
"min": 0,
"max": 5
},
"logScale": false, "logScale": false,
"sensitivity": 1, "sensitivity": 1,
"steps": "", "steps": "",
"value": "[@{@{parent.id}_input_min.value}, @{@{parent.id}_input_max.value}]", "value": "[@{@{parent.id}_input_min.value}, @{@{parent.id}_input_max.value}]",
"default": [ "default": "[\n @{parent.variables.min},\n @{parent.variables.max}\n]",
0.5,
2
],
"linkId": "", "linkId": "",
"address": "auto", "address": "auto",
"preArgs": "", "preArgs": "",
@ -280,7 +273,7 @@
"address": "auto", "address": "auto",
"preArgs": "", "preArgs": "",
"typeTags": "", "typeTags": "",
"decimals": 2, "decimals": "@{parent.variables.decimals}",
"target": "", "target": "",
"ignoreDefaults": false, "ignoreDefaults": false,
"bypass": true, "bypass": true,
@ -316,7 +309,7 @@
"linkId": "", "linkId": "",
"address": "auto", "address": "auto",
"preArgs": "", "preArgs": "",
"decimals": 2, "decimals": "@{parent.variables.decimals}",
"target": "", "target": "",
"onCreate": "", "onCreate": "",
"onValue": "", "onValue": "",
@ -367,6 +360,7 @@
"wrap": false "wrap": false
} }
], ],
"tabs": [] "tabs": [],
"tabsPosition": "top"
} }
} }

@ -104,6 +104,21 @@ loadModel = function(model){
receive("/sus_weights/2_val_slider", model.sus_weights[2]) receive("/sus_weights/2_val_slider", model.sus_weights[2])
} }
if(typeof model.step_probs_vals !== 'undefined') {
var envValsFlat = model.step_probs_vals.slice(2)
var envSize = envValsFlat.length / 2
var envVals = new Array(64).fill({type: 'f', value: 0})
for (var i = 0; i < envSize; i++) {
envVals[i] = [envValsFlat[i * 2], envValsFlat[i * 2 + 1]]
}
receive("/step_probs_env_size", envSize)
receive("/step_probs_env_rslider", ...model.step_probs_vals.slice(0, 2))
receive("/step_probs_env_canvas", ...envVals)
}
if(typeof model.hd_exp !== 'undefined') {receive("/hd_exp_val_slider", envSize)}
if(typeof model.hd_invert !== 'undefined') {receive("/hd_invert", envSize)}
if(typeof model.order_size !== 'undefined') {receive("/order_size_rslider", ...model.order_size)} if(typeof model.order_size !== 'undefined') {receive("/order_size_rslider", ...model.order_size)}
if(typeof model.passages_size !== 'undefined') {receive("/passages_size_rslider", ...model.passages_size)} if(typeof model.passages_size !== 'undefined') {receive("/passages_size_rslider", ...model.passages_size)}
@ -222,6 +237,8 @@ module.exports = {
state["passages_weights/3_val_slider"], state["passages_weights/3_val_slider"],
state["passages_weights/4_val_slider"] state["passages_weights/4_val_slider"]
] ]
model.hd_exp = state.hd_exp_val_slider
model.hd_invert = state.hd_invert
if(state.order_lock == 1){ if(state.order_lock == 1){
model.order = JSON.parse(state.order) model.order = JSON.parse(state.order)
} }
@ -233,6 +250,8 @@ module.exports = {
model.order_size = state.order_size_rslider model.order_size = state.order_size_rslider
model.passages_size = state.passages_size_rslider model.passages_size = state.passages_size_rslider
model.step_probs_vals = state.step_probs_env_vals
model.motif_edited = false model.motif_edited = false
model.order_edited = false model.order_edited = false
//console.log(model) //console.log(model)

@ -0,0 +1 @@
{"send":["127.0.0.1:57120"],"custom-module":"/home/mwinter/Sketches/seeds_and_ledgers/source/open_stage_control/modules/custom_module.js","load":"/home/mwinter/Sketches/seeds_and_ledgers/source/open_stage_control/seeds_and_ledgers_gui.json"}

@ -2178,7 +2178,7 @@
"top": 10, "top": 10,
"left": 10, "left": 10,
"lock": false, "lock": false,
"id": "step_env", "id": "step_probs",
"visible": true, "visible": true,
"interaction": true, "interaction": true,
"comments": "", "comments": "",
@ -2186,9 +2186,15 @@
"height": 260, "height": 260,
"expand": "false", "expand": "false",
"css": "", "css": "",
"props": {
"variables": {
"min": 0,
"max": 1200,
"decimals": 0
}
},
"file": "fragments/env.json", "file": "fragments/env.json",
"fallback": "", "fallback": "",
"props": {},
"address": "auto", "address": "auto",
"variables": "@{parent.variables}" "variables": "@{parent.variables}"
}, },
@ -2201,7 +2207,7 @@
"visible": true, "visible": true,
"interaction": true, "interaction": true,
"comments": "", "comments": "",
"width": "96.53%", "width": "79.15%",
"height": "40.57%", "height": "40.57%",
"expand": "false", "expand": "false",
"colorText": "auto", "colorText": "auto",
@ -2227,7 +2233,7 @@
"traversing": false, "traversing": false,
"widgetType": "fragment", "widgetType": "fragment",
"quantity": 5, "quantity": 5,
"props": "{\n \"file\": \"fragments/slider.json\",\n \"props\": {\n \"variables\": #{{\n \"n\": $, \"slider_label\": [\"step\", \"dc\", \"range\", \"registration\", \"hd\"][$], \n \"min\": 0, \"max\": 1\n }}\n }\n}", "props": "{\n \"file\": \"fragments/slider.json\",\n \"props\": {\n \"variables\": #{{\n \"n\": $, \"slider_label\": [\"step\", \"dc\", \"range\", \"reg\", \"hd\"][$], \n \"min\": 0, \"max\": 1\n }}\n }\n}",
"value": "", "value": "",
"default": "", "default": "",
"linkId": "", "linkId": "",
@ -2243,6 +2249,127 @@
"widgets": [], "widgets": [],
"tabs": [], "tabs": [],
"tabsPosition": "top" "tabsPosition": "top"
},
{
"type": "panel",
"top": 280,
"left": 420,
"lock": false,
"id": "panel_1",
"visible": true,
"interaction": true,
"comments": "",
"width": 90,
"height": "auto",
"expand": "false",
"colorText": "auto",
"colorWidget": "auto",
"colorStroke": "auto",
"colorFill": "auto",
"alphaStroke": "auto",
"alphaFillOff": "auto",
"alphaFillOn": "auto",
"lineWidth": "auto",
"borderRadius": "auto",
"padding": "auto",
"html": "",
"css": "",
"colorBg": "auto",
"layout": "default",
"justify": "start",
"gridTemplate": "",
"contain": true,
"scroll": true,
"innerPadding": true,
"tabsPosition": "top",
"variables": "@{parent.variables}",
"traversing": false,
"value": "",
"default": "",
"linkId": "",
"address": "auto",
"preArgs": "",
"typeTags": "",
"decimals": 2,
"target": "",
"ignoreDefaults": false,
"bypass": false,
"onCreate": "",
"onValue": "",
"widgets": [
{
"type": "fragment",
"top": 0,
"left": 0,
"lock": false,
"id": "hd_exp",
"visible": true,
"interaction": true,
"comments": "",
"width": 80,
"height": 190,
"expand": "false",
"css": "",
"file": "fragments/slider.json",
"fallback": "",
"props": {
"variables": {
"min": -2,
"max": 2,
"slider_label": "hd exp"
}
},
"address": "auto",
"variables": "@{parent.variables}"
},
{
"type": "button",
"top": 130,
"left": 50,
"lock": false,
"id": "hd_invert",
"visible": true,
"interaction": true,
"comments": "",
"width": 20,
"height": 20,
"expand": "false",
"colorText": "auto",
"colorWidget": "auto",
"colorStroke": "auto",
"colorFill": "auto",
"alphaStroke": "auto",
"alphaFillOff": "auto",
"alphaFillOn": "auto",
"lineWidth": "auto",
"borderRadius": "auto",
"padding": "auto",
"html": "",
"css": "",
"colorTextOn": "auto",
"label": "i",
"vertical": false,
"wrap": false,
"on": 1,
"off": 0,
"mode": "toggle",
"doubleTap": false,
"decoupled": false,
"value": "",
"default": "",
"linkId": "",
"address": "auto",
"preArgs": "",
"typeTags": "",
"decimals": 2,
"target": "",
"ignoreDefaults": false,
"bypass": false,
"onCreate": "",
"onValue": ""
}
],
"tabs": []
} }
], ],
"tabs": [], "tabs": [],

@ -283,7 +283,7 @@ genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLa
}); });
//format and return //format and return
if(startFromLast, {lastXChanges = lastXChangesHold}); if(startFromLast, {lastXChanges = lastXChangesHold.deepCopy});
res; res;
}; };
@ -359,10 +359,17 @@ genPatterns = {arg inSeq, addr, oneShot = false;
seq = inSeq.collect({arg mSeq; mSeq[0]}); seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop; # voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
pbinds = voices.flop.collect({arg voice, v; pbinds = voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs; var clumps, hdScores, freqs, fDurs, attacks, rels, amps;
clumps = voice.separate({arg a, b; a != b }); clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})}); freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum}); fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
//attacks = 2.collect({rrand(1, 3)}) ++ freqs.drop(2).collect({rrand(0.3, 0.5)});
attacks = fDurs.collect({arg dur; dur * rrand(0.2, 0.4)});
//rels = freqs.drop(2).collect({rrand(0.3, 0.5)}) ++ 2.collect({rrand(1, 3)});
rels = (clumps.size - 1).collect({arg c;
if(clumps[c + 1][0] == ["Rest"], {rrand(1, 3)}, {rrand(0.3, 0.5)});
});
amps = freqs.collect({rrand(0.6, 0.99)});
[ [
Pbind( Pbind(
@ -370,7 +377,11 @@ genPatterns = {arg inSeq, addr, oneShot = false;
\group, group, \group, group,
\freq, Pseq(freqs, 1), \freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1), \dur, Pseq(fDurs, 1),
\attack, Pseq(attacks, 1),
\sustain, Pseq(fDurs, 1), \sustain, Pseq(fDurs, 1),
\release, Pseq(rels, 1),
//\amp, Pseq(amps, 1),
\amp, Pbrown(0.5, 1, 0.5),
\busIndex, v \busIndex, v
), ),
Pbind( Pbind(
@ -549,12 +560,15 @@ loadModelJSON = {arg jsonObject;
dict dict
}; };
setGlobalVars = {arg dict; setGlobalVars = {arg dict, skipLastXChanges = false;
var tmpLastXChanges;
tmpLastXChanges = lastXChanges.deepCopy;
// order really matters!!!! // order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed, # seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals, entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize, ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]}); motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
if(skipLastXChanges, {lastXChanges = tmpLastXChanges});
dict dict
}; };
@ -636,7 +650,7 @@ OSCdef(\generate, {arg msg, time, addr, port;
path = msg[1].asString; path = msg[1].asString;
dict = loadModelFile.value(path); dict = loadModelFile.value(path);
setGlobalVars.value(dict); setGlobalVars.value(dict, true);
popSize = ranges.size; popSize = ranges.size;
@ -646,14 +660,16 @@ OSCdef(\generate, {arg msg, time, addr, port;
if(ledger == nil, {ledger = ["tmp"]}); if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")}); if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, { if(refUID == nil, {lastXChanges = [initVoices.value().deepCopy]});
[initVoices.value().deepCopy]; if((refUID != nil) && (refUID != "tmp"), {
}, {
var file; var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r"); file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]); lastXChanges = msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
}); });
refUID.postln;
lastXChanges.collect({arg item; item.postln});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln; durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]); entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]); passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
@ -665,6 +681,8 @@ OSCdef(\generate, {arg msg, time, addr, port;
}); });
seq = seedFunc.value(genMotif, motifSeed).value; seq = seedFunc.value(genMotif, motifSeed).value;
lastXChanges.collect({arg item; item.postln});
dict = globalVarsToDict.value; dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict); modelString = writeResources.value(path, dict);
@ -719,8 +737,9 @@ OSCdef(\commit, {arg msg, time, addr, port;
OSCdef(\transport, {arg msg, time, addr, port; OSCdef(\transport, {arg msg, time, addr, port;
msg.postln; msg.postln;
if(msg[1] == 0, { if(msg[1] == 0, {
player.stop; group.set(\release, 2);
group.set(\gate, 0); group.set(\gate, 0);
player.stop;
}, { }, {
// the cued sequence can now be read from file, so this can be cleaned up // the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger; var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
@ -769,15 +788,15 @@ OSCdef(\transport, {arg msg, time, addr, port;
~hdustBusArray = 1.collect({Bus.audio(s, 1)}); ~hdustBusArray = 1.collect({Bus.audio(s, 1)});
~samplerBusArray = 2.collect({Bus.audio(s, 1)}); ~samplerBusArray = 2.collect({Bus.audio(s, 1)});
~sBuf = Buffer.alloc(s, 10, 2); ~sBuf = Buffer.alloc(s, 10, 2);
SynthDef(\string_model, {arg freq, gate = 1, sustain, amp, dur, busIndex = 0; SynthDef(\string_model, {arg freq, gate = 1, sustain, amp, dur, attack, release = 1, busIndex = 0;
var trig, exc, sig1, sig2, noHarms; var trig, exc, sig1, sig2, noHarms;
noHarms = 30; noHarms = rrand(20, 40);
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01); exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq), sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}), Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.8).softclip; Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.8).softclip;
sig1 = HPF.ar(sig1, 300); //sig1 = HPF.ar(sig1, 300);
Out.ar(Select.kr(busIndex, ~stringModelBusArray), sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2)); Out.ar(Select.kr(busIndex, ~stringModelBusArray), sig1 * amp * EnvGen.kr(Env.adsr(attack, 0.3, 0.9, release, 0.9, -3), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2)); //Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add; }).add;
@ -785,6 +804,7 @@ SynthDef(\sine, {arg freq, gate = 1, sustain, amp, dur, busIndex = 0;
var sig; var sig;
sig = SinOsc.ar(freq); sig = SinOsc.ar(freq);
Out.ar(Select.kr(busIndex, ~sineBusArray), sig * EnvGen.kr(Env.asr(0.3, 0.4, 0.3), gate, timeScale: dur, doneAction: 2)); Out.ar(Select.kr(busIndex, ~sineBusArray), sig * EnvGen.kr(Env.asr(0.3, 0.4, 0.3), gate, timeScale: dur, doneAction: 2));
//Out.ar(Select.kr(busIndex, ~sineBusArray), sig * EnvGen.kr(Env.sine(dur), gate, doneAction: 2));
}).add; }).add;
SynthDef(\mixer, {arg freq, gate = 1, sustain, amp, dur, out; SynthDef(\mixer, {arg freq, gate = 1, sustain, amp, dur, out;

@ -0,0 +1,83 @@
{
"music_data":
[
[
[
[ [ [ "Rest" ], [ "Rest" ], [ 0, 1, 0, 0, 0, -1 ], [ "Rest" ] ], 4 ],
[ [ [ "Rest" ], [ 0, 1, 0, 1, 0, -1 ], [ 0, 1, 0, 0, 0, -1 ], [ "Rest" ] ], 2 ],
[ [ [ "Rest" ], [ 0, 1, 0, 1, 0, -1 ], [ 0, 1, 0, 0, 0, -1 ], [ 1, 1, 0, 0, -1, -1 ] ], 1.875 ],
[ [ [ -1, 1, 0, 1, 0, -1 ], [ 0, 1, 0, 1, 0, -1 ], [ 0, 1, 0, 0, 0, -1 ], [ 1, 1, 0, 0, -1, -1 ] ], 1.625 ],
[ [ [ -1, 1, 0, 1, 0, -1 ], [ 0, 1, 0, 1, 0, -1 ], [ 0, 1, 0, 0, 0, -1 ], [ 0, 2, 0, 0, 0, -1 ] ], 1.75 ],
[ [ [ -1, 2, 0, 0, 0, -1 ], [ 0, 1, 0, 1, 0, -1 ], [ 0, 1, 0, 0, 0, -1 ], [ 0, 2, 0, 0, 0, -1 ] ], 1.875 ],
[ [ [ -1, 1, 0, 0, 0, 0 ], [ 0, 1, 0, 1, 0, -1 ], [ 0, 1, 0, 0, 0, -1 ], [ 0, 2, 0, 0, 0, -1 ] ], 0 ],
[ [ [ -1, 1, 0, 0, 0, 0 ], [ 1, 1, 0, 0, 0, -1 ], [ 0, 1, 0, 0, 0, -1 ], [ 0, 2, 0, 0, 0, -1 ] ], 2 ],
[ [ [ -1, 1, 0, 0, 0, 0 ], [ 2, 1, 0, -1, 0, -1 ], [ 0, 1, 0, 0, 0, -1 ], [ 0, 2, 0, 0, 0, -1 ] ], 1.375 ],
[ [ [ 0, 1, -1, 0, 0, -1 ], [ 2, 1, 0, -1, 0, -1 ], [ 0, 1, 0, 0, 0, -1 ], [ 0, 2, 0, 0, 0, -1 ] ], 1 ],
[ [ [ 0, 1, -1, 0, 0, -1 ], [ 2, 1, 0, 0, 0, -2 ], [ 0, 1, 0, 0, 0, -1 ], [ 0, 2, 0, 0, 0, -1 ] ], 7.375 ]
],
[
[ [ [ -1, 2, 0, 0, 0, -1 ], [ 2, 1, 0, 0, 0, -2 ], [ 0, 1, 0, 0, 0, -1 ], [ 0, 2, 0, 0, 0, -1 ] ], 0 ],
[ [ [ -1, 2, 0, 0, 0, -1 ], [ 2, 1, 0, 0, 0, -2 ], [ 0, 1, 0, 0, 0, -1 ], [ 1, 0, 0, 0, 0, -1 ] ], 0 ],
[ [ [ -1, 2, 0, 0, 0, -1 ], [ 2, 0, 0, 0, 0, -1 ], [ 0, 1, 0, 0, 0, -1 ], [ 1, 0, 0, 0, 0, -1 ] ], 5.375 ]
],
[
[ [ [ -1, 2, 0, 0, 0, -1 ], [ "Rest" ], [ 0, 1, 0, 0, 0, -1 ], [ 1, 0, 0, 0, 0, -1 ] ], 0 ],
[ [ [ -1, 2, 0, 0, 0, -1 ], [ "Rest" ], [ 0, 1, 0, 0, 0, -1 ], [ "Rest" ] ], 2 ],
[ [ [ -1, 2, 0, 0, 0, -1 ], [ "Rest" ], [ -1, 2, 1, 0, 0, -1 ], [ "Rest" ] ], 1.25 ],
[ [ [ -1, 2, 0, 0, 0, -1 ], [ "Rest" ], [ -1, 2, 0, 0, 1, -1 ], [ "Rest" ] ], 1.875 ],
[ [ [ -1, 2, 0, 0, 0, -1 ], [ "Rest" ], [ 0, 2, 0, 0, -1, -1 ], [ "Rest" ] ], 1.25 ],
[ [ [ -1, 2, 0, 0, 0, -1 ], [ "Rest" ], [ -1, 3, 0, 0, 0, -1 ], [ "Rest" ] ], 1.375 ],
[ [ [ -1, 2, 0, 0, 0, -1 ], [ "Rest" ], [ 0, 2, -1, 0, 0, -1 ], [ "Rest" ] ], 8.375 ]
],
[
[ [ [ -1, 2, 0, 0, 0, -1 ], [ 2, 2, -1, 0, 0, -2 ], [ 0, 2, -1, 0, 0, -1 ], [ "Rest" ] ], 1.75 ],
[ [ [ -1, 2, 0, 0, 0, -1 ], [ 2, 2, -1, 0, 0, -2 ], [ 0, 2, -1, 0, 0, -1 ], [ 1, 2, -1, 0, 0, -2 ] ], 0 ],
[ [ [ -1, 2, -1, 0, 1, -1 ], [ 2, 2, -1, 0, 0, -2 ], [ 0, 2, -1, 0, 0, -1 ], [ 1, 2, -1, 0, 0, -2 ] ], 2 ],
[ [ [ 0, 2, -1, 0, 0, -2 ], [ 2, 2, -1, 0, 0, -2 ], [ 0, 2, -1, 0, 0, -1 ], [ 1, 2, -1, 0, 0, -2 ] ], 1.5 ],
[ [ [ 0, 2, -1, 0, 0, -2 ], [ 2, 2, -1, -1, 0, -1 ], [ 0, 2, -1, 0, 0, -1 ], [ 1, 2, -1, 0, 0, -2 ] ], 7 ]
],
[
[ [ [ 0, 2, -1, 0, 0, -2 ], [ "Rest" ], [ 0, 2, -1, 0, 0, -1 ], [ 1, 2, -1, 0, 0, -2 ] ], 1.5 ],
[ [ [ 0, 2, -1, 0, 0, -2 ], [ "Rest" ], [ 0, 2, -1, 0, 0, -1 ], [ "Rest" ] ], 1.25 ],
[ [ [ 0, 2, -1, -1, 0, -1 ], [ "Rest" ], [ 0, 2, -1, 0, 0, -1 ], [ "Rest" ] ], 1.875 ],
[ [ [ -1, 2, -1, 0, 0, -1 ], [ "Rest" ], [ 0, 2, -1, 0, 0, -1 ], [ "Rest" ] ], 1.5 ],
[ [ [ -2, 2, -1, 0, 0, 0 ], [ "Rest" ], [ 0, 2, -1, 0, 0, -1 ], [ "Rest" ] ], 1 ],
[ [ [ -1, 2, -2, 0, 0, -1 ], [ "Rest" ], [ 0, 2, -1, 0, 0, -1 ], [ "Rest" ] ], 1.375 ],
[ [ [ -2, 2, -1, 1, 0, -1 ], [ "Rest" ], [ 0, 2, -1, 0, 0, -1 ], [ "Rest" ] ], 6.75 ],
[ [ [ "Rest" ], [ "Rest" ], [ 0, 2, -1, 0, 0, -1 ], [ "Rest" ] ], 1.125 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 7.5 ]
]
]
],
"last_changes":
[
[ [ 0, 2, -1, -1, 0, -1 ], [ 2, 2, -1, -1, 0, -1 ], [ 0, 2, -1, 0, 0, -1 ], [ 1, 2, -1, 0, 0, -2 ] ],
[ [ -1, 2, -1, 0, 0, -1 ], [ 2, 2, -1, -1, 0, -1 ], [ 0, 2, -1, 0, 0, -1 ], [ 1, 2, -1, 0, 0, -2 ] ],
[ [ -2, 2, -1, 0, 0, 0 ], [ 2, 2, -1, -1, 0, -1 ], [ 0, 2, -1, 0, 0, -1 ], [ 1, 2, -1, 0, 0, -2 ] ],
[ [ -1, 2, -2, 0, 0, -1 ], [ 2, 2, -1, -1, 0, -1 ], [ 0, 2, -1, 0, 0, -1 ], [ 1, 2, -1, 0, 0, -2 ] ],
[ [ -2, 2, -1, 1, 0, -1 ], [ 2, 2, -1, -1, 0, -1 ], [ 0, 2, -1, 0, 0, -1 ], [ 1, 2, -1, 0, 0, -2 ] ]
],
"cur_uid": "449aeaa6",
"ref_uid": "628d5c8b",
"order_seed": 338959,
"dur_seed": 810921,
"motifs_seed": 154723,
"entrances_probs_vals": [ 0.29, 0, 7.0238095238095, 0.77, 2.1703296703297, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"passages_probs_vals": [ 0.29, 0, 7.0238095238095, 0.77, 2.1703296703297, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0.29, 0, 7.0238095238095, 0.77, 2.1703296703297, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ -3600, -349 ], [ 799, 1758 ], [ -282, 1013 ], [ -282, 799 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ],
"order":
[
[ [ 2 ], [ 1, 3, 0, 3, 0, 0, 1, 1, 0, 1 ], [ ] ],
[ [ 2 ], [ 0, 3, 1 ], [ ] ],
[ [ 0 ], [ 2, 2, 2, 2, 2 ], [ 1, 3 ] ],
[ [ 2 ], [ 1, 3, 0, 0, 1 ], [ ] ],
[ [ 2 ], [ 0, 0, 0, 0, 0 ], [ 1, 3 ] ]
],
"sus_weights": [ 0.75, 0.34, 0 ],
"order_size": [ 2, 6 ],
"passages_size": [ 0, 10 ],
"motif_edited": "false",
"order_edited": "false"
}

@ -1,796 +0,0 @@
(
// helper funcs
var hsArrayToCents, pDist, hdSum, hsChordalDistance, hsArrayToFreq;
// score funcs
var isInRange, spacingScore, rangeScore, intervalScore, inclusionScore;
// subroutines
var genTuples, initVoices, genOrders, genSubMotif, updateVoices, genDurFunc;
// primary routines
var genMotif, genSecondarySeq;
// audition funcs
var genPatterns, genMidiPatterns;
// resource management funcs
var seedFunc, genUID, writeResources, stringifyToDepth, setSeeds, sanityCheck,
msgInterpret, loadLedgerFile, loadLedgerJSON, loadModelFile, loadModelJSON,
setGlobalVars, globalVarsToDict, saveLedger;
// model vars
//(model and global vars mostly set by OSC funcs
var seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited;
// model aux vars
var entrancesDurFunc, passagesDurFunc, exitsDurFunc;
// other global vars
var popSize, exPath, dir, primes, dims, tuples,
group, player, ledgerPath, ledger, currentlyPlayingUID,
nameSpaces;
// install JSON quark
if(Quarks.isInstalled("JSONlib").not, {
Quarks.install("https://github.com/musikinformatik/JSONlib.git");
thisProcess.recompile;
//HelpBrowser.openHelpFor("Classes/JSONlib");
});
//------helper funcs
hsArrayToCents = {
arg hsArray;
hsArray.collect({arg dist, p; dist * 1200 * log2(primes[p][0]/primes[p][1])}).sum
};
pDist = {
arg array1, array2, signed = false;
var pDistance;
pDistance = hsArrayToCents.value(array1) - hsArrayToCents.value(array2);
if(signed, {pDistance}, {abs(pDistance)})
};
hdSum = {
arg hsArrays;
var size, distances, mean;
size = hsArrays.size;
distances = (size - 1).collect({arg i;
((i + 1)..(size - 1)).collect({arg j;
abs(hsArrays[i] - hsArrays[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsChordalDistance = {
arg hsArrays1, hsArrays2;
var size, distances, mean;
size = hsArrays1.size;
distances = hsArrays1.size.collect({arg i;
hsArrays2.size.collect({arg j;
abs(hsArrays1[i] - hsArrays2[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsArrayToFreq = {
arg array;
array.collect({arg dim, d; pow(primes[d][0]/primes[d][1], dim)}).product
};
//------score funcs
/*
isInRange = {
arg hsArray, min, max;
var cents;
cents = hsArrayToCents.value(hsArray);
(cents >= min) && (cents <= max)
};
*/
spacingScore = {
arg hsArrays, min;
var centsArray;
centsArray = hsArrays.collect({arg hsArray; hsArrayToCents.value(hsArray)}).sort({arg a, b; a < b});
centsArray.differentiate.drop(1).collect({arg pDistance; if(pDistance >= min, {1}, {0.01})}).sum;
};
rangeScore = {
arg hsArray1, hsArray2, min, max, low, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
if((pDistance >= min) && (pDistance <= max), {1}, {low});
};
intervalScore = {
arg hsArray1, hsArray2, mean, sd, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
pDistance.gaussCurve(1, mean, sd)
};
inclusionScore = {
arg array, test, min = 0.01;
if(array.collect({arg v; v.hash}).includes(test.hash), {min}, {1});
};
//------subroutines
genTuples = {
var tuples;
tuples = dims.collect({[-1, 0, 1]}).allTuples.select({arg tuple; (abs(tuple.drop(1)).sum <= 1) && (tuple[0] == 0)});
tuples = tuples ++ tuples.collect({arg tuple; [-3, -2, -1, 1, 2, 3].collect({arg octTrans; tuple.deepCopy.put(0, octTrans)})}).flatten;
};
initVoices = {
var init, voicesInit;
voicesInit = popSize.collect({dims.collect({0})});
/*
voicesInit = [dims.collect({0})];
(popSize - 1).do({
arg rep, new;
rep = dims.rand;
new = voicesInit.last.deepCopy;
new[rep] = new[rep] + [-1, 1].choose();
voicesInit = voicesInit.add(new);
});
*/
voicesInit.deepCopy;
};
genDurFunc = {arg chordProb, minPad, maxPad, minDur, maxDur, envData, seed;
var env, pTable, durFunc;
env = Env.pairs([[0, 0]] ++ envData.clump(2) ++ [[1, 0]]).asSignal(256).asList.asArray;
pTable = env.asRandomTable;
[chordProb, minPad, maxPad, minDur, maxDur, envData].postln;
durFunc = {arg allowChord, pad = false;
var res;
res = if(allowChord.not, {
pTable.tableRand * (maxDur - minDur) + minDur
}, {
if(1.0.rand < chordProb, {0}, {pTable.tableRand * (maxDur - minDur) + minDur});
}).round(0.125);
if(pad, {res = res + rrand(minPad.asFloat, maxPad.asFloat).round(0.125)});
if(res.asInteger == res, {res = res.asInteger});
res
};
seedFunc.value(durFunc, seed);
};
genOrders = {arg minMotifLength = 1, maxMotifLength = 5, minProgLength = 0, maxProgLength = 5;
((maxMotifLength - minMotifLength).rand + minMotifLength).collect({
var noProgIns, noSusIns, noSilentIns, prog, sus, silent, order;
noSusIns = [1, 2, 3].wchoose(susWeights.normalizeSum);
noProgIns = (popSize - noSusIns).rand + 1;
noSilentIns = popSize - noSusIns - noProgIns;
# prog, sus, silent = (0..(popSize-1)).scramble.clumps([noProgIns, noSusIns, noSilentIns]);
prog = (prog.scramble ++ ((maxProgLength - minProgLength).rand + minProgLength).collect({prog.choose}).scramble);
if(silent == nil, {silent = []});
[sus.scramble, prog, silent.scramble]
});
};
updateVoices = {arg ins, sus;
var voices, candidates, nWeights, nProbs, sel;
voices = lastXChanges.deepCopy.last;
candidates = sus.collect({arg v; tuples.collect({arg t; voices[v] + t})}).flatten;
candidates = difference(candidates.asSet, voices.asSet).asList;
nProbs = candidates.collect({arg candidate;
var stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore;
//stepScore = intervalScore.value(voices[ins], candidate, 30, 400, 0.1);
stepScore = intervalScore.value(voices[ins], candidate, 100, 100);
recentlySoundedScore = inclusionScore.value(lastXChanges.flop[ins], candidate, 0);
isInRangeScore = rangeScore.value(candidate, candidate.collect({0}), ranges[ins][0], ranges[ins][1], 0, true);
regScore = spacingScore.value(voices.deepCopy.put(ins, candidate), 300);
hdScore = 1/pow(hdSum.value(voices.deepCopy.put(ins, candidate)), 2);
//maybe what you want here is a vector to another root and then favoring movement towards it.
//distScore = pow(hsChordalDistance.value(voices, voices.put(ins, candidate)), 2);
[stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore]
});
nWeights = passagesWeights;
//this handles nWeights of 0; mainly for testing
nProbs = nProbs.flop.select({arg scores, s; nWeights[s] != 0}).flop;
nWeights = nWeights.select({arg weight; weight != 0});
nProbs = nProbs.flop.collect({arg scores, s;
if(scores.sum == 0, {scores}, {scores.normalizeSum * nWeights[s]})
});
nProbs = nProbs.flop.collect({arg scores, s; scores.product}).normalizeSum;
sel = candidates.wchoose(nProbs);
voices[ins] = sel;
lastXChanges = lastXChanges.add(voices).keep(-5);
};
genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLast = false, isLastOrder = false;
var sus, prog, silent, flatOrder, res, isInChord, allowChord, pad, lastXChangesHold, voices, adder;
# sus, prog, silent = order;
flatOrder = silent ++ sus ++ prog;
lastXChangesHold = lastXChanges.deepCopy;
voices = lastState.deepCopy;
isInChord = popSize.collect({false});
allowChord = false;
pad = false;
res = [];
"------generating motif".postln;
//need to figure out here if voices move between motifs
flatOrder.do({arg ins, i;
if(prog.includes(ins) && repeatLast.not, {updateVoices.value(ins, sus)});
adder = if(silent.includes(ins), {["Rest"]}, {lastXChanges.last.deepCopy[ins]});
if(voices[ins] != adder, {
var dur;
if((sus ++ silent).includes(ins), {
allowChord = (ins != sus.last);
pad = (ins == sus.last);
}, {
if(i < (flatOrder.size - 1), {
allowChord = (isInChord[flatOrder[i + 1]] || (ins == flatOrder[i + 1])).not;
pad = false;
}, {
allowChord = false;
pad = true
});
});
if((orderIndex == 0) && sus.includes(ins), {
dur = entrancesDurFunc.value(allowChord, pad);
}, {
dur = passagesDurFunc.value(allowChord, pad);
});
if(dur == 0, {isInChord[ins] = true}, {isInChord = popSize.collect({false})});
voices[ins] = adder;
res = res.add([voices.deepCopy.postln, dur]);
});
});
// pad ending
if(orderIndex == (orders.size - 1), {
(0..(popSize-1)).scramble.do({arg ins;
if(res.last.first[ins] != ["Rest"], {
var dur;
voices[ins] = ["Rest"];
allowChord = (voices != popSize.collect({["Rest"]}));
pad = allowChord.not;
dur = exitsDurFunc.value(allowChord, pad);
res = res.add([voices.deepCopy.postln, dur]);
});
});
});
//format and return
if(startFromLast, {lastXChanges = lastXChangesHold});
res;
};
//------primary routines
genMotif = {
var repeats, fSeq;
repeats = 1;
fSeq = [];
repeats.do({arg index;
var motif;
motif = [];
orders.do({arg order, o;
var lastState, subMotif;
lastState = if(o == 0, {popSize.collect({["Rest"]})}, {motif.last.last.first});
subMotif = genSubMotif.value(order, o, lastState, isLastOrder: o == (orders.size - 1));
motif = motif.add(subMotif);
});
sanityCheck.value(motif, index);
fSeq = fSeq.add(motif);
});
fSeq
};
genSecondarySeq = {arg seq;
var curdles, fSeq;
curdles = [];
while({curdles.sum < seq.size}, {curdles = curdles ++ [3.rand + 1]});
fSeq = seq.clumps(curdles).collect({arg clump, m;
var repeats, paddedSeq;
//add rest
paddedSeq = clump.add([[[popSize.collect({["Rest"]}), 0.5.rand]]]);
//implement repeats
repeats = [0.rand + 1, 1].wchoose([1, 0].normalizeSum);
repeats.collect({paddedSeq});
});
fSeq
};
//------audition funcs
/*
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~addr.sendMsg(~indexPath, ~indexMsg);
~addr.sendMsg(~seqPath, stringifyToDepth.value(~seqMsg, 3));
//~addr.sendMsg("/STATE/OPEN", (dir.replace("supercollider", "resources") +/+ ~idMsg +/+ ~idMsg ++ "_gui_state" ++ ".state").standardizePath.postln);
};
});
*/
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~msg.postln;
~addr.sendMsg(~path, *~msg);
};
});
genPatterns = {arg inSeq, addr, oneShot = false;
var voices, durs, pbinds, res, indices, sectionDurs, msg, ids, seq;
seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
pbinds = voices.flop.collect({arg voice;
var clumps, hdScores, freqs, fDurs;
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\instrument, \test,
\group, group,
\freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1),
\sustain, Pseq(fDurs, 1)
)
});
if(oneShot.not, {
msg = inSeq.collect({arg mSeq, m; mSeq[1..]});
//ids = inSeq.collect({arg mSeq, m; mSeq[2]});
sectionDurs = seq.collect({arg mSeq; mSeq.flatten2(mSeq.maxDepth - 5).flop[1].sum});
pbinds = pbinds ++
[
Pbind(
\type, \osc,
\addr, addr,
\path, "/playing",
\msg, Pseq(msg, 1),
\dur, Pseq(sectionDurs, 1)
);
]
});
res = Ppar(pbinds);
res
};
/*
genMidiPatterns = {arg seq;
var voices, durs, patterns, res, mOut, pbRange;
pbRange = 1; //semitones - change this as needed for your situation
mOut = MIDIOut.newByName("TiMidity", "TiMidity port 0").latency_(Server.default.latency);
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
res = Ppar(
voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs;
mOut.program(v, 70);
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\type, \midi,
\chan, v,
\noteval, Pseq(freqs.cpsmidi - 24, 1),
\note, Pfunc({ | event | event[\noteval].floor }),
\dur, Pseq(fDurs, 1),
\midiout, mOut,
\amp, 1,
\bend, Pfunc({
| event |
if (event[\note].isRest.not) {
var pitchbendvalue = event[\noteval].frac.linlin(0, pbRange, 8192, 8192*2).asInteger;
m.bend(v, pitchbendvalue);
};
0; // return something other than nil to avoid stopping the pattern
}),
);
});
);
res
};
*/
//------resource management funcs
genUID = {Date.seed.asHexString.toLower};
seedFunc = {arg func, seed;
var funcArgs, next;
next = Routine({loop{func.valueArray(funcArgs).yield }});
next.randSeed_(seed);
{arg ...args; funcArgs = args; next.value}
};
stringifyToDepth = {arg data, maxDepth = 1;
var prettyString = "", rCount = 0, writeArray, indent;
if(maxDepth == 0, {
data.asCompileString
}, {
indent = {arg size; size.collect({" "}).join("")};
writeArray = {arg array;
prettyString = prettyString ++ indent.value(rCount) ++ "[\n";
rCount = rCount + 1;
if(rCount < maxDepth, {
array.do({arg subArray; writeArray.value(subArray)});
}, {
prettyString = prettyString ++ array.collect({arg subArray;
indent.value(rCount + 1) ++ subArray.asCompileString
}).join(",\n");
});
rCount = rCount - 1;
prettyString = prettyString ++ "\n" ++ indent.value(rCount) ++ "],\n";
};
writeArray.value(data);
prettyString.replace(",\n\n", "\n").drop(-2);
})
};
sanityCheck = {arg motif, index;
//print functions = very helpful
("----------" + index + "------------").postln;
motif.flatten.do({arg val, v;
if(v > 0, {
if(motif.flatten[v-1][0].hammingDistance(val[0]) > 1, {"problem 1".postln});
if(motif.flatten[v-1][0].hammingDistance(val[0]) == 0, {"problem 2".postln});
});
val.postln
});
"***********".postln;
};
msgInterpret = {arg in, escapeDoubleQuotes = true, escapeSingleQuotes = true;
var res;
res = in;
if(res.isNil.not, {
if((res.isArray && res.isString.not), {
res = res.asCompileString;
res = res.replace(" ", "").replace("\n", "").replace("\t", "");
if(escapeSingleQuotes, {res = res.replace("\'", "")});
if(escapeDoubleQuotes, {res = res.replace("\"", "")});
res = res.replace("Rest", "\"Rest\"");
res = res.interpret;
}, {
//res.postln;
if(res.every({arg char; char.isDecDigit}), {res = res.asInteger});
});
});
res
};
writeResources = {arg path, dict;
var file, modelItems, resString;
file = File(path,"w");
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
resString = nameSpaces.collect({arg nameSpace;
var depth = 0, insert = " ";
if(nameSpace == "music_data", {depth = 3; insert = "\n"});
if(nameSpace == "last_changes", {depth = 1; insert = "\n"});
if(nameSpace == "order", {depth = 1; insert = "\n"});
if((nameSpace == "ref_uid") && (dict[nameSpace] == nil), {dict[nameSpace] = "nil"});
"\"" ++ nameSpace ++ "\":" ++ insert ++ stringifyToDepth.value(dict[nameSpace], depth)
}).join(",\n");
resString = "{\n" ++ resString ++ "\n}";
file.write(resString);
file.close;
resString
};
loadModelFile = {arg path; loadModelJSON.value(File(path, "r").readAllString.parseJSON)};
loadModelJSON = {arg jsonObject;
var dict;
dict = Dictionary.with(*nameSpaces.collect({arg nS; nS->msgInterpret.value(jsonObject[nS])}));
dict
};
setGlobalVars = {arg dict;
// order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
dict
};
globalVarsToDict = {
var modelItems, dict;
// order really matters!!!!
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
dict = Dictionary.with(*nameSpaces.collect({arg nS, n; nS->modelItems[n]}));
};
loadLedgerFile = {arg path;
ledgerPath = path;
loadLedgerJSON.value(File(ledgerPath, "r").readAllString.parseJSON)
};
loadLedgerJSON = {arg jsonObject; ledger = jsonObject["ledger"]};
saveLedger = {arg ledger, path;
var file;
file = File(path, "w");
file.write("{\n\"ledger\":\n" ++ stringifyToDepth.value(ledger, 1) ++ "\n}");
file.close;
};
//------global vars
primes = [[2, 1], [3, 2], [5, 4], [7, 4], [11, 8], [13, 8]];
//ranges = [[-2400, 0], [-1200, 1200], [0, 2400], [0, 2400]];
exPath = thisProcess.nowExecutingPath;
dir = exPath.dirname;
//popSize = 4;
dims = primes.size;
tuples = genTuples.value();
//refUID = nil;
group = Group.new;
loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json");
//passagesWeights = [1, 1, 1, 1, 1];
//susWeights = [1, 1, 1];
// order really matters!!!!
nameSpaces = [
"music_data", "last_changes", "cur_uid", "ref_uid", "order_seed", "dur_seed", "motifs_seed",
"entrances_probs_vals","passages_probs_vals", "exits_probs_vals",
"ranges", "passages_weights", "order", "sus_weights", "order_size", "passages_size",
"motif_edited", "order_edited"
];
//------OSC funcs
OSCdef(\load_ledger, {arg msg, time, addr, port;
loadLedgerFile.value(msg[1].asString);
}, \load_ledger);
OSCdef(\load_model, {arg msg, time, addr, port;
var dict;
dict = loadModelFile.value(msg[1].asString);
setGlobalVars.value(dict);
}, \load_model);
OSCdef(\save_ledger, {arg msg, time, addr, port;
msg.postln;
ledger = msgInterpret.value(msg[1].asString.parseJSON["ledger"], false).postln;
//loadLedgerJSON.value(msg[0])
saveLedger.value(ledger, msg[2].asString);
//loadLedgerFile.value(msg[1].asString);
}, \save_ledger);
OSCdef(\generate, {arg msg, time, addr, port;
var path, dict, durSeeds, musPath, modelString;
msg.postln;
path = msg[1].asString;
dict = loadModelFile.value(path);
setGlobalVars.value(dict);
popSize = ranges.size;
//refUID.postln;
loadLedgerFile.value(ledgerPath);
if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, {
[initVoices.value().deepCopy];
}, {
var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
exitsDurFunc = genDurFunc.valueArray(exitsProbVals[..4] ++ [exitsProbVals[5..]] ++ [durSeeds[2]]);
if(orders == nil, {
orders = seedFunc.value(genOrders, orderSeed).valueArray(orderSize ++ passagesSize);
//addr.sendMsg("/order", stringifyToDepth.value(orders, 1));
});
seq = seedFunc.value(genMotif, motifSeed).value;
dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict);
//addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3));
addr.sendMsg("/generated", path, modelString);
}, \generate);
OSCdef(\commit, {arg msg, time, addr, port;
var musicData, musicChanged, dict, newLedger, modelPath, musString, musFile, test1, test2;
//msg.postln;
/*
test1 = msg[1].asString.parseJSON;
test2 = (dir +/+ ".." +/+ "resources/tmp/tmp_music" ++ ".json").standardizePath.parseJSONFile;
msgInterpret.value(test1["music"])[0][0][0][1].class.postln;
msgInterpret.value(test2["music_data"])[0][0][0][1].class.postln;
(test1["music"] == test2["music_data"]).postln;
*/
musicData = loadModelJSON.value(msg[1].asString.parseJSON)["music_data"].postln;
musicChanged = (musicData != seq).postln;
curUID = genUID.value;
File.mkdir((dir +/+ ".." +/+ "resources" +/+ curUID).standardizePath);
File.copy(exPath, (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_code" ++ ".scd").standardizePath);
modelPath = (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_mus_model" ++ ".json").standardizePath;
dict = globalVarsToDict.value;
if(musicChanged, {
seq = musicData;
dict["music_data"] = seq;
dict["motif_edited"] = "true"
});
dict["cur_uid"] = curUID;
writeResources.value(modelPath, dict);
File.delete(ledgerPath ++ "_bak");
File.copy(ledgerPath, ledgerPath ++ "_bak");
File.delete(ledgerPath);
ledger = ledger.drop(-1).add(curUID);
saveLedger.value(ledger, ledgerPath);
addr.sendMsg("/committed", curUID, ledgerPath);
//refUID = curUID;
}, \commit);
OSCdef(\transport, {arg msg, time, addr, port;
msg.postln;
if(msg[1] == 0, {
player.stop;
group.set(\gate, 0);
}, {
// the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
if(msg[1] == 1, {
pSeq = [];
cuedSeek = (seq != nil);
indexStart = msg[2].asInteger;
indexEnd = ledger.size - if(cuedSeek, {2}, {1});
//ledger.postln;
if(((indexStart == (ledger.size - 1)) && cuedSeek).not, {
ledger[indexStart..indexEnd].do({arg uid, index;
var path, file;
path = (dir +/+ ".." +/+ "resources" +/+ uid +/+ uid ++ "_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.postln.parseJSON["music_data"]), path, indexStart + index, uid]);
file.close;
});
});
if(cuedSeek, {
var path, file;
path = (dir +/+ ".." +/+ "resources/tmp/tmp_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.parseJSON["music_data"]), path, ledger.size - 1, "tmp"]);
file.close;
});
}, {
"here".postln;
pSeq = [loadModelJSON.value(msg[2].asString.parseJSON)["music_data"].postln];
});
patterns = genPatterns.value(pSeq, addr);
player = Pfset(pattern: patterns, cleanupFunc: {
addr.sendMsg("/transport", 0);
});
player = player.play
});
}, \transport);
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms;
noHarms = 30;
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add;
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms, freqFinal, start, end;
noHarms = 30;
freq = WhiteNoise.ar * 3 + freq;
freqFinal = Duty.ar((1/freq), 0, freq);
trig = Changed.ar(freqFinal);
start = Demand.ar(trig, 0, Dwhite(-1, -0.75));
end = Demand.ar(trig, 0, Dwhite(0.75, 1));
exc = Phasor.ar(trig, (end - start) * freqFinal / SampleRate.ir, start, end, 0) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(2, 3)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
}).add;
)
"{\"a\": 1}".parseYAML["a"].asInteger;
"{\"a\": 1}".parseJSON["a"].isNumber;
1223423434123.asHexString.toLower
Date.getDate.rawSeconds
Date.seed.asHexString.toLower
n = NetAddr("localhost", 8080);
n.sendMsg("/GET/#", (NetAddr.localAddr.hostname ++ ":" ++ NetAddr.localAddr.port), "/passage_probs_vals");

@ -1,55 +0,0 @@
{
"music_data":
[
[
[
[ [ [ "Rest" ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 16.75 ],
[ [ [ 0, 0, 1, 0, 0, 0 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0.125 ],
[ [ [ 1, -1, 0, 0, 0, 0 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0.5 ],
[ [ [ 0, 1, 0, 0, 0, 0 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0 ],
[ [ [ 0, 0, 0, 1, 0, 0 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0.375 ],
[ [ [ 1, 0, 0, 0, 0, 0 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0.25 ],
[ [ [ 2, 0, 0, -1, 0, 0 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0.25 ],
[ [ [ 2, 0, 0, 0, 0, -1 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0.25 ],
[ [ [ 2, -1, 0, 0, 0, 0 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0.375 ],
[ [ [ 1, 1, 0, 0, 0, 0 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0.125 ],
[ [ [ 2, 0, -1, 0, 0, 0 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 3.25 ]
],
[
[ [ [ 2, 0, -1, 0, 0, 0 ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 0 ],
[ [ [ 2, 0, -1, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 9.375 ],
[ [ [ 2, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 3.125 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 3.25 ]
]
]
],
"last_changes":
[
[ [ 2, 0, 0, 0, 0, -1 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 2, -1, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 1, 1, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 2, 0, -1, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 2, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]
],
"cur_uid": "46f2010f",
"ref_uid": "nil",
"order_seed": 209033,
"dur_seed": 797162,
"motifs_seed": 128998,
"entrances_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.26424870466321, 0.75675675675676, 0.5, 0.5, 0.58549222797927, 0.72635135135135, 1, 0.5 ],
"passages_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ -384, 2400 ], [ -507, 2400 ], [ -282, 2237 ], [ -1200, 2053 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ],
"order":
[
[ [ 2 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 3, 1 ] ],
[ [ 1 ], [ 0 ], [ 2, 3 ] ]
],
"sus_weights": [ 0.75, 0.69, 0.75 ],
"order_size": [ 2, 6 ],
"passages_size": [ 0, 10 ],
"motif_edited": "true",
"order_edited": "false"
}

@ -283,7 +283,7 @@ genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLa
}); });
//format and return //format and return
if(startFromLast, {lastXChanges = lastXChangesHold}); if(startFromLast, {lastXChanges = lastXChangesHold.deepCopy});
res; res;
}; };
@ -359,10 +359,17 @@ genPatterns = {arg inSeq, addr, oneShot = false;
seq = inSeq.collect({arg mSeq; mSeq[0]}); seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop; # voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
pbinds = voices.flop.collect({arg voice, v; pbinds = voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs; var clumps, hdScores, freqs, fDurs, attacks, rels, amps;
clumps = voice.separate({arg a, b; a != b }); clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})}); freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum}); fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
//attacks = 2.collect({rrand(1, 3)}) ++ freqs.drop(2).collect({rrand(0.3, 0.5)});
attacks = fDurs.collect({arg dur; dur * rrand(0.2, 0.4)});
//rels = freqs.drop(2).collect({rrand(0.3, 0.5)}) ++ 2.collect({rrand(1, 3)});
rels = (clumps.size - 1).collect({arg c;
if(clumps[c + 1][0] == ["Rest"], {rrand(1, 3)}, {rrand(0.3, 0.5)});
});
amps = freqs.collect({rrand(0.6, 0.99)});
[ [
Pbind( Pbind(
@ -370,7 +377,11 @@ genPatterns = {arg inSeq, addr, oneShot = false;
\group, group, \group, group,
\freq, Pseq(freqs, 1), \freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1), \dur, Pseq(fDurs, 1),
\attack, Pseq(attacks, 1),
\sustain, Pseq(fDurs, 1), \sustain, Pseq(fDurs, 1),
\release, Pseq(rels, 1),
//\amp, Pseq(amps, 1),
\amp, Pbrown(0.5, 1, 0.5),
\busIndex, v \busIndex, v
), ),
Pbind( Pbind(
@ -549,12 +560,15 @@ loadModelJSON = {arg jsonObject;
dict dict
}; };
setGlobalVars = {arg dict; setGlobalVars = {arg dict, skipLastXChanges = false;
var tmpLastXChanges;
tmpLastXChanges = lastXChanges.deepCopy;
// order really matters!!!! // order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed, # seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals, entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize, ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]}); motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
if(skipLastXChanges, {lastXChanges = tmpLastXChanges});
dict dict
}; };
@ -636,7 +650,7 @@ OSCdef(\generate, {arg msg, time, addr, port;
path = msg[1].asString; path = msg[1].asString;
dict = loadModelFile.value(path); dict = loadModelFile.value(path);
setGlobalVars.value(dict); setGlobalVars.value(dict, true);
popSize = ranges.size; popSize = ranges.size;
@ -646,14 +660,16 @@ OSCdef(\generate, {arg msg, time, addr, port;
if(ledger == nil, {ledger = ["tmp"]}); if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")}); if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, { if(refUID == nil, {lastXChanges = [initVoices.value().deepCopy]});
[initVoices.value().deepCopy]; if((refUID != nil) && (refUID != "tmp"), {
}, {
var file; var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r"); file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]); lastXChanges = msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
}); });
refUID.postln;
lastXChanges.collect({arg item; item.postln});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln; durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]); entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]); passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
@ -665,6 +681,8 @@ OSCdef(\generate, {arg msg, time, addr, port;
}); });
seq = seedFunc.value(genMotif, motifSeed).value; seq = seedFunc.value(genMotif, motifSeed).value;
lastXChanges.collect({arg item; item.postln});
dict = globalVarsToDict.value; dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict); modelString = writeResources.value(path, dict);
@ -719,8 +737,9 @@ OSCdef(\commit, {arg msg, time, addr, port;
OSCdef(\transport, {arg msg, time, addr, port; OSCdef(\transport, {arg msg, time, addr, port;
msg.postln; msg.postln;
if(msg[1] == 0, { if(msg[1] == 0, {
player.stop; group.set(\release, 2);
group.set(\gate, 0); group.set(\gate, 0);
player.stop;
}, { }, {
// the cued sequence can now be read from file, so this can be cleaned up // the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger; var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
@ -769,15 +788,15 @@ OSCdef(\transport, {arg msg, time, addr, port;
~hdustBusArray = 1.collect({Bus.audio(s, 1)}); ~hdustBusArray = 1.collect({Bus.audio(s, 1)});
~samplerBusArray = 2.collect({Bus.audio(s, 1)}); ~samplerBusArray = 2.collect({Bus.audio(s, 1)});
~sBuf = Buffer.alloc(s, 10, 2); ~sBuf = Buffer.alloc(s, 10, 2);
SynthDef(\string_model, {arg freq, gate = 1, sustain, amp, dur, busIndex = 0; SynthDef(\string_model, {arg freq, gate = 1, sustain, amp, dur, attack, release = 1, busIndex = 0;
var trig, exc, sig1, sig2, noHarms; var trig, exc, sig1, sig2, noHarms;
noHarms = 30; noHarms = rrand(20, 40);
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01); exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq), sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}), Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.8).softclip; Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.8).softclip;
sig1 = HPF.ar(sig1, 300); //sig1 = HPF.ar(sig1, 300);
Out.ar(Select.kr(busIndex, ~stringModelBusArray), sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2)); Out.ar(Select.kr(busIndex, ~stringModelBusArray), sig1 * amp * EnvGen.kr(Env.adsr(attack, 0.3, 0.9, release, 0.9, -3), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2)); //Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add; }).add;
@ -785,6 +804,7 @@ SynthDef(\sine, {arg freq, gate = 1, sustain, amp, dur, busIndex = 0;
var sig; var sig;
sig = SinOsc.ar(freq); sig = SinOsc.ar(freq);
Out.ar(Select.kr(busIndex, ~sineBusArray), sig * EnvGen.kr(Env.asr(0.3, 0.4, 0.3), gate, timeScale: dur, doneAction: 2)); Out.ar(Select.kr(busIndex, ~sineBusArray), sig * EnvGen.kr(Env.asr(0.3, 0.4, 0.3), gate, timeScale: dur, doneAction: 2));
//Out.ar(Select.kr(busIndex, ~sineBusArray), sig * EnvGen.kr(Env.sine(dur), gate, doneAction: 2));
}).add; }).add;
SynthDef(\mixer, {arg freq, gate = 1, sustain, amp, dur, out; SynthDef(\mixer, {arg freq, gate = 1, sustain, amp, dur, out;

@ -0,0 +1,48 @@
{
"music_data":
[
[
[
[ [ [ "Rest" ], [ "Rest" ], [ 7, -7, -4, 0, -1, -2 ], [ "Rest" ] ], 2.25 ],
[ [ [ "Rest" ], [ "Rest" ], [ 7, -7, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 3.875 ],
[ [ [ 8, -7, -4, 1, -1, -2 ], [ "Rest" ], [ 7, -7, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 1.125 ],
[ [ [ 8, -7, -4, 1, -1, -2 ], [ 7, -8, -4, 0, -1, -2 ], [ 7, -7, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 6.5 ]
],
[
[ [ [ 8, -7, -4, 1, -1, -2 ], [ "Rest" ], [ 7, -7, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 2 ],
[ [ [ 8, -7, -4, 1, -1, -2 ], [ "Rest" ], [ 6, -7, -3, 1, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 7.125 ],
[ [ [ "Rest" ], [ "Rest" ], [ 6, -7, -3, 1, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 0 ],
[ [ [ "Rest" ], [ "Rest" ], [ 6, -7, -3, 1, -1, -2 ], [ "Rest" ] ], 1.625 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 5.5 ]
]
]
],
"last_changes":
[
[ [ 8, -6, -4, 0, -1, -2 ], [ 6, -5, -4, 0, -1, -3 ], [ 6, -5, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ],
[ [ 8, -6, -4, 0, -1, -2 ], [ 6, -5, -4, 0, -1, -3 ], [ 7, -7, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ],
[ [ 8, -7, -4, 1, -1, -2 ], [ 6, -5, -4, 0, -1, -3 ], [ 7, -7, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ],
[ [ 8, -7, -4, 1, -1, -2 ], [ 7, -8, -4, 0, -1, -2 ], [ 7, -7, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ],
[ [ 8, -7, -4, 1, -1, -2 ], [ 7, -8, -4, 0, -1, -2 ], [ 6, -7, -3, 1, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ]
],
"cur_uid": "4b96f62d",
"ref_uid": "703e109b",
"order_seed": 550421,
"dur_seed": 808010,
"motifs_seed": 180604,
"entrances_probs_vals": [ 0.52, 0.56, 5.1984126984127, 0.76923076923077, 2.31, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"passages_probs_vals": [ 0.52, 0.56, 5.1984126984127, 0.76923076923077, 2.31, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0.52, 0.56, 5.1984126984127, 0.76923076923077, 2.31, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ 1211.1455108359, 2400 ], [ -1650, 450 ], [ -405, 1137 ], [ 951.08359133127, 2053 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ],
"order":
[
[ [ 2, 3 ], [ 0, 1 ], [ ] ],
[ [ 3, 0 ], [ 2 ], [ 1 ] ]
],
"sus_weights": [ 0.73, 0.49, 0 ],
"order_size": [ 1, 3 ],
"passages_size": [ 0, 0 ],
"motif_edited": "false",
"order_edited": "false"
}

@ -1,794 +0,0 @@
(
// helper funcs
var hsArrayToCents, pDist, hdSum, hsChordalDistance, hsArrayToFreq;
// score funcs
var isInRange, spacingScore, rangeScore, intervalScore, inclusionScore;
// subroutines
var genTuples, initVoices, genOrders, genSubMotif, updateVoices, genDurFunc;
// primary routines
var genMotif, genSecondarySeq;
// audition funcs
var genPatterns, genMidiPatterns;
// resource management funcs
var seedFunc, genUID, writeResources, stringifyToDepth, setSeeds, sanityCheck,
msgInterpret, loadLedgerFile, loadLedgerJSON, loadModelFile, loadModelJSON,
setGlobalVars, globalVarsToDict, saveLedger;
// model vars
//(model and global vars mostly set by OSC funcs
var seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited;
// model aux vars
var entrancesDurFunc, passagesDurFunc, exitsDurFunc;
// other global vars
var popSize, exPath, dir, primes, dims, tuples,
group, player, ledgerPath, ledger, currentlyPlayingUID,
nameSpaces;
// install JSON quark
if(Quarks.isInstalled("JSONlib").not, {
Quarks.install("https://github.com/musikinformatik/JSONlib.git");
thisProcess.recompile;
//HelpBrowser.openHelpFor("Classes/JSONlib");
});
//------helper funcs
hsArrayToCents = {
arg hsArray;
hsArray.collect({arg dist, p; dist * 1200 * log2(primes[p][0]/primes[p][1])}).sum
};
pDist = {
arg array1, array2, signed = false;
var pDistance;
pDistance = hsArrayToCents.value(array1) - hsArrayToCents.value(array2);
if(signed, {pDistance}, {abs(pDistance)})
};
hdSum = {
arg hsArrays;
var size, distances, mean;
size = hsArrays.size;
distances = (size - 1).collect({arg i;
((i + 1)..(size - 1)).collect({arg j;
abs(hsArrays[i] - hsArrays[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsChordalDistance = {
arg hsArrays1, hsArrays2;
var size, distances, mean;
size = hsArrays1.size;
distances = hsArrays1.size.collect({arg i;
hsArrays2.size.collect({arg j;
abs(hsArrays1[i] - hsArrays2[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsArrayToFreq = {
arg array;
array.collect({arg dim, d; pow(primes[d][0]/primes[d][1], dim)}).product
};
//------score funcs
/*
isInRange = {
arg hsArray, min, max;
var cents;
cents = hsArrayToCents.value(hsArray);
(cents >= min) && (cents <= max)
};
*/
spacingScore = {
arg hsArrays, min;
var centsArray;
centsArray = hsArrays.collect({arg hsArray; hsArrayToCents.value(hsArray)}).sort({arg a, b; a < b});
centsArray.differentiate.drop(1).collect({arg pDistance; if(pDistance >= min, {1}, {0.01})}).sum;
};
rangeScore = {
arg hsArray1, hsArray2, min, max, low, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
if((pDistance >= min) && (pDistance <= max), {1}, {low});
};
intervalScore = {
arg hsArray1, hsArray2, mean, sd, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
pDistance.gaussCurve(1, mean, sd)
};
inclusionScore = {
arg array, test, min = 0.01;
if(array.collect({arg v; v.hash}).includes(test.hash), {min}, {1});
};
//------subroutines
genTuples = {
var tuples;
tuples = dims.collect({[-1, 0, 1]}).allTuples.select({arg tuple; (abs(tuple.drop(1)).sum <= 1) && (tuple[0] == 0)});
tuples = tuples ++ tuples.collect({arg tuple; [-3, -2, -1, 1, 2, 3].collect({arg octTrans; tuple.deepCopy.put(0, octTrans)})}).flatten;
};
initVoices = {
var init, voicesInit;
voicesInit = popSize.collect({dims.collect({0})});
/*
voicesInit = [dims.collect({0})];
(popSize - 1).do({
arg rep, new;
rep = dims.rand;
new = voicesInit.last.deepCopy;
new[rep] = new[rep] + [-1, 1].choose();
voicesInit = voicesInit.add(new);
});
*/
voicesInit.deepCopy;
};
genDurFunc = {arg chordProb, minPad, maxPad, minDur, maxDur, envData, seed;
var env, pTable, durFunc;
env = Env.pairs([[0, 0]] ++ envData.clump(2) ++ [[1, 0]]).asSignal(256).asList.asArray;
pTable = env.asRandomTable;
[chordProb, minPad, maxPad, minDur, maxDur, envData].postln;
durFunc = {arg allowChord, pad = false;
var res;
res = if(allowChord.not, {
pTable.tableRand * (maxDur - minDur) + minDur
}, {
if(1.0.rand < chordProb, {0}, {pTable.tableRand * (maxDur - minDur) + minDur});
}).round(0.125);
if(pad, {res = res + rrand(minPad.asFloat, maxPad.asFloat).round(0.125)});
if(res.asInteger == res, {res = res.asInteger});
res
};
seedFunc.value(durFunc, seed);
};
genOrders = {arg minMotifLength = 1, maxMotifLength = 5, minProgLength = 0, maxProgLength = 5;
((maxMotifLength - minMotifLength).rand + minMotifLength).collect({
var noProgIns, noSusIns, noSilentIns, prog, sus, silent, order;
noSusIns = [1, 2, 3].wchoose(susWeights.normalizeSum);
noProgIns = (popSize - noSusIns).rand + 1;
noSilentIns = popSize - noSusIns - noProgIns;
# prog, sus, silent = (0..(popSize-1)).scramble.clumps([noProgIns, noSusIns, noSilentIns]);
prog = (prog.scramble ++ ((maxProgLength - minProgLength).rand + minProgLength).collect({prog.choose}).scramble);
if(silent == nil, {silent = []});
[sus.scramble, prog, silent.scramble]
});
};
updateVoices = {arg ins, sus;
var voices, candidates, nWeights, nProbs, sel;
voices = lastXChanges.deepCopy.last;
candidates = sus.collect({arg v; tuples.collect({arg t; voices[v] + t})}).flatten;
candidates = difference(candidates.asSet, voices.asSet).asList;
nProbs = candidates.collect({arg candidate;
var stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore;
//stepScore = intervalScore.value(voices[ins], candidate, 30, 400, 0.1);
stepScore = intervalScore.value(voices[ins], candidate, 100, 100);
recentlySoundedScore = inclusionScore.value(lastXChanges.flop[ins], candidate, 0);
isInRangeScore = rangeScore.value(candidate, candidate.collect({0}), ranges[ins][0], ranges[ins][1], 0, true);
regScore = spacingScore.value(voices.deepCopy.put(ins, candidate), 300);
hdScore = 1/pow(hdSum.value(voices.deepCopy.put(ins, candidate)), 2);
//maybe what you want here is a vector to another root and then favoring movement towards it.
//distScore = pow(hsChordalDistance.value(voices, voices.put(ins, candidate)), 2);
[stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore]
});
nWeights = passagesWeights;
//this handles nWeights of 0; mainly for testing
nProbs = nProbs.flop.select({arg scores, s; nWeights[s] != 0}).flop;
nWeights = nWeights.select({arg weight; weight != 0});
nProbs = nProbs.flop.collect({arg scores, s;
if(scores.sum == 0, {scores}, {scores.normalizeSum * nWeights[s]})
});
nProbs = nProbs.flop.collect({arg scores, s; scores.product}).normalizeSum;
sel = candidates.wchoose(nProbs);
voices[ins] = sel;
lastXChanges = lastXChanges.add(voices).keep(-5);
};
genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLast = false, isLastOrder = false;
var sus, prog, silent, flatOrder, res, isInChord, allowChord, pad, lastXChangesHold, voices, adder;
# sus, prog, silent = order;
flatOrder = silent ++ sus ++ prog;
lastXChangesHold = lastXChanges.deepCopy;
voices = lastState.deepCopy;
isInChord = popSize.collect({false});
allowChord = false;
pad = false;
res = [];
"------generating motif".postln;
//need to figure out here if voices move between motifs
flatOrder.do({arg ins, i;
if(prog.includes(ins) && repeatLast.not, {updateVoices.value(ins, sus)});
adder = if(silent.includes(ins), {["Rest"]}, {lastXChanges.last.deepCopy[ins]});
if(voices[ins] != adder, {
var dur;
if((sus ++ silent).includes(ins), {
allowChord = (ins != sus.last);
pad = (ins == sus.last);
}, {
if(i < (flatOrder.size - 1), {
allowChord = (isInChord[flatOrder[i + 1]] || (ins == flatOrder[i + 1])).not;
pad = false;
}, {
allowChord = false;
pad = true
});
});
if((orderIndex == 0) && sus.includes(ins), {
dur = entrancesDurFunc.value(allowChord, pad);
}, {
dur = passagesDurFunc.value(allowChord, pad);
});
if(dur == 0, {isInChord[ins] = true}, {isInChord = popSize.collect({false})});
voices[ins] = adder;
res = res.add([voices.deepCopy.postln, dur]);
});
});
// pad ending
if(orderIndex == (orders.size - 1), {
(0..(popSize-1)).scramble.do({arg ins;
if(res.last.first[ins] != ["Rest"], {
var dur;
voices[ins] = ["Rest"];
allowChord = (voices != popSize.collect({["Rest"]}));
pad = allowChord.not;
dur = exitsDurFunc.value(allowChord, pad);
res = res.add([voices.deepCopy.postln, dur]);
});
});
});
//format and return
if(startFromLast, {lastXChanges = lastXChangesHold});
res;
};
//------primary routines
genMotif = {
var repeats, fSeq;
repeats = 1;
fSeq = [];
repeats.do({arg index;
var motif;
motif = [];
orders.do({arg order, o;
var lastState, subMotif;
lastState = if(o == 0, {popSize.collect({["Rest"]})}, {motif.last.last.first});
subMotif = genSubMotif.value(order, o, lastState, isLastOrder: o == (orders.size - 1));
motif = motif.add(subMotif);
});
sanityCheck.value(motif, index);
fSeq = fSeq.add(motif);
});
fSeq
};
genSecondarySeq = {arg seq;
var curdles, fSeq;
curdles = [];
while({curdles.sum < seq.size}, {curdles = curdles ++ [3.rand + 1]});
fSeq = seq.clumps(curdles).collect({arg clump, m;
var repeats, paddedSeq;
//add rest
paddedSeq = clump.add([[[popSize.collect({["Rest"]}), 0.5.rand]]]);
//implement repeats
repeats = [0.rand + 1, 1].wchoose([1, 0].normalizeSum);
repeats.collect({paddedSeq});
});
fSeq
};
//------audition funcs
/*
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~addr.sendMsg(~indexPath, ~indexMsg);
~addr.sendMsg(~seqPath, stringifyToDepth.value(~seqMsg, 3));
//~addr.sendMsg("/STATE/OPEN", (dir.replace("supercollider", "resources") +/+ ~idMsg +/+ ~idMsg ++ "_gui_state" ++ ".state").standardizePath.postln);
};
});
*/
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~msg.postln;
~addr.sendMsg(~path, *~msg);
};
});
genPatterns = {arg inSeq, addr, oneShot = false;
var voices, durs, pbinds, res, indices, sectionDurs, msg, ids, seq;
seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
pbinds = voices.flop.collect({arg voice;
var clumps, hdScores, freqs, fDurs;
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\instrument, \test,
\group, group,
\freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1),
\sustain, Pseq(fDurs, 1)
)
});
if(oneShot.not, {
msg = inSeq.collect({arg mSeq, m; mSeq[1..]});
//ids = inSeq.collect({arg mSeq, m; mSeq[2]});
sectionDurs = seq.collect({arg mSeq; mSeq.flatten2(mSeq.maxDepth - 5).flop[1].sum});
pbinds = pbinds ++
[
Pbind(
\type, \osc,
\addr, addr,
\path, "/playing",
\msg, Pseq(msg, 1),
\dur, Pseq(sectionDurs, 1)
);
]
});
res = Ppar(pbinds);
res
};
/*
genMidiPatterns = {arg seq;
var voices, durs, patterns, res, mOut, pbRange;
pbRange = 1; //semitones - change this as needed for your situation
mOut = MIDIOut.newByName("TiMidity", "TiMidity port 0").latency_(Server.default.latency);
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
res = Ppar(
voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs;
mOut.program(v, 70);
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\type, \midi,
\chan, v,
\noteval, Pseq(freqs.cpsmidi - 24, 1),
\note, Pfunc({ | event | event[\noteval].floor }),
\dur, Pseq(fDurs, 1),
\midiout, mOut,
\amp, 1,
\bend, Pfunc({
| event |
if (event[\note].isRest.not) {
var pitchbendvalue = event[\noteval].frac.linlin(0, pbRange, 8192, 8192*2).asInteger;
m.bend(v, pitchbendvalue);
};
0; // return something other than nil to avoid stopping the pattern
}),
);
});
);
res
};
*/
//------resource management funcs
genUID = {Date.seed.asHexString.toLower};
seedFunc = {arg func, seed;
var funcArgs, next;
next = Routine({loop{func.valueArray(funcArgs).yield }});
next.randSeed_(seed);
{arg ...args; funcArgs = args; next.value}
};
stringifyToDepth = {arg data, maxDepth = 1;
var prettyString = "", rCount = 0, writeArray, indent;
if(maxDepth == 0, {
data.asCompileString
}, {
indent = {arg size; size.collect({" "}).join("")};
writeArray = {arg array;
prettyString = prettyString ++ indent.value(rCount) ++ "[\n";
rCount = rCount + 1;
if(rCount < maxDepth, {
array.do({arg subArray; writeArray.value(subArray)});
}, {
prettyString = prettyString ++ array.collect({arg subArray;
indent.value(rCount + 1) ++ subArray.asCompileString
}).join(",\n");
});
rCount = rCount - 1;
prettyString = prettyString ++ "\n" ++ indent.value(rCount) ++ "],\n";
};
writeArray.value(data);
prettyString.replace(",\n\n", "\n").drop(-2);
})
};
sanityCheck = {arg motif, index;
//print functions = very helpful
("----------" + index + "------------").postln;
motif.flatten.do({arg val, v;
if(v > 0, {
if(motif.flatten[v-1][0].hammingDistance(val[0]) > 1, {"problem 1".postln});
if(motif.flatten[v-1][0].hammingDistance(val[0]) == 0, {"problem 2".postln});
});
val.postln
});
"***********".postln;
};
msgInterpret = {arg in, escapeDoubleQuotes = true, escapeSingleQuotes = true;
var res;
res = in;
if(res.isNil.not, {
if((res.isArray && res.isString.not), {
res = res.asCompileString;
res = res.replace(" ", "").replace("\n", "").replace("\t", "");
if(escapeSingleQuotes, {res = res.replace("\'", "")});
if(escapeDoubleQuotes, {res = res.replace("\"", "")});
res = res.replace("Rest", "\"Rest\"");
res = res.interpret;
}, {
//res.postln;
if(res.every({arg char; char.isDecDigit}), {res = res.asInteger});
});
});
res
};
writeResources = {arg path, dict;
var file, modelItems, resString;
file = File(path,"w");
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
resString = nameSpaces.collect({arg nameSpace;
var depth = 0, insert = " ";
if(nameSpace == "music_data", {depth = 3; insert = "\n"});
if(nameSpace == "last_changes", {depth = 1; insert = "\n"});
if(nameSpace == "order", {depth = 1; insert = "\n"});
if((nameSpace == "ref_uid") && (dict[nameSpace] == nil), {dict[nameSpace] = "nil"});
"\"" ++ nameSpace ++ "\":" ++ insert ++ stringifyToDepth.value(dict[nameSpace], depth)
}).join(",\n");
resString = "{\n" ++ resString ++ "\n}";
file.write(resString);
file.close;
resString
};
loadModelFile = {arg path; loadModelJSON.value(File(path, "r").readAllString.parseJSON)};
loadModelJSON = {arg jsonObject;
var dict;
dict = Dictionary.with(*nameSpaces.collect({arg nS; nS->msgInterpret.value(jsonObject[nS])}));
dict
};
setGlobalVars = {arg dict;
// order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
dict
};
globalVarsToDict = {
var modelItems, dict;
// order really matters!!!!
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
dict = Dictionary.with(*nameSpaces.collect({arg nS, n; nS->modelItems[n]}));
};
loadLedgerFile = {arg path;
ledgerPath = path;
loadLedgerJSON.value(File(ledgerPath, "r").readAllString.parseJSON)
};
loadLedgerJSON = {arg jsonObject; ledger = jsonObject["ledger"]};
saveLedger = {arg ledger, path;
var file;
file = File(path, "w");
file.write("{\n\"ledger\":\n" ++ stringifyToDepth.value(ledger, 1) ++ "\n}");
file.close;
};
//------global vars
primes = [[2, 1], [3, 2], [5, 4], [7, 4], [11, 8], [13, 8]];
//ranges = [[-2400, 0], [-1200, 1200], [0, 2400], [0, 2400]];
exPath = thisProcess.nowExecutingPath;
dir = exPath.dirname;
//popSize = 4;
dims = primes.size;
tuples = genTuples.value();
//refUID = nil;
group = Group.new;
loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json");
//passagesWeights = [1, 1, 1, 1, 1];
//susWeights = [1, 1, 1];
// order really matters!!!!
nameSpaces = [
"music_data", "last_changes", "cur_uid", "ref_uid", "order_seed", "dur_seed", "motifs_seed",
"entrances_probs_vals","passages_probs_vals", "exits_probs_vals",
"ranges", "passages_weights", "order", "sus_weights", "order_size", "passages_size",
"motif_edited", "order_edited"
];
//------OSC funcs
OSCdef(\load_ledger, {arg msg, time, addr, port;
loadLedgerFile.value(msg[1].asString);
}, \load_ledger);
OSCdef(\load_model, {arg msg, time, addr, port;
var dict;
dict = loadModelFile.value(msg[1].asString);
setGlobalVars.value(dict);
}, \load_model);
OSCdef(\save_ledger, {arg msg, time, addr, port;
msg.postln;
ledger = msgInterpret.value(msg[1].asString.parseJSON["ledger"], false).postln;
//loadLedgerJSON.value(msg[0])
saveLedger.value(ledger, msg[2].asString);
//loadLedgerFile.value(msg[1].asString);
}, \save_ledger);
OSCdef(\generate, {arg msg, time, addr, port;
var path, dict, durSeeds, musPath, modelString;
msg.postln;
path = msg[1].asString;
dict = loadModelFile.value(path);
setGlobalVars.value(dict);
popSize = ranges.size;
//refUID.postln;
loadLedgerFile.value(ledgerPath);
if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, {
[initVoices.value().deepCopy];
}, {
var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
exitsDurFunc = genDurFunc.valueArray(exitsProbVals[..4] ++ [exitsProbVals[5..]] ++ [durSeeds[2]]);
if(orders == nil, {
orders = seedFunc.value(genOrders, orderSeed).valueArray(orderSize ++ passagesSize);
//addr.sendMsg("/order", stringifyToDepth.value(orders, 1));
});
seq = seedFunc.value(genMotif, motifSeed).value;
dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict);
//addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3));
addr.sendMsg("/generated", path, modelString);
}, \generate);
OSCdef(\commit, {arg msg, time, addr, port;
var musicData, musicChanged, dict, newLedger, modelPath, musString, musFile, test1, test2;
//msg.postln;
/*
test1 = msg[1].asString.parseJSON;
test2 = (dir +/+ ".." +/+ "resources/tmp/tmp_music" ++ ".json").standardizePath.parseJSONFile;
msgInterpret.value(test1["music"])[0][0][0][1].class.postln;
msgInterpret.value(test2["music_data"])[0][0][0][1].class.postln;
(test1["music"] == test2["music_data"]).postln;
*/
musicData = loadModelJSON.value(msg[1].asString.parseJSON)["music_data"].postln;
musicChanged = (musicData != seq).postln;
curUID = genUID.value;
File.mkdir((dir +/+ ".." +/+ "resources" +/+ curUID).standardizePath);
File.copy(exPath, (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_code" ++ ".scd").standardizePath);
modelPath = (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_mus_model" ++ ".json").standardizePath;
dict = globalVarsToDict.value;
if(musicChanged, {
seq = musicData;
dict["music_data"] = seq;
dict["motif_edited"] = "true"
});
dict["cur_uid"] = curUID;
writeResources.value(modelPath, dict);
File.delete(ledgerPath ++ "_bak");
File.copy(ledgerPath, ledgerPath ++ "_bak");
File.delete(ledgerPath);
ledger = ledger.drop(-1).add(curUID);
saveLedger.value(ledger, ledgerPath);
addr.sendMsg("/committed", curUID, ledgerPath);
//refUID = curUID;
}, \commit);
OSCdef(\transport, {arg msg, time, addr, port;
msg.postln;
if(msg[1] == 0, {
player.stop;
group.set(\gate, 0);
}, {
// the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
if(msg[1] == 1, {
pSeq = [];
cuedSeek = (seq != nil);
indexStart = msg[2].asInteger;
indexEnd = ledger.size - if(cuedSeek, {2}, {1});
//ledger.postln;
if(((indexStart == (ledger.size - 1)) && cuedSeek).not, {
ledger[indexStart..indexEnd].do({arg uid, index;
var path, file;
path = (dir +/+ ".." +/+ "resources" +/+ uid +/+ uid ++ "_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.postln.parseJSON["music_data"]), path, indexStart + index, uid]);
file.close;
});
});
if(cuedSeek, {
var path, file;
path = (dir +/+ ".." +/+ "resources/tmp/tmp_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.parseJSON["music_data"]), path, ledger.size - 1, "tmp"]);
file.close;
});
}, {
pSeq = [loadModelJSON.value(msg[2].asString.parseJSON)["music_data"].postln];
});
patterns = genPatterns.value(pSeq, addr);
player = Pfset(pattern: patterns, cleanupFunc: {
addr.sendMsg("/transport", 0);
});
player = player.play
});
}, \transport);
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms;
noHarms = 30;
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add;
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms, freqFinal, start, end;
noHarms = 30;
freq = WhiteNoise.ar * 3 + freq;
freqFinal = Duty.ar((1/freq), 0, freq);
trig = Changed.ar(freqFinal);
start = Demand.ar(trig, 0, Dwhite(-1, -0.75));
end = Demand.ar(trig, 0, Dwhite(0.75, 1));
exc = Phasor.ar(trig, (end - start) * freqFinal / SampleRate.ir, start, end, 0) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(2, 3)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
}).add;
)
"{\"a\": 1}".parseYAML["a"].asInteger;
"{\"a\": 1}".parseJSON["a"].isNumber;
1223423434123.asHexString.toLower
Date.getDate.rawSeconds
Date.seed.asHexString.toLower
n = NetAddr("localhost", 8080);
n.sendMsg("/GET/#", (NetAddr.localAddr.hostname ++ ":" ++ NetAddr.localAddr.port), "/passage_probs_vals");

@ -1,794 +0,0 @@
(
// helper funcs
var hsArrayToCents, pDist, hdSum, hsChordalDistance, hsArrayToFreq;
// score funcs
var isInRange, spacingScore, rangeScore, intervalScore, inclusionScore;
// subroutines
var genTuples, initVoices, genOrders, genSubMotif, updateVoices, genDurFunc;
// primary routines
var genMotif, genSecondarySeq;
// audition funcs
var genPatterns, genMidiPatterns;
// resource management funcs
var seedFunc, genUID, writeResources, stringifyToDepth, setSeeds, sanityCheck,
msgInterpret, loadLedgerFile, loadLedgerJSON, loadModelFile, loadModelJSON,
setGlobalVars, globalVarsToDict, saveLedger;
// model vars
//(model and global vars mostly set by OSC funcs
var seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited;
// model aux vars
var entrancesDurFunc, passagesDurFunc, exitsDurFunc;
// other global vars
var popSize, exPath, dir, primes, dims, tuples,
group, player, ledgerPath, ledger, currentlyPlayingUID,
nameSpaces;
// install JSON quark
if(Quarks.isInstalled("JSONlib").not, {
Quarks.install("https://github.com/musikinformatik/JSONlib.git");
thisProcess.recompile;
//HelpBrowser.openHelpFor("Classes/JSONlib");
});
//------helper funcs
hsArrayToCents = {
arg hsArray;
hsArray.collect({arg dist, p; dist * 1200 * log2(primes[p][0]/primes[p][1])}).sum
};
pDist = {
arg array1, array2, signed = false;
var pDistance;
pDistance = hsArrayToCents.value(array1) - hsArrayToCents.value(array2);
if(signed, {pDistance}, {abs(pDistance)})
};
hdSum = {
arg hsArrays;
var size, distances, mean;
size = hsArrays.size;
distances = (size - 1).collect({arg i;
((i + 1)..(size - 1)).collect({arg j;
abs(hsArrays[i] - hsArrays[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsChordalDistance = {
arg hsArrays1, hsArrays2;
var size, distances, mean;
size = hsArrays1.size;
distances = hsArrays1.size.collect({arg i;
hsArrays2.size.collect({arg j;
abs(hsArrays1[i] - hsArrays2[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsArrayToFreq = {
arg array;
array.collect({arg dim, d; pow(primes[d][0]/primes[d][1], dim)}).product
};
//------score funcs
/*
isInRange = {
arg hsArray, min, max;
var cents;
cents = hsArrayToCents.value(hsArray);
(cents >= min) && (cents <= max)
};
*/
spacingScore = {
arg hsArrays, min;
var centsArray;
centsArray = hsArrays.collect({arg hsArray; hsArrayToCents.value(hsArray)}).sort({arg a, b; a < b});
centsArray.differentiate.drop(1).collect({arg pDistance; if(pDistance >= min, {1}, {0.01})}).sum;
};
rangeScore = {
arg hsArray1, hsArray2, min, max, low, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
if((pDistance >= min) && (pDistance <= max), {1}, {low});
};
intervalScore = {
arg hsArray1, hsArray2, mean, sd, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
pDistance.gaussCurve(1, mean, sd)
};
inclusionScore = {
arg array, test, min = 0.01;
if(array.collect({arg v; v.hash}).includes(test.hash), {min}, {1});
};
//------subroutines
genTuples = {
var tuples;
tuples = dims.collect({[-1, 0, 1]}).allTuples.select({arg tuple; (abs(tuple.drop(1)).sum <= 1) && (tuple[0] == 0)});
tuples = tuples ++ tuples.collect({arg tuple; [-3, -2, -1, 1, 2, 3].collect({arg octTrans; tuple.deepCopy.put(0, octTrans)})}).flatten;
};
initVoices = {
var init, voicesInit;
voicesInit = popSize.collect({dims.collect({0})});
/*
voicesInit = [dims.collect({0})];
(popSize - 1).do({
arg rep, new;
rep = dims.rand;
new = voicesInit.last.deepCopy;
new[rep] = new[rep] + [-1, 1].choose();
voicesInit = voicesInit.add(new);
});
*/
voicesInit.deepCopy;
};
genDurFunc = {arg chordProb, minPad, maxPad, minDur, maxDur, envData, seed;
var env, pTable, durFunc;
env = Env.pairs([[0, 0]] ++ envData.clump(2) ++ [[1, 0]]).asSignal(256).asList.asArray;
pTable = env.asRandomTable;
[chordProb, minPad, maxPad, minDur, maxDur, envData].postln;
durFunc = {arg allowChord, pad = false;
var res;
res = if(allowChord.not, {
pTable.tableRand * (maxDur - minDur) + minDur
}, {
if(1.0.rand < chordProb, {0}, {pTable.tableRand * (maxDur - minDur) + minDur});
}).round(0.125);
if(pad, {res = res + rrand(minPad.asFloat, maxPad.asFloat).round(0.125)});
if(res.asInteger == res, {res = res.asInteger});
res
};
seedFunc.value(durFunc, seed);
};
genOrders = {arg minMotifLength = 1, maxMotifLength = 5, minProgLength = 0, maxProgLength = 5;
((maxMotifLength - minMotifLength).rand + minMotifLength).collect({
var noProgIns, noSusIns, noSilentIns, prog, sus, silent, order;
noSusIns = [1, 2, 3].wchoose(susWeights.normalizeSum);
noProgIns = (popSize - noSusIns).rand + 1;
noSilentIns = popSize - noSusIns - noProgIns;
# prog, sus, silent = (0..(popSize-1)).scramble.clumps([noProgIns, noSusIns, noSilentIns]);
prog = (prog.scramble ++ ((maxProgLength - minProgLength).rand + minProgLength).collect({prog.choose}).scramble);
if(silent == nil, {silent = []});
[sus.scramble, prog, silent.scramble]
});
};
updateVoices = {arg ins, sus;
var voices, candidates, nWeights, nProbs, sel;
voices = lastXChanges.deepCopy.last;
candidates = sus.collect({arg v; tuples.collect({arg t; voices[v] + t})}).flatten;
candidates = difference(candidates.asSet, voices.asSet).asList;
nProbs = candidates.collect({arg candidate;
var stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore;
//stepScore = intervalScore.value(voices[ins], candidate, 30, 400, 0.1);
stepScore = intervalScore.value(voices[ins], candidate, 100, 100);
recentlySoundedScore = inclusionScore.value(lastXChanges.flop[ins], candidate, 0);
isInRangeScore = rangeScore.value(candidate, candidate.collect({0}), ranges[ins][0], ranges[ins][1], 0, true);
regScore = spacingScore.value(voices.deepCopy.put(ins, candidate), 300);
hdScore = 1/pow(hdSum.value(voices.deepCopy.put(ins, candidate)), 2);
//maybe what you want here is a vector to another root and then favoring movement towards it.
//distScore = pow(hsChordalDistance.value(voices, voices.put(ins, candidate)), 2);
[stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore]
});
nWeights = passagesWeights;
//this handles nWeights of 0; mainly for testing
nProbs = nProbs.flop.select({arg scores, s; nWeights[s] != 0}).flop;
nWeights = nWeights.select({arg weight; weight != 0});
nProbs = nProbs.flop.collect({arg scores, s;
if(scores.sum == 0, {scores}, {scores.normalizeSum * nWeights[s]})
});
nProbs = nProbs.flop.collect({arg scores, s; scores.product}).normalizeSum;
sel = candidates.wchoose(nProbs);
voices[ins] = sel;
lastXChanges = lastXChanges.add(voices).keep(-5);
};
genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLast = false, isLastOrder = false;
var sus, prog, silent, flatOrder, res, isInChord, allowChord, pad, lastXChangesHold, voices, adder;
# sus, prog, silent = order;
flatOrder = silent ++ sus ++ prog;
lastXChangesHold = lastXChanges.deepCopy;
voices = lastState.deepCopy;
isInChord = popSize.collect({false});
allowChord = false;
pad = false;
res = [];
"------generating motif".postln;
//need to figure out here if voices move between motifs
flatOrder.do({arg ins, i;
if(prog.includes(ins) && repeatLast.not, {updateVoices.value(ins, sus)});
adder = if(silent.includes(ins), {["Rest"]}, {lastXChanges.last.deepCopy[ins]});
if(voices[ins] != adder, {
var dur;
if((sus ++ silent).includes(ins), {
allowChord = (ins != sus.last);
pad = (ins == sus.last);
}, {
if(i < (flatOrder.size - 1), {
allowChord = (isInChord[flatOrder[i + 1]] || (ins == flatOrder[i + 1])).not;
pad = false;
}, {
allowChord = false;
pad = true
});
});
if((orderIndex == 0) && sus.includes(ins), {
dur = entrancesDurFunc.value(allowChord, pad);
}, {
dur = passagesDurFunc.value(allowChord, pad);
});
if(dur == 0, {isInChord[ins] = true}, {isInChord = popSize.collect({false})});
voices[ins] = adder;
res = res.add([voices.deepCopy.postln, dur]);
});
});
// pad ending
if(orderIndex == (orders.size - 1), {
(0..(popSize-1)).scramble.do({arg ins;
if(res.last.first[ins] != ["Rest"], {
var dur;
voices[ins] = ["Rest"];
allowChord = (voices != popSize.collect({["Rest"]}));
pad = allowChord.not;
dur = exitsDurFunc.value(allowChord, pad);
res = res.add([voices.deepCopy.postln, dur]);
});
});
});
//format and return
if(startFromLast, {lastXChanges = lastXChangesHold});
res;
};
//------primary routines
genMotif = {
var repeats, fSeq;
repeats = 1;
fSeq = [];
repeats.do({arg index;
var motif;
motif = [];
orders.do({arg order, o;
var lastState, subMotif;
lastState = if(o == 0, {popSize.collect({["Rest"]})}, {motif.last.last.first});
subMotif = genSubMotif.value(order, o, lastState, isLastOrder: o == (orders.size - 1));
motif = motif.add(subMotif);
});
sanityCheck.value(motif, index);
fSeq = fSeq.add(motif);
});
fSeq
};
genSecondarySeq = {arg seq;
var curdles, fSeq;
curdles = [];
while({curdles.sum < seq.size}, {curdles = curdles ++ [3.rand + 1]});
fSeq = seq.clumps(curdles).collect({arg clump, m;
var repeats, paddedSeq;
//add rest
paddedSeq = clump.add([[[popSize.collect({["Rest"]}), 0.5.rand]]]);
//implement repeats
repeats = [0.rand + 1, 1].wchoose([1, 0].normalizeSum);
repeats.collect({paddedSeq});
});
fSeq
};
//------audition funcs
/*
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~addr.sendMsg(~indexPath, ~indexMsg);
~addr.sendMsg(~seqPath, stringifyToDepth.value(~seqMsg, 3));
//~addr.sendMsg("/STATE/OPEN", (dir.replace("supercollider", "resources") +/+ ~idMsg +/+ ~idMsg ++ "_gui_state" ++ ".state").standardizePath.postln);
};
});
*/
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~msg.postln;
~addr.sendMsg(~path, *~msg);
};
});
genPatterns = {arg inSeq, addr, oneShot = false;
var voices, durs, pbinds, res, indices, sectionDurs, msg, ids, seq;
seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
pbinds = voices.flop.collect({arg voice;
var clumps, hdScores, freqs, fDurs;
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\instrument, \test,
\group, group,
\freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1),
\sustain, Pseq(fDurs, 1)
)
});
if(oneShot.not, {
msg = inSeq.collect({arg mSeq, m; mSeq[1..]});
//ids = inSeq.collect({arg mSeq, m; mSeq[2]});
sectionDurs = seq.collect({arg mSeq; mSeq.flatten2(mSeq.maxDepth - 5).flop[1].sum});
pbinds = pbinds ++
[
Pbind(
\type, \osc,
\addr, addr,
\path, "/playing",
\msg, Pseq(msg, 1),
\dur, Pseq(sectionDurs, 1)
);
]
});
res = Ppar(pbinds);
res
};
/*
genMidiPatterns = {arg seq;
var voices, durs, patterns, res, mOut, pbRange;
pbRange = 1; //semitones - change this as needed for your situation
mOut = MIDIOut.newByName("TiMidity", "TiMidity port 0").latency_(Server.default.latency);
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
res = Ppar(
voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs;
mOut.program(v, 70);
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\type, \midi,
\chan, v,
\noteval, Pseq(freqs.cpsmidi - 24, 1),
\note, Pfunc({ | event | event[\noteval].floor }),
\dur, Pseq(fDurs, 1),
\midiout, mOut,
\amp, 1,
\bend, Pfunc({
| event |
if (event[\note].isRest.not) {
var pitchbendvalue = event[\noteval].frac.linlin(0, pbRange, 8192, 8192*2).asInteger;
m.bend(v, pitchbendvalue);
};
0; // return something other than nil to avoid stopping the pattern
}),
);
});
);
res
};
*/
//------resource management funcs
genUID = {Date.seed.asHexString.toLower};
seedFunc = {arg func, seed;
var funcArgs, next;
next = Routine({loop{func.valueArray(funcArgs).yield }});
next.randSeed_(seed);
{arg ...args; funcArgs = args; next.value}
};
stringifyToDepth = {arg data, maxDepth = 1;
var prettyString = "", rCount = 0, writeArray, indent;
if(maxDepth == 0, {
data.asCompileString
}, {
indent = {arg size; size.collect({" "}).join("")};
writeArray = {arg array;
prettyString = prettyString ++ indent.value(rCount) ++ "[\n";
rCount = rCount + 1;
if(rCount < maxDepth, {
array.do({arg subArray; writeArray.value(subArray)});
}, {
prettyString = prettyString ++ array.collect({arg subArray;
indent.value(rCount + 1) ++ subArray.asCompileString
}).join(",\n");
});
rCount = rCount - 1;
prettyString = prettyString ++ "\n" ++ indent.value(rCount) ++ "],\n";
};
writeArray.value(data);
prettyString.replace(",\n\n", "\n").drop(-2);
})
};
sanityCheck = {arg motif, index;
//print functions = very helpful
("----------" + index + "------------").postln;
motif.flatten.do({arg val, v;
if(v > 0, {
if(motif.flatten[v-1][0].hammingDistance(val[0]) > 1, {"problem 1".postln});
if(motif.flatten[v-1][0].hammingDistance(val[0]) == 0, {"problem 2".postln});
});
val.postln
});
"***********".postln;
};
msgInterpret = {arg in, escapeDoubleQuotes = true, escapeSingleQuotes = true;
var res;
res = in;
if(res.isNil.not, {
if((res.isArray && res.isString.not), {
res = res.asCompileString;
res = res.replace(" ", "").replace("\n", "").replace("\t", "");
if(escapeSingleQuotes, {res = res.replace("\'", "")});
if(escapeDoubleQuotes, {res = res.replace("\"", "")});
res = res.replace("Rest", "\"Rest\"");
res = res.interpret;
}, {
//res.postln;
if(res.every({arg char; char.isDecDigit}), {res = res.asInteger});
});
});
res
};
writeResources = {arg path, dict;
var file, modelItems, resString;
file = File(path,"w");
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
resString = nameSpaces.collect({arg nameSpace;
var depth = 0, insert = " ";
if(nameSpace == "music_data", {depth = 3; insert = "\n"});
if(nameSpace == "last_changes", {depth = 1; insert = "\n"});
if(nameSpace == "order", {depth = 1; insert = "\n"});
if((nameSpace == "ref_uid") && (dict[nameSpace] == nil), {dict[nameSpace] = "nil"});
"\"" ++ nameSpace ++ "\":" ++ insert ++ stringifyToDepth.value(dict[nameSpace], depth)
}).join(",\n");
resString = "{\n" ++ resString ++ "\n}";
file.write(resString);
file.close;
resString
};
loadModelFile = {arg path; loadModelJSON.value(File(path, "r").readAllString.parseJSON)};
loadModelJSON = {arg jsonObject;
var dict;
dict = Dictionary.with(*nameSpaces.collect({arg nS; nS->msgInterpret.value(jsonObject[nS])}));
dict
};
setGlobalVars = {arg dict;
// order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
dict
};
globalVarsToDict = {
var modelItems, dict;
// order really matters!!!!
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
dict = Dictionary.with(*nameSpaces.collect({arg nS, n; nS->modelItems[n]}));
};
loadLedgerFile = {arg path;
ledgerPath = path;
loadLedgerJSON.value(File(ledgerPath, "r").readAllString.parseJSON)
};
loadLedgerJSON = {arg jsonObject; ledger = jsonObject["ledger"]};
saveLedger = {arg ledger, path;
var file;
file = File(path, "w");
file.write("{\n\"ledger\":\n" ++ stringifyToDepth.value(ledger, 1) ++ "\n}");
file.close;
};
//------global vars
primes = [[2, 1], [3, 2], [5, 4], [7, 4], [11, 8], [13, 8]];
//ranges = [[-2400, 0], [-1200, 1200], [0, 2400], [0, 2400]];
exPath = thisProcess.nowExecutingPath;
dir = exPath.dirname;
//popSize = 4;
dims = primes.size;
tuples = genTuples.value();
//refUID = nil;
group = Group.new;
loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json");
//passagesWeights = [1, 1, 1, 1, 1];
//susWeights = [1, 1, 1];
// order really matters!!!!
nameSpaces = [
"music_data", "last_changes", "cur_uid", "ref_uid", "order_seed", "dur_seed", "motifs_seed",
"entrances_probs_vals","passages_probs_vals", "exits_probs_vals",
"ranges", "passages_weights", "order", "sus_weights", "order_size", "passages_size",
"motif_edited", "order_edited"
];
//------OSC funcs
OSCdef(\load_ledger, {arg msg, time, addr, port;
loadLedgerFile.value(msg[1].asString);
}, \load_ledger);
OSCdef(\load_model, {arg msg, time, addr, port;
var dict;
dict = loadModelFile.value(msg[1].asString);
setGlobalVars.value(dict);
}, \load_model);
OSCdef(\save_ledger, {arg msg, time, addr, port;
msg.postln;
ledger = msgInterpret.value(msg[1].asString.parseJSON["ledger"], false).postln;
//loadLedgerJSON.value(msg[0])
saveLedger.value(ledger, msg[2].asString);
//loadLedgerFile.value(msg[1].asString);
}, \save_ledger);
OSCdef(\generate, {arg msg, time, addr, port;
var path, dict, durSeeds, musPath, modelString;
msg.postln;
path = msg[1].asString;
dict = loadModelFile.value(path);
setGlobalVars.value(dict);
popSize = ranges.size;
//refUID.postln;
loadLedgerFile.value(ledgerPath);
if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, {
[initVoices.value().deepCopy];
}, {
var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
exitsDurFunc = genDurFunc.valueArray(exitsProbVals[..4] ++ [exitsProbVals[5..]] ++ [durSeeds[2]]);
if(orders == nil, {
orders = seedFunc.value(genOrders, orderSeed).valueArray(orderSize ++ passagesSize);
//addr.sendMsg("/order", stringifyToDepth.value(orders, 1));
});
seq = seedFunc.value(genMotif, motifSeed).value;
dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict);
//addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3));
addr.sendMsg("/generated", path, modelString);
}, \generate);
OSCdef(\commit, {arg msg, time, addr, port;
var musicData, musicChanged, dict, newLedger, modelPath, musString, musFile, test1, test2;
//msg.postln;
/*
test1 = msg[1].asString.parseJSON;
test2 = (dir +/+ ".." +/+ "resources/tmp/tmp_music" ++ ".json").standardizePath.parseJSONFile;
msgInterpret.value(test1["music"])[0][0][0][1].class.postln;
msgInterpret.value(test2["music_data"])[0][0][0][1].class.postln;
(test1["music"] == test2["music_data"]).postln;
*/
musicData = loadModelJSON.value(msg[1].asString.parseJSON)["music_data"].postln;
musicChanged = (musicData != seq).postln;
curUID = genUID.value;
File.mkdir((dir +/+ ".." +/+ "resources" +/+ curUID).standardizePath);
File.copy(exPath, (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_code" ++ ".scd").standardizePath);
modelPath = (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_mus_model" ++ ".json").standardizePath;
dict = globalVarsToDict.value;
if(musicChanged, {
seq = musicData;
dict["music_data"] = seq;
dict["motif_edited"] = "true"
});
dict["cur_uid"] = curUID;
writeResources.value(modelPath, dict);
File.delete(ledgerPath ++ "_bak");
File.copy(ledgerPath, ledgerPath ++ "_bak");
File.delete(ledgerPath);
ledger = ledger.drop(-1).add(curUID);
saveLedger.value(ledger, ledgerPath);
addr.sendMsg("/committed", curUID, ledgerPath);
//refUID = curUID;
}, \commit);
OSCdef(\transport, {arg msg, time, addr, port;
msg.postln;
if(msg[1] == 0, {
player.stop;
group.set(\gate, 0);
}, {
// the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
if(msg[1] == 1, {
pSeq = [];
cuedSeek = (seq != nil);
indexStart = msg[2].asInteger;
indexEnd = ledger.size - if(cuedSeek, {2}, {1});
//ledger.postln;
if(((indexStart == (ledger.size - 1)) && cuedSeek).not, {
ledger[indexStart..indexEnd].do({arg uid, index;
var path, file;
path = (dir +/+ ".." +/+ "resources" +/+ uid +/+ uid ++ "_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.postln.parseJSON["music_data"]), path, indexStart + index, uid]);
file.close;
});
});
if(cuedSeek, {
var path, file;
path = (dir +/+ ".." +/+ "resources/tmp/tmp_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.parseJSON["music_data"]), path, ledger.size - 1, "tmp"]);
file.close;
});
}, {
pSeq = [loadModelJSON.value(msg[2].asString.parseJSON)["music_data"].postln];
});
patterns = genPatterns.value(pSeq, addr);
player = Pfset(pattern: patterns, cleanupFunc: {
addr.sendMsg("/transport", 0);
});
player = player.play
});
}, \transport);
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms;
noHarms = 30;
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add;
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms, freqFinal, start, end;
noHarms = 30;
freq = WhiteNoise.ar * 3 + freq;
freqFinal = Duty.ar((1/freq), 0, freq);
trig = Changed.ar(freqFinal);
start = Demand.ar(trig, 0, Dwhite(-1, -0.75));
end = Demand.ar(trig, 0, Dwhite(0.75, 1));
exc = Phasor.ar(trig, (end - start) * freqFinal / SampleRate.ir, start, end, 0) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(2, 3)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
}).add;
)
"{\"a\": 1}".parseYAML["a"].asInteger;
"{\"a\": 1}".parseJSON["a"].isNumber;
1223423434123.asHexString.toLower
Date.getDate.rawSeconds
Date.seed.asHexString.toLower
n = NetAddr("localhost", 8080);
n.sendMsg("/GET/#", (NetAddr.localAddr.hostname ++ ":" ++ NetAddr.localAddr.port), "/passage_probs_vals");

@ -1,55 +0,0 @@
{
"music_data":
[
[
[
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 7.125 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 1, 0, 0, 0 ], [ "Rest" ] ], 0.25 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 1, -1, 0, 0, 0, 0 ], [ "Rest" ] ], 0.375 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 1, 0, 0, 0, 0 ], [ "Rest" ] ], 0.125 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ "Rest" ] ], 7.25 ]
],
[
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ "Rest" ] ], 0.125 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 5 ],
[ [ [ "Rest" ], [ 0, 0, 0, -1, 0, 1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 0.25 ],
[ [ [ "Rest" ], [ -1, 0, 1, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 0 ],
[ [ [ "Rest" ], [ 1, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 0.125 ],
[ [ [ "Rest" ], [ 1, -1, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 0.5 ],
[ [ [ "Rest" ], [ 1, 0, 0, 0, 0, -1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 10.25 ],
[ [ [ "Rest" ], [ 1, 0, 0, 0, 0, -1 ], [ 0, 0, 0, 0, 0, 1 ], [ "Rest" ] ], 0 ],
[ [ [ "Rest" ], [ "Rest" ], [ 0, 0, 0, 0, 0, 1 ], [ "Rest" ] ], 0 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 6.125 ]
]
]
],
"last_changes":
[
[ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, -1, 0, 1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ -1, 0, 1, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, -1, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, 0, -1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ]
],
"cur_uid": "64085471",
"ref_uid": "nil",
"order_seed": 815237,
"dur_seed": 146432,
"motifs_seed": 680955,
"entrances_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.26424870466321, 0.75675675675676, 0.5, 0.5, 0.58549222797927, 0.72635135135135, 1, 0.5 ],
"passages_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ -384, 2400 ], [ -507, 2400 ], [ -282, 2237 ], [ -1200, 2053 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ],
"order":
[
[ [ 1, 0 ], [ 2, 2, 2, 2 ], [ 3 ] ],
[ [ 2, 3 ], [ 1, 1, 1, 1, 1 ], [ 0 ] ]
],
"sus_weights": [ 0.75, 0.69, 0.75 ],
"order_size": [ 2, 6 ],
"passages_size": [ 0, 10 ],
"motif_edited": "false",
"order_edited": "false"
}

@ -283,7 +283,7 @@ genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLa
}); });
//format and return //format and return
if(startFromLast, {lastXChanges = lastXChangesHold}); if(startFromLast, {lastXChanges = lastXChangesHold.deepCopy});
res; res;
}; };
@ -359,20 +359,41 @@ genPatterns = {arg inSeq, addr, oneShot = false;
seq = inSeq.collect({arg mSeq; mSeq[0]}); seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop; # voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
pbinds = voices.flop.collect({arg voice, v; pbinds = voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs; var clumps, hdScores, freqs, fDurs, attacks, rels, amps;
clumps = voice.separate({arg a, b; a != b }); clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})}); freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum}); fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
//attacks = 2.collect({rrand(1, 3)}) ++ freqs.drop(2).collect({rrand(0.3, 0.5)});
attacks = fDurs.collect({arg dur; dur * rrand(0.2, 0.4)});
//rels = freqs.drop(2).collect({rrand(0.3, 0.5)}) ++ 2.collect({rrand(1, 3)});
rels = (clumps.size - 1).collect({arg c;
if(clumps[c + 1][0] == ["Rest"], {rrand(1, 3)}, {rrand(0.3, 0.5)});
});
amps = freqs.collect({rrand(0.6, 0.99)});
[
Pbind( Pbind(
\instrument, \string_model, \instrument, \string_model,
\group, group, \group, group,
\freq, Pseq(freqs, 1), \freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1), \dur, Pseq(fDurs, 1),
\attack, Pseq(attacks, 1),
\sustain, Pseq(fDurs, 1),
\release, Pseq(rels, 1),
//\amp, Pseq(amps, 1),
\amp, Pbrown(0.5, 1, 0.5),
\busIndex, v
),
Pbind(
\instrument, \sine,
\group, group,
\freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1),
\sustain, Pseq(fDurs, 1), \sustain, Pseq(fDurs, 1),
\busIndex, v \busIndex, v
) )
}); ]
}).flatten;
if(oneShot.not, { if(oneShot.not, {
msg = inSeq.collect({arg mSeq, m; mSeq[1..]}); msg = inSeq.collect({arg mSeq, m; mSeq[1..]});
//ids = inSeq.collect({arg mSeq, m; mSeq[2]}); //ids = inSeq.collect({arg mSeq, m; mSeq[2]});
@ -539,12 +560,15 @@ loadModelJSON = {arg jsonObject;
dict dict
}; };
setGlobalVars = {arg dict; setGlobalVars = {arg dict, skipLastXChanges = false;
var tmpLastXChanges;
tmpLastXChanges = lastXChanges.deepCopy;
// order really matters!!!! // order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed, # seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals, entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize, ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]}); motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
if(skipLastXChanges, {lastXChanges = tmpLastXChanges});
dict dict
}; };
@ -586,6 +610,7 @@ dims = primes.size;
tuples = genTuples.value(); tuples = genTuples.value();
//refUID = nil; //refUID = nil;
group = Group.new; group = Group.new;
~group = group;
loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json"); loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json");
//passagesWeights = [1, 1, 1, 1, 1]; //passagesWeights = [1, 1, 1, 1, 1];
//susWeights = [1, 1, 1]; //susWeights = [1, 1, 1];
@ -625,7 +650,7 @@ OSCdef(\generate, {arg msg, time, addr, port;
path = msg[1].asString; path = msg[1].asString;
dict = loadModelFile.value(path); dict = loadModelFile.value(path);
setGlobalVars.value(dict); setGlobalVars.value(dict, true);
popSize = ranges.size; popSize = ranges.size;
@ -635,14 +660,16 @@ OSCdef(\generate, {arg msg, time, addr, port;
if(ledger == nil, {ledger = ["tmp"]}); if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")}); if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, { if(refUID == nil, {lastXChanges = [initVoices.value().deepCopy]});
[initVoices.value().deepCopy]; if((refUID != nil) && (refUID != "tmp"), {
}, {
var file; var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r"); file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]); lastXChanges = msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
}); });
refUID.postln;
lastXChanges.collect({arg item; item.postln});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln; durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]); entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]); passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
@ -654,11 +681,13 @@ OSCdef(\generate, {arg msg, time, addr, port;
}); });
seq = seedFunc.value(genMotif, motifSeed).value; seq = seedFunc.value(genMotif, motifSeed).value;
lastXChanges.collect({arg item; item.postln});
dict = globalVarsToDict.value; dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict); modelString = writeResources.value(path, dict);
//addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3)); //addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3));
addr.sendMsg("/generated", path, modelString); addr.sendMsg("/generated", path, modelString, ledgerPath);
}, \generate); }, \generate);
@ -708,8 +737,9 @@ OSCdef(\commit, {arg msg, time, addr, port;
OSCdef(\transport, {arg msg, time, addr, port; OSCdef(\transport, {arg msg, time, addr, port;
msg.postln; msg.postln;
if(msg[1] == 0, { if(msg[1] == 0, {
player.stop; group.set(\release, 2);
group.set(\gate, 0); group.set(\gate, 0);
player.stop;
}, { }, {
// the cued sequence can now be read from file, so this can be cleaned up // the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger; var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
@ -751,28 +781,110 @@ OSCdef(\transport, {arg msg, time, addr, port;
) )
( (
~busArray = 4.collect({Bus.audio(s, 1).index}); //synthdefs
~busArray.postln; ~stringModelBusArray = 4.collect({Bus.audio(s, 1)});
SynthDef(\string_model, {arg freq, gate = 1, sustain, amp, dur, busIndex = 0; ~sineBusArray = 4.collect({Bus.audio(s, 1)});
~bassBusArray = 1.collect({Bus.audio(s, 1)});
~hdustBusArray = 1.collect({Bus.audio(s, 1)});
~samplerBusArray = 2.collect({Bus.audio(s, 1)});
~sBuf = Buffer.alloc(s, 10, 2);
SynthDef(\string_model, {arg freq, gate = 1, sustain, amp, dur, attack, release = 1, busIndex = 0;
var trig, exc, sig1, sig2, noHarms; var trig, exc, sig1, sig2, noHarms;
noHarms = 30; noHarms = rrand(20, 40);
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01); exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq), sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}), Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.5).softclip; Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.8).softclip;
sig1 = HPF.ar(sig1, 300); //sig1 = HPF.ar(sig1, 300);
Out.ar(Select.kr(busIndex, ~busArray).poll, sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2)); Out.ar(Select.kr(busIndex, ~stringModelBusArray), sig1 * amp * EnvGen.kr(Env.adsr(attack, 0.3, 0.9, release, 0.9, -3), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2)); //Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add; }).add;
SynthDef(\sine, {arg freq, gate = 1, sustain, amp, dur, busIndex = 0;
var sig;
sig = SinOsc.ar(freq);
Out.ar(Select.kr(busIndex, ~sineBusArray), sig * EnvGen.kr(Env.asr(0.3, 0.4, 0.3), gate, timeScale: dur, doneAction: 2));
//Out.ar(Select.kr(busIndex, ~sineBusArray), sig * EnvGen.kr(Env.sine(dur), gate, doneAction: 2));
}).add;
SynthDef(\mixer, {arg freq, gate = 1, sustain, amp, dur, out;
var nameSpaces, sigs, hierarchicalDust;
hierarchicalDust = (
TIRand.kr(0, 1, Impulse.kr(100)) *
TIRand.kr(0, 1, Impulse.kr(10)) *
TIRand.kr(0, 1, Impulse.kr(1))
);
sigs = [~stringModelBusArray, ~sineBusArray, ~bassBusArray, ~hdustBusArray, ~samplerBusArray].collect({arg busArray, i;
var nameSpace, sig;
nameSpace = ['string', 'sine', 'bass', 'hdust', 'sampler'][i];
sig = busArray.collect({arg bus, c; In.ar(bus, 1) * NamedControl.kr(\ ++ nameSpace ++ '_volume_' ++ c, 1, 0.1)});
sig = sig.collect({arg channel, c; Pan2.ar(channel, NamedControl.kr(\ ++ nameSpace ++ '_pan_' ++ c, i / (busArray.size - 1), 0.1) * 2 - 1)});
sig = sig.collect({arg channel, c; channel * NamedControl.kr(\ ++ nameSpace ++ '_mute_' ++ c, 1, 0.1)});
sig = Mix.ar(sig) * pow(NamedControl.kr(\ ++ nameSpace ++ '_volume_master', 1, 0.1), 2);
});
sigs = Mix.ar(sigs / 4);
Out.ar(0, sigs)
}).add;
SynthDef(\bass, {
var switches, drone;
switches = {|i| Dust.kr(0.1)} ! 9;
drone = {|i| var harm = pow(2, 2 - (i / 3).trunc), amp = (1 / pow(harm, 2));
SinOsc.ar(60 * harm + TRand.kr(-3, 3, switches[i]), 0, amp)} ! 9;
Out.ar(~bassBusArray[0], Mix.new(drone) * 0.2);
}).add;
SynthDef(\sampler, {
Out.ar(~samplerBusArray, PlayBuf.ar(2, ~sBuf, BufRateScale.kr(~sBuf), doneAction: 2))
}).add;
// main routine
SynthDef(\hdust, {
arg gate = 0;
var hierarchical_dust, low_sine, high_sine, brown_noise, white_noise;
// this triggers the combinations of sources
// it is similar to the Supercollider UGen called dust but with a hierarchical structure
hierarchical_dust = (
TIRand.kr(0, 1, Impulse.kr(100)) *
TIRand.kr(0, 1, Impulse.kr(10)) *
TIRand.kr(0, 1, Impulse.kr(1)) *
TIRand.kr(0, 1, Impulse.kr(0.1))
);
// adjust the multiplier at the end of each line for adjusting levels
// note with each trigger, each source has a 1 in 3 chance of sounding
low_sine = SinOsc.ar(76.midicps / 16) * (TIRand.kr(0, 2, hierarchical_dust) < 1) * 0.1;
high_sine = SinOsc.ar(76.midicps * 8) * (TIRand.kr(0, 2, hierarchical_dust) < 1) * 0.01;
brown_noise = BrownNoise.ar() * (TIRand.kr(0, 2, hierarchical_dust) < 1) * 0.025;
white_noise = WhiteNoise.ar() * (TIRand.kr(0, 2, hierarchical_dust) < 1) * 0.02;
Out.ar(~hdustBusArray[0],
((low_sine + high_sine + brown_noise + white_noise) )
);
}).add;
) )
( (
SynthDef(\mixer, {arg freq, gate = 1, sustain, amp, dur, out; var bass, hdust, sampler, mixer;
var input; bass = Synth.tail(~group, \bass);
input = ~busArray.collect({arg busIndex; In.ar(busIndex, 1)}); hdust = Synth.tail(~group, \hdust);
Out.ar(0, Mix.ar(input)) sampler = Synth.head(~group, \sampler);
}).play mixer = Synth.tail(~group, \mixer);
OSCdef(\mixer, {arg msg, time, addr, port;
mixer.set((msg[1] ++ '_' ++ msg[2] ++ '_' ++ msg[3]), msg[4])
}, \mixer);
OSCdef(\sampler, {arg msg, time, addr, port;
msg.postln;
sampler.free;
~sBuf.free;
~sBuf = Buffer.read(s, msg[1].asString.postln, action: {sampler = Synth.head(~group, \sampler)});
}, \sampler);
) )
/* old something
( (
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur; SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms, freqFinal, start, end; var trig, exc, sig1, sig2, noHarms, freqFinal, start, end;
@ -791,16 +903,5 @@ SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2)); Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
}).add; }).add;
) )
*/
"{\"a\": 1}".parseYAML["a"].asInteger;
"{\"a\": 1}".parseJSON["a"].isNumber;
1223423434123.asHexString.toLower
Date.getDate.rawSeconds
Date.seed.asHexString.toLower
n = NetAddr("localhost", 8080);
n.sendMsg("/GET/#", (NetAddr.localAddr.hostname ++ ":" ++ NetAddr.localAddr.port), "/passage_probs_vals");

@ -0,0 +1,49 @@
{
"music_data":
[
[
[
[ [ [ "Rest" ], [ -2, 3, -2, 1, 1, 1 ], [ "Rest" ], [ "Rest" ] ], 0.125 ],
[ [ [ -5, 3, -2, 2, 1, 1 ], [ -2, 3, -2, 1, 1, 1 ], [ "Rest" ], [ "Rest" ] ], 0.5 ],
[ [ [ -5, 3, -2, 2, 1, 1 ], [ -2, 3, -2, 1, 1, 1 ], [ "Rest" ], [ -4, 5, -2, 2, 2, -1 ] ], 0.625 ],
[ [ [ -5, 3, -2, 2, 1, 1 ], [ -2, 3, -2, 1, 1, 1 ], [ -2, 2, -2, 1, 1, 1 ], [ -4, 5, -2, 2, 2, -1 ] ], 5.625 ]
],
[
[ [ [ -5, 3, -2, 2, 1, 1 ], [ -2, 3, -2, 1, 1, 1 ], [ -3, 4, -2, 2, 2, -1 ], [ -4, 5, -2, 2, 2, -1 ] ], 1.125 ],
[ [ [ -5, 3, -2, 2, 1, 1 ], [ -3, 3, -1, 2, 1, 1 ], [ -3, 4, -2, 2, 2, -1 ], [ -4, 5, -2, 2, 2, -1 ] ], 2.5 ],
[ [ [ -5, 3, -2, 2, 1, 1 ], [ -3, 3, -1, 2, 1, 1 ], [ -3, 4, -2, 2, 2, -1 ], [ "Rest" ] ], 1.375 ],
[ [ [ "Rest" ], [ -3, 3, -1, 2, 1, 1 ], [ -3, 4, -2, 2, 2, -1 ], [ "Rest" ] ], 0.75 ],
[ [ [ "Rest" ], [ "Rest" ], [ -3, 4, -2, 2, 2, -1 ], [ "Rest" ] ], 0 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 1.125 ]
]
]
],
"last_changes":
[
[ [ -5, 3, -2, 2, 1, 1 ], [ -4, 5, -2, 3, 2, -1 ], [ -4, 3, -2, 3, 1, 1 ], [ -4, 5, -2, 2, 2, -1 ] ],
[ [ -5, 3, -2, 2, 1, 1 ], [ -2, 3, -2, 1, 1, 1 ], [ -4, 3, -2, 3, 1, 1 ], [ -4, 5, -2, 2, 2, -1 ] ],
[ [ -5, 3, -2, 2, 1, 1 ], [ -2, 3, -2, 1, 1, 1 ], [ -2, 2, -2, 1, 1, 1 ], [ -4, 5, -2, 2, 2, -1 ] ],
[ [ -5, 3, -2, 2, 1, 1 ], [ -2, 3, -2, 1, 1, 1 ], [ -3, 4, -2, 2, 2, -1 ], [ -4, 5, -2, 2, 2, -1 ] ],
[ [ -5, 3, -2, 2, 1, 1 ], [ -3, 3, -1, 2, 1, 1 ], [ -3, 4, -2, 2, 2, -1 ], [ -4, 5, -2, 2, 2, -1 ] ]
],
"cur_uid": "6409252e",
"ref_uid": "tmp",
"order_seed": 825836,
"dur_seed": 453411,
"motifs_seed": 115471,
"entrances_probs_vals": [ 0.29, 0, 1.3492063492064, 0, 0.65934065934066, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"passages_probs_vals": [ 0.29, 0, 5, 0.58, 1.7582417582418, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0.29, 0, 5, 0.58, 1.7582417582418, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ -3600, -349 ], [ 799, 1758 ], [ -282, 1013 ], [ -282, 799 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ],
"order":
[
[ [ 1, 0, 3 ], [ 2 ], [ ] ],
[ [ 3, 0 ], [ 2, 1 ], [ ] ]
],
"sus_weights": [ 0.39, 0.32, 0.77 ],
"order_size": [ 1, 3 ],
"passages_size": [ 0, 0 ],
"motif_edited": "false",
"order_edited": "false"
}

@ -1,825 +0,0 @@
(
// helper funcs
var hsArrayToCents, pDist, hdSum, hsChordalDistance, hsArrayToFreq;
// score funcs
var isInRange, spacingScore, rangeScore, intervalScore, inclusionScore;
// subroutines
var genTuples, initVoices, genOrders, genSubMotif, updateVoices, genDurFunc;
// primary routines
var genMotif, genSecondarySeq;
// audition funcs
var genPatterns, genMidiPatterns;
// resource management funcs
var seedFunc, genUID, writeResources, stringifyToDepth, setSeeds, sanityCheck,
msgInterpret, loadLedgerFile, loadLedgerJSON, loadModelFile, loadModelJSON,
setGlobalVars, globalVarsToDict, saveLedger;
// model vars
//(model and global vars mostly set by OSC funcs
var seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited;
// model aux vars
var entrancesDurFunc, passagesDurFunc, exitsDurFunc;
// other global vars
var popSize, exPath, dir, primes, dims, tuples,
group, player, ledgerPath, ledger, currentlyPlayingUID,
nameSpaces;
// install JSON quark
if(Quarks.isInstalled("JSONlib").not, {
Quarks.install("https://github.com/musikinformatik/JSONlib.git");
thisProcess.recompile;
//HelpBrowser.openHelpFor("Classes/JSONlib");
});
//------helper funcs
hsArrayToCents = {
arg hsArray;
hsArray.collect({arg dist, p; dist * 1200 * log2(primes[p][0]/primes[p][1])}).sum
};
pDist = {
arg array1, array2, signed = false;
var pDistance;
pDistance = hsArrayToCents.value(array1) - hsArrayToCents.value(array2);
if(signed, {pDistance}, {abs(pDistance)})
};
hdSum = {
arg hsArrays;
var size, distances, mean;
size = hsArrays.size;
distances = (size - 1).collect({arg i;
((i + 1)..(size - 1)).collect({arg j;
abs(hsArrays[i] - hsArrays[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsChordalDistance = {
arg hsArrays1, hsArrays2;
var size, distances, mean;
size = hsArrays1.size;
distances = hsArrays1.size.collect({arg i;
hsArrays2.size.collect({arg j;
abs(hsArrays1[i] - hsArrays2[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsArrayToFreq = {
arg array;
array.collect({arg dim, d; pow(primes[d][0]/primes[d][1], dim)}).product
};
//------score funcs
/*
isInRange = {
arg hsArray, min, max;
var cents;
cents = hsArrayToCents.value(hsArray);
(cents >= min) && (cents <= max)
};
*/
spacingScore = {
arg hsArrays, min;
var centsArray;
centsArray = hsArrays.collect({arg hsArray; hsArrayToCents.value(hsArray)}).sort({arg a, b; a < b});
centsArray.differentiate.drop(1).collect({arg pDistance; if(pDistance >= min, {1}, {0.01})}).sum;
};
rangeScore = {
arg hsArray1, hsArray2, min, max, low, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
if((pDistance >= min) && (pDistance <= max), {1}, {low});
};
intervalScore = {
arg hsArray1, hsArray2, mean, sd, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
pDistance.gaussCurve(1, mean, sd)
};
inclusionScore = {
arg array, test, min = 0.01;
if(array.collect({arg v; v.hash}).includes(test.hash), {min}, {1});
};
//------subroutines
genTuples = {
var tuples;
tuples = dims.collect({[-1, 0, 1]}).allTuples.select({arg tuple; (abs(tuple.drop(1)).sum <= 1) && (tuple[0] == 0)});
tuples = tuples ++ tuples.collect({arg tuple; [-3, -2, -1, 1, 2, 3].collect({arg octTrans; tuple.deepCopy.put(0, octTrans)})}).flatten;
};
initVoices = {
var init, voicesInit;
voicesInit = popSize.collect({dims.collect({0})});
/*
voicesInit = [dims.collect({0})];
(popSize - 1).do({
arg rep, new;
rep = dims.rand;
new = voicesInit.last.deepCopy;
new[rep] = new[rep] + [-1, 1].choose();
voicesInit = voicesInit.add(new);
});
*/
voicesInit.deepCopy;
};
genDurFunc = {arg chordProb, minPad, maxPad, minDur, maxDur, envData, seed;
var env, pTable, durFunc;
env = Env.pairs([[0, 0]] ++ envData.clump(2) ++ [[1, 0]]).asSignal(256).asList.asArray;
pTable = env.asRandomTable;
[chordProb, minPad, maxPad, minDur, maxDur, envData].postln;
durFunc = {arg allowChord, pad = false;
var res;
res = if(allowChord.not, {
pTable.tableRand * (maxDur - minDur) + minDur
}, {
if(1.0.rand < chordProb, {0}, {pTable.tableRand * (maxDur - minDur) + minDur});
}).round(0.125);
if(pad, {res = res + rrand(minPad.asFloat, maxPad.asFloat).round(0.125)});
if(res.asInteger == res, {res = res.asInteger});
res
};
seedFunc.value(durFunc, seed);
};
genOrders = {arg minMotifLength = 1, maxMotifLength = 5, minProgLength = 0, maxProgLength = 5;
((maxMotifLength - minMotifLength).rand + minMotifLength).collect({
var noProgIns, noSusIns, noSilentIns, prog, sus, silent, order;
noSusIns = [1, 2, 3].wchoose(susWeights.normalizeSum);
noProgIns = (popSize - noSusIns).rand + 1;
noSilentIns = popSize - noSusIns - noProgIns;
# prog, sus, silent = (0..(popSize-1)).scramble.clumps([noProgIns, noSusIns, noSilentIns]);
prog = (prog.scramble ++ ((maxProgLength - minProgLength).rand + minProgLength).collect({prog.choose}).scramble);
if(silent == nil, {silent = []});
[sus.scramble, prog, silent.scramble]
});
};
updateVoices = {arg ins, sus;
var voices, candidates, nWeights, nProbs, sel;
voices = lastXChanges.deepCopy.last;
candidates = sus.collect({arg v; tuples.collect({arg t; voices[v] + t})}).flatten;
candidates = difference(candidates.asSet, voices.asSet).asList;
nProbs = candidates.collect({arg candidate;
var stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore;
//stepScore = intervalScore.value(voices[ins], candidate, 30, 400, 0.1);
stepScore = intervalScore.value(voices[ins], candidate, 100, 100);
recentlySoundedScore = inclusionScore.value(lastXChanges.flop[ins], candidate, 0);
isInRangeScore = rangeScore.value(candidate, candidate.collect({0}), ranges[ins][0], ranges[ins][1], 0, true);
regScore = spacingScore.value(voices.deepCopy.put(ins, candidate), 300);
hdScore = 1/pow(hdSum.value(voices.deepCopy.put(ins, candidate)), 2);
//maybe what you want here is a vector to another root and then favoring movement towards it.
//distScore = pow(hsChordalDistance.value(voices, voices.put(ins, candidate)), 2);
[stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore]
});
nWeights = passagesWeights;
//this handles nWeights of 0; mainly for testing
nProbs = nProbs.flop.select({arg scores, s; nWeights[s] != 0}).flop;
nWeights = nWeights.select({arg weight; weight != 0});
nProbs = nProbs.flop.collect({arg scores, s;
if(scores.sum == 0, {scores}, {scores.normalizeSum * nWeights[s]})
});
nProbs = nProbs.flop.collect({arg scores, s; scores.product}).normalizeSum;
sel = candidates.wchoose(nProbs);
voices[ins] = sel;
lastXChanges = lastXChanges.add(voices).keep(-5);
};
genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLast = false, isLastOrder = false;
var sus, prog, silent, flatOrder, res, isInChord, allowChord, pad, lastXChangesHold, voices, adder;
# sus, prog, silent = order;
flatOrder = silent ++ sus ++ prog;
lastXChangesHold = lastXChanges.deepCopy;
voices = lastState.deepCopy;
isInChord = popSize.collect({false});
allowChord = false;
pad = false;
res = [];
"------generating motif".postln;
//need to figure out here if voices move between motifs
flatOrder.do({arg ins, i;
if(prog.includes(ins) && repeatLast.not, {updateVoices.value(ins, sus)});
adder = if(silent.includes(ins), {["Rest"]}, {lastXChanges.last.deepCopy[ins]});
if(voices[ins] != adder, {
var dur;
if((sus ++ silent).includes(ins), {
allowChord = (ins != sus.last);
pad = (ins == sus.last);
}, {
if(i < (flatOrder.size - 1), {
allowChord = (isInChord[flatOrder[i + 1]] || (ins == flatOrder[i + 1])).not;
pad = false;
}, {
allowChord = false;
pad = true
});
});
if((orderIndex == 0) && sus.includes(ins), {
dur = entrancesDurFunc.value(allowChord, pad);
}, {
dur = passagesDurFunc.value(allowChord, pad);
});
if(dur == 0, {isInChord[ins] = true}, {isInChord = popSize.collect({false})});
voices[ins] = adder;
res = res.add([voices.deepCopy.postln, dur]);
});
});
// pad ending
if(orderIndex == (orders.size - 1), {
(0..(popSize-1)).scramble.do({arg ins;
if(res.last.first[ins] != ["Rest"], {
var dur;
voices[ins] = ["Rest"];
allowChord = (voices != popSize.collect({["Rest"]}));
pad = allowChord.not;
dur = exitsDurFunc.value(allowChord, pad);
res = res.add([voices.deepCopy.postln, dur]);
});
});
});
//format and return
if(startFromLast, {lastXChanges = lastXChangesHold});
res;
};
//------primary routines
genMotif = {
var repeats, fSeq;
repeats = 1;
fSeq = [];
repeats.do({arg index;
var motif;
motif = [];
orders.do({arg order, o;
var lastState, subMotif;
lastState = if(o == 0, {popSize.collect({["Rest"]})}, {motif.last.last.first});
subMotif = genSubMotif.value(order, o, lastState, isLastOrder: o == (orders.size - 1));
motif = motif.add(subMotif);
});
sanityCheck.value(motif, index);
fSeq = fSeq.add(motif);
});
fSeq
};
genSecondarySeq = {arg seq;
var curdles, fSeq;
curdles = [];
while({curdles.sum < seq.size}, {curdles = curdles ++ [3.rand + 1]});
fSeq = seq.clumps(curdles).collect({arg clump, m;
var repeats, paddedSeq;
//add rest
paddedSeq = clump.add([[[popSize.collect({["Rest"]}), 0.5.rand]]]);
//implement repeats
repeats = [0.rand + 1, 1].wchoose([1, 0].normalizeSum);
repeats.collect({paddedSeq});
});
fSeq
};
//------audition funcs
/*
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~addr.sendMsg(~indexPath, ~indexMsg);
~addr.sendMsg(~seqPath, stringifyToDepth.value(~seqMsg, 3));
//~addr.sendMsg("/STATE/OPEN", (dir.replace("supercollider", "resources") +/+ ~idMsg +/+ ~idMsg ++ "_gui_state" ++ ".state").standardizePath.postln);
};
});
*/
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~msg.postln;
~addr.sendMsg(~path, *~msg);
};
});
genPatterns = {arg inSeq, addr;
var voices, durs, patterns, res, indices, sectionDurs, msg, ids, seq;
seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
msg = inSeq.collect({arg mSeq, m; mSeq[1..]});
//ids = inSeq.collect({arg mSeq, m; mSeq[2]});
sectionDurs = seq.collect({arg mSeq; mSeq.flatten2(mSeq.maxDepth - 5).flop[1].sum});
res = Ppar(
voices.flop.collect({arg voice;
var clumps, hdScores, freqs, fDurs;
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\instrument, \test,
\group, group,
\freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1),
\sustain, Pseq(fDurs, 1)
)
}) ++
[
Pbind(
\type, \osc,
\addr, addr,
//\indexPath, "/cur_play_index",
//\indexMsg, Pseq(indices, 1),
//\seqPath, "/mus_seq",
//\seqMsg, Pseq(seq, 1),
\path, "/playing",
\msg, Pseq(msg, 1),
\dur, Pseq(sectionDurs, 1)
);
]
);
res
};
/*
genMidiPatterns = {arg seq;
var voices, durs, patterns, res, mOut, pbRange;
pbRange = 1; //semitones - change this as needed for your situation
mOut = MIDIOut.newByName("TiMidity", "TiMidity port 0").latency_(Server.default.latency);
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
res = Ppar(
voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs;
mOut.program(v, 70);
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\type, \midi,
\chan, v,
\noteval, Pseq(freqs.cpsmidi - 24, 1),
\note, Pfunc({ | event | event[\noteval].floor }),
\dur, Pseq(fDurs, 1),
\midiout, mOut,
\amp, 1,
\bend, Pfunc({
| event |
if (event[\note].isRest.not) {
var pitchbendvalue = event[\noteval].frac.linlin(0, pbRange, 8192, 8192*2).asInteger;
m.bend(v, pitchbendvalue);
};
0; // return something other than nil to avoid stopping the pattern
}),
);
});
);
res
};
*/
//------resource management funcs
genUID = {Date.seed.asHexString.toLower};
seedFunc = {arg func, seed;
var funcArgs, next;
next = Routine({loop{func.valueArray(funcArgs).yield }});
next.randSeed_(seed);
{arg ...args; funcArgs = args; next.value}
};
stringifyToDepth = {arg data, maxDepth = 1;
var prettyString = "", rCount = 0, writeArray, indent;
if(maxDepth == 0, {
data.asCompileString
}, {
indent = {arg size; size.collect({" "}).join("")};
writeArray = {arg array;
prettyString = prettyString ++ indent.value(rCount) ++ "[\n";
rCount = rCount + 1;
if(rCount < maxDepth, {
array.do({arg subArray; writeArray.value(subArray)});
}, {
prettyString = prettyString ++ array.collect({arg subArray;
indent.value(rCount + 1) ++ subArray.asCompileString
}).join(",\n");
});
rCount = rCount - 1;
prettyString = prettyString ++ "\n" ++ indent.value(rCount) ++ "],\n";
};
writeArray.value(data);
prettyString.replace(",\n\n", "\n").drop(-2);
})
};
sanityCheck = {arg motif, index;
//print functions = very helpful
("----------" + index + "------------").postln;
motif.flatten.do({arg val, v;
if(v > 0, {
if(motif.flatten[v-1][0].hammingDistance(val[0]) > 1, {"problem 1".postln});
if(motif.flatten[v-1][0].hammingDistance(val[0]) == 0, {"problem 2".postln});
});
val.postln
});
"***********".postln;
};
msgInterpret = {arg in, escapeDoubleQuotes = true, escapeSingleQuotes = true;
var res;
res = in;
if(res.isNil.not, {
if((res.isArray && res.isString.not), {
res = res.asCompileString;
res = res.replace(" ", "").replace("\n", "").replace("\t", "");
if(escapeSingleQuotes, {res = res.replace("\'", "")});
if(escapeDoubleQuotes, {res = res.replace("\"", "")});
res = res.replace("Rest", "\"Rest\"");
res = res.interpret;
}, {
//res.postln;
if(res.every({arg char; char.isDecDigit}), {res = res.asInteger});
});
});
res
};
/*
writeResources = {arg path;
var file, modelItems, resString;
file = File(path,"w");
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
resString = [nameSpaces, modelItems].flop.collect({arg item;
var nameSpace, modelItem, depth = 0, insert = " ";
# nameSpace, modelItem = item;
if(nameSpace == "music_data", {depth = 3; insert = "\n"});
if(nameSpace == "last_changes", {depth = 1; insert = "\n"});
if(nameSpace == "order", {depth = 1; insert = "\n"});
if((nameSpace == "ref_uid") && (modelItem == nil), {modelItem = "nil"});
"\"" ++ nameSpace ++ "\":" ++ insert ++ stringifyToDepth.value(modelItem, depth)
}).join(",\n");
resString = "{\n" ++ resString ++ "\n}";
file.write(resString);
file.close;
resString
};
*/
writeResources = {arg path, dict;
var file, modelItems, resString;
file = File(path,"w");
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
resString = nameSpaces.collect({arg nameSpace;
var depth = 0, insert = " ";
if(nameSpace == "music_data", {depth = 3; insert = "\n"});
if(nameSpace == "last_changes", {depth = 1; insert = "\n"});
if(nameSpace == "order", {depth = 1; insert = "\n"});
if((nameSpace == "ref_uid") && (dict[nameSpace] == nil), {dict[nameSpace] = "nil"});
"\"" ++ nameSpace ++ "\":" ++ insert ++ stringifyToDepth.value(dict[nameSpace], depth)
}).join(",\n");
resString = "{\n" ++ resString ++ "\n}";
file.write(resString);
file.close;
resString
};
loadModelFile = {arg path; loadModelJSON.value(File(path, "r").readAllString.parseJSON)};
loadModelJSON = {arg jsonObject;
var dict;
//model = File(path, "r").readAllString.parseJSON;
dict = Dictionary.with(*nameSpaces.collect({arg nS; nS->msgInterpret.value(jsonObject[nS])}));
dict
};
setGlobalVars = {arg dict;
// order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
dict
};
globalVarsToDict = {
var modelItems, dict;
// order really matters!!!!
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
dict = Dictionary.with(*nameSpaces.collect({arg nS, n; nS->modelItems[n]}));
};
loadLedgerFile = {arg path;
ledgerPath = path;
loadLedgerJSON.value(File(ledgerPath, "r").readAllString.parseJSON)
};
loadLedgerJSON = {arg jsonObject; ledger = jsonObject["ledger"]};
saveLedger = {arg ledger, path;
var file;
file = File(path, "w");
file.write("{\n\"ledger\":\n" ++ stringifyToDepth.value(ledger, 1) ++ "\n}");
file.close;
};
//------global vars
primes = [[2, 1], [3, 2], [5, 4], [7, 4], [11, 8], [13, 8]];
//ranges = [[-2400, 0], [-1200, 1200], [0, 2400], [0, 2400]];
exPath = thisProcess.nowExecutingPath;
dir = exPath.dirname;
//popSize = 4;
dims = primes.size;
tuples = genTuples.value();
//refUID = nil;
group = Group.new;
loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json");
//passagesWeights = [1, 1, 1, 1, 1];
//susWeights = [1, 1, 1];
// order really matters!!!!
nameSpaces = [
"music_data", "last_changes", "cur_uid", "ref_uid", "order_seed", "dur_seed", "motifs_seed",
"entrances_probs_vals","passages_probs_vals", "exits_probs_vals",
"ranges", "passages_weights", "order", "sus_weights", "order_size", "passages_size",
"motif_edited", "order_edited"
];
//------OSC funcs
OSCdef(\load_ledger, {arg msg, time, addr, port;
loadLedgerFile.value(msg[1].asString);
}, \load_ledger);
OSCdef(\load_model, {arg msg, time, addr, port;
var dict;
dict = loadModelFile.value(msg[1].asString);
setGlobalVars.value(dict);
}, \load_model);
OSCdef(\save_ledger, {arg msg, time, addr, port;
msg.postln;
ledger = msgInterpret.value(msg[1].asString.parseJSON["ledger"], false).postln;
//loadLedgerJSON.value(msg[0])
saveLedger.value(ledger, msg[2].asString);
//loadLedgerFile.value(msg[1].asString);
}, \save_ledger);
OSCdef(\generate, {arg msg, time, addr, port;
var path, dict, durSeeds, musPath, modelString;
msg.postln;
path = msg[1].asString;
dict = loadModelFile.value(path);
setGlobalVars.value(dict);
popSize = ranges.size;
//refUID.postln;
loadLedgerFile.value(ledgerPath);
if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, {
[initVoices.value().deepCopy];
}, {
var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
exitsDurFunc = genDurFunc.valueArray(exitsProbVals[..4] ++ [exitsProbVals[5..]] ++ [durSeeds[2]]);
if(orders == nil, {
orders = seedFunc.value(genOrders, orderSeed).valueArray(orderSize ++ passagesSize);
//addr.sendMsg("/order", stringifyToDepth.value(orders, 1));
});
seq = seedFunc.value(genMotif, motifSeed).value;
dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict);
//addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3));
addr.sendMsg("/generated", path, modelString);
}, \generate);
OSCdef(\commit, {arg msg, time, addr, port;
var musicData, musicChanged, dict, newLedger, modelPath, musString, musFile, test1, test2;
//msg.postln;
/*
test1 = msg[1].asString.parseJSON;
test2 = (dir +/+ ".." +/+ "resources/tmp/tmp_music" ++ ".json").standardizePath.parseJSONFile;
msgInterpret.value(test1["music"])[0][0][0][1].class.postln;
msgInterpret.value(test2["music_data"])[0][0][0][1].class.postln;
(test1["music"] == test2["music_data"]).postln;
*/
musicData = loadModelJSON.value(msg[1].asString.parseJSON)["music_data"].postln;
musicChanged = (musicData != seq).postln;
curUID = genUID.value;
File.mkdir((dir +/+ ".." +/+ "resources" +/+ curUID).standardizePath);
File.copy(exPath, (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_code" ++ ".scd").standardizePath);
modelPath = (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_mus_model" ++ ".json").standardizePath;
dict = globalVarsToDict.value;
if(musicChanged, {
seq = musicData;
dict["music_data"] = seq;
dict["motif_edited"] = "true"
});
dict["cur_uid"] = curUID;
writeResources.value(modelPath, dict);
File.delete(ledgerPath ++ "_bak");
File.copy(ledgerPath, ledgerPath ++ "_bak");
File.delete(ledgerPath);
ledger = ledger.drop(-1).add(curUID);
saveLedger.value(ledger, ledgerPath);
addr.sendMsg("/committed", curUID, ledgerPath);
//refUID = curUID;
}, \commit);
OSCdef(\transport, {arg msg, time, addr, port;
msg.postln;
if(msg[1] == 0, {
player.stop;
group.set(\gate, 0);
}, {
// the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
pSeq = [];
cuedSeek = (seq != nil);
indexStart = msg[2].asInteger;
indexEnd = ledger.size - if(cuedSeek, {2}, {1});
//ledger.postln;
if(((indexStart == (ledger.size - 1)) && cuedSeek).not, {
ledger[indexStart..indexEnd].do({arg uid, index;
var path, file;
path = (dir +/+ ".." +/+ "resources" +/+ uid +/+ uid ++ "_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
//"here".postln;
pSeq = pSeq.add([msgInterpret.value(file.readAllString.postln.parseJSON["music_data"]), path, indexStart + index, uid]);
file.close;
});
});
if(cuedSeek, {
var path, file;
path = (dir +/+ ".." +/+ "resources/tmp/tmp_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.parseJSON["music_data"]), path, ledger.size - 1, "tmp"]);
file.close;
});
patterns = genPatterns.value(pSeq, addr);
player = Pfset(pattern: patterns, cleanupFunc: {
addr.sendMsg("/transport", 0);
});
player = player.play
});
}, \transport);
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms;
noHarms = 30;
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add;
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms, freqFinal, start, end;
noHarms = 30;
freq = WhiteNoise.ar * 3 + freq;
freqFinal = Duty.ar((1/freq), 0, freq);
trig = Changed.ar(freqFinal);
start = Demand.ar(trig, 0, Dwhite(-1, -0.75));
end = Demand.ar(trig, 0, Dwhite(0.75, 1));
exc = Phasor.ar(trig, (end - start) * freqFinal / SampleRate.ir, start, end, 0) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(2, 3)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
}).add;
)
"{\"a\": 1}".parseYAML["a"].asInteger;
"{\"a\": 1}".parseJSON["a"].isNumber;
1223423434123.asHexString.toLower
Date.getDate.rawSeconds
Date.seed.asHexString.toLower
n = NetAddr("localhost", 8080);
n.sendMsg("/GET/#", (NetAddr.localAddr.hostname ++ ":" ++ NetAddr.localAddr.port), "/passage_probs_vals");

@ -1,91 +0,0 @@
{
"music_data":
[
[
[
[ [ [ "Rest" ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 7.375 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, 0, -1 ] ], 0.375 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 1, 0, 0, 0 ] ], 0 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0 ] ], 0.25 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 1, 0, 0, 0, 0 ] ], 0.375 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, -1, 0, 0, 0 ] ], 0.375 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, 0, 0 ] ], 0.25 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0, -1, 0, 0 ] ], 0.375 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 2, -1, 0, 0, 0, 0 ] ], 0.375 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 1, 0, 0, 0 ] ], 0.125 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 1, 1, 0, 0, 0, 0 ] ], 9.125 ]
],
[
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ], [ 1, 1, 0, 0, 0, 0 ] ], 0 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 7.125 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, -1, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 1, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0 ], [ "Rest" ], [ "Rest" ] ], 0.375 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 1, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0.125 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, -1, 0 ], [ "Rest" ], [ "Rest" ] ], 0.5 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ "Rest" ], [ "Rest" ] ], 0.375 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 1, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0.375 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, -1, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0.125 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0.375 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0, -1, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 9 ]
],
[
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 4.75 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0, 0, -1, 0 ] ], 0 ],
[ [ [ 0, 1, 0, -1, 0, 0 ], [ 2, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0, 0, -1, 0 ] ], 0.25 ],
[ [ [ 0, 1, 0, -1, 0, 0 ], [ 2, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, 1, 0 ] ], 0.375 ],
[ [ [ 0, 1, 0, -1, 0, 0 ], [ 2, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 2, -1, 0, 0, 0, 0 ] ], 5 ]
],
[
[ [ [ "Rest" ], [ 2, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 2, -1, 0, 0, 0, 0 ] ], 0 ],
[ [ [ "Rest" ], [ 2, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ] ], 0.5 ],
[ [ [ "Rest" ], [ 2, 0, 0, -1, 0, 0 ], [ 1, 0, -1, -1, 0, 0 ], [ "Rest" ] ], 0.375 ],
[ [ [ "Rest" ], [ 2, 0, 0, -1, 0, 0 ], [ 0, 0, 0, -1, 0, 1 ], [ "Rest" ] ], 0.375 ],
[ [ [ "Rest" ], [ 2, 0, 0, -1, 0, 0 ], [ 1, 0, 0, -1, 0, 0 ], [ "Rest" ] ], 0.25 ],
[ [ [ "Rest" ], [ 2, 0, 0, -1, 0, 0 ], [ 2, 0, 0, -2, 0, 0 ], [ "Rest" ] ], 0.375 ],
[ [ [ "Rest" ], [ 2, 0, 0, -1, 0, 0 ], [ 2, -1, 0, -1, 0, 0 ], [ "Rest" ] ], 7 ]
],
[
[ [ [ "Rest" ], [ 2, -1, 0, -1, 0, 1 ], [ 2, -1, 0, -1, 0, 0 ], [ "Rest" ] ], 0.25 ],
[ [ [ "Rest" ], [ 3, -1, -1, -1, 0, 0 ], [ 2, -1, 0, -1, 0, 0 ], [ "Rest" ] ], 0.25 ],
[ [ [ "Rest" ], [ 3, -1, 0, -1, -1, 0 ], [ 2, -1, 0, -1, 0, 0 ], [ "Rest" ] ], 0.5 ],
[ [ [ "Rest" ], [ 3, -2, 0, -1, 0, 0 ], [ 2, -1, 0, -1, 0, 0 ], [ "Rest" ] ], 6.5 ],
[ [ [ "Rest" ], [ 3, -2, 0, -1, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0.25 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 1.375 ]
]
]
],
"last_changes":
[
[ [ 0, 1, 0, -1, 0, 0 ], [ 2, 0, 0, -1, 0, 0 ], [ 2, -1, 0, -1, 0, 0 ], [ 2, -1, 0, 0, 0, 0 ] ],
[ [ 0, 1, 0, -1, 0, 0 ], [ 2, -1, 0, -1, 0, 1 ], [ 2, -1, 0, -1, 0, 0 ], [ 2, -1, 0, 0, 0, 0 ] ],
[ [ 0, 1, 0, -1, 0, 0 ], [ 3, -1, -1, -1, 0, 0 ], [ 2, -1, 0, -1, 0, 0 ], [ 2, -1, 0, 0, 0, 0 ] ],
[ [ 0, 1, 0, -1, 0, 0 ], [ 3, -1, 0, -1, -1, 0 ], [ 2, -1, 0, -1, 0, 0 ], [ 2, -1, 0, 0, 0, 0 ] ],
[ [ 0, 1, 0, -1, 0, 0 ], [ 3, -2, 0, -1, 0, 0 ], [ 2, -1, 0, -1, 0, 0 ], [ 2, -1, 0, 0, 0, 0 ] ]
],
"cur_uid": "65c4abeb",
"ref_uid": "nil",
"order_seed": 792993,
"dur_seed": 209090,
"motifs_seed": 340840,
"entrances_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.26424870466321, 0.75675675675676, 0.5, 0.5, 0.58549222797927, 0.72635135135135, 1, 0.5 ],
"passages_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ -384, 2400 ], [ -507, 2400 ], [ -282, 2237 ], [ -1200, 2053 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ],
"order":
[
[ [ 2, 1 ], [ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 ], [ 0 ] ],
[ [ 0 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 2, 3 ] ],
[ [ 1, 2 ], [ 3, 0, 3, 3 ], [ ] ],
[ [ 1 ], [ 2, 2, 2, 2, 2 ], [ 0, 3 ] ],
[ [ 2 ], [ 1, 1, 1, 1 ], [ 3, 0 ] ]
],
"sus_weights": [ 0.75, 0.69, 0.75 ],
"order_size": [ 2, 6 ],
"passages_size": [ 0, 10 ],
"motif_edited": "false",
"order_edited": "false"
}

@ -1,796 +0,0 @@
(
// helper funcs
var hsArrayToCents, pDist, hdSum, hsChordalDistance, hsArrayToFreq;
// score funcs
var isInRange, spacingScore, rangeScore, intervalScore, inclusionScore;
// subroutines
var genTuples, initVoices, genOrders, genSubMotif, updateVoices, genDurFunc;
// primary routines
var genMotif, genSecondarySeq;
// audition funcs
var genPatterns, genMidiPatterns;
// resource management funcs
var seedFunc, genUID, writeResources, stringifyToDepth, setSeeds, sanityCheck,
msgInterpret, loadLedgerFile, loadLedgerJSON, loadModelFile, loadModelJSON,
setGlobalVars, globalVarsToDict, saveLedger;
// model vars
//(model and global vars mostly set by OSC funcs
var seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited;
// model aux vars
var entrancesDurFunc, passagesDurFunc, exitsDurFunc;
// other global vars
var popSize, exPath, dir, primes, dims, tuples,
group, player, ledgerPath, ledger, currentlyPlayingUID,
nameSpaces;
// install JSON quark
if(Quarks.isInstalled("JSONlib").not, {
Quarks.install("https://github.com/musikinformatik/JSONlib.git");
thisProcess.recompile;
//HelpBrowser.openHelpFor("Classes/JSONlib");
});
//------helper funcs
hsArrayToCents = {
arg hsArray;
hsArray.collect({arg dist, p; dist * 1200 * log2(primes[p][0]/primes[p][1])}).sum
};
pDist = {
arg array1, array2, signed = false;
var pDistance;
pDistance = hsArrayToCents.value(array1) - hsArrayToCents.value(array2);
if(signed, {pDistance}, {abs(pDistance)})
};
hdSum = {
arg hsArrays;
var size, distances, mean;
size = hsArrays.size;
distances = (size - 1).collect({arg i;
((i + 1)..(size - 1)).collect({arg j;
abs(hsArrays[i] - hsArrays[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsChordalDistance = {
arg hsArrays1, hsArrays2;
var size, distances, mean;
size = hsArrays1.size;
distances = hsArrays1.size.collect({arg i;
hsArrays2.size.collect({arg j;
abs(hsArrays1[i] - hsArrays2[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsArrayToFreq = {
arg array;
array.collect({arg dim, d; pow(primes[d][0]/primes[d][1], dim)}).product
};
//------score funcs
/*
isInRange = {
arg hsArray, min, max;
var cents;
cents = hsArrayToCents.value(hsArray);
(cents >= min) && (cents <= max)
};
*/
spacingScore = {
arg hsArrays, min;
var centsArray;
centsArray = hsArrays.collect({arg hsArray; hsArrayToCents.value(hsArray)}).sort({arg a, b; a < b});
centsArray.differentiate.drop(1).collect({arg pDistance; if(pDistance >= min, {1}, {0.01})}).sum;
};
rangeScore = {
arg hsArray1, hsArray2, min, max, low, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
if((pDistance >= min) && (pDistance <= max), {1}, {low});
};
intervalScore = {
arg hsArray1, hsArray2, mean, sd, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
pDistance.gaussCurve(1, mean, sd)
};
inclusionScore = {
arg array, test, min = 0.01;
if(array.collect({arg v; v.hash}).includes(test.hash), {min}, {1});
};
//------subroutines
genTuples = {
var tuples;
tuples = dims.collect({[-1, 0, 1]}).allTuples.select({arg tuple; (abs(tuple.drop(1)).sum <= 1) && (tuple[0] == 0)});
tuples = tuples ++ tuples.collect({arg tuple; [-3, -2, -1, 1, 2, 3].collect({arg octTrans; tuple.deepCopy.put(0, octTrans)})}).flatten;
};
initVoices = {
var init, voicesInit;
voicesInit = popSize.collect({dims.collect({0})});
/*
voicesInit = [dims.collect({0})];
(popSize - 1).do({
arg rep, new;
rep = dims.rand;
new = voicesInit.last.deepCopy;
new[rep] = new[rep] + [-1, 1].choose();
voicesInit = voicesInit.add(new);
});
*/
voicesInit.deepCopy;
};
genDurFunc = {arg chordProb, minPad, maxPad, minDur, maxDur, envData, seed;
var env, pTable, durFunc;
env = Env.pairs([[0, 0]] ++ envData.clump(2) ++ [[1, 0]]).asSignal(256).asList.asArray;
pTable = env.asRandomTable;
[chordProb, minPad, maxPad, minDur, maxDur, envData].postln;
durFunc = {arg allowChord, pad = false;
var res;
res = if(allowChord.not, {
pTable.tableRand * (maxDur - minDur) + minDur
}, {
if(1.0.rand < chordProb, {0}, {pTable.tableRand * (maxDur - minDur) + minDur});
}).round(0.125);
if(pad, {res = res + rrand(minPad.asFloat, maxPad.asFloat).round(0.125)});
if(res.asInteger == res, {res = res.asInteger});
res
};
seedFunc.value(durFunc, seed);
};
genOrders = {arg minMotifLength = 1, maxMotifLength = 5, minProgLength = 0, maxProgLength = 5;
((maxMotifLength - minMotifLength).rand + minMotifLength).collect({
var noProgIns, noSusIns, noSilentIns, prog, sus, silent, order;
noSusIns = [1, 2, 3].wchoose(susWeights.normalizeSum);
noProgIns = (popSize - noSusIns).rand + 1;
noSilentIns = popSize - noSusIns - noProgIns;
# prog, sus, silent = (0..(popSize-1)).scramble.clumps([noProgIns, noSusIns, noSilentIns]);
prog = (prog.scramble ++ ((maxProgLength - minProgLength).rand + minProgLength).collect({prog.choose}).scramble);
if(silent == nil, {silent = []});
[sus.scramble, prog, silent.scramble]
});
};
updateVoices = {arg ins, sus;
var voices, candidates, nWeights, nProbs, sel;
voices = lastXChanges.deepCopy.last;
candidates = sus.collect({arg v; tuples.collect({arg t; voices[v] + t})}).flatten;
candidates = difference(candidates.asSet, voices.asSet).asList;
nProbs = candidates.collect({arg candidate;
var stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore;
//stepScore = intervalScore.value(voices[ins], candidate, 30, 400, 0.1);
stepScore = intervalScore.value(voices[ins], candidate, 100, 100);
recentlySoundedScore = inclusionScore.value(lastXChanges.flop[ins], candidate, 0);
isInRangeScore = rangeScore.value(candidate, candidate.collect({0}), ranges[ins][0], ranges[ins][1], 0, true);
regScore = spacingScore.value(voices.deepCopy.put(ins, candidate), 300);
hdScore = 1/pow(hdSum.value(voices.deepCopy.put(ins, candidate)), 2);
//maybe what you want here is a vector to another root and then favoring movement towards it.
//distScore = pow(hsChordalDistance.value(voices, voices.put(ins, candidate)), 2);
[stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore]
});
nWeights = passagesWeights;
//this handles nWeights of 0; mainly for testing
nProbs = nProbs.flop.select({arg scores, s; nWeights[s] != 0}).flop;
nWeights = nWeights.select({arg weight; weight != 0});
nProbs = nProbs.flop.collect({arg scores, s;
if(scores.sum == 0, {scores}, {scores.normalizeSum * nWeights[s]})
});
nProbs = nProbs.flop.collect({arg scores, s; scores.product}).normalizeSum;
sel = candidates.wchoose(nProbs);
voices[ins] = sel;
lastXChanges = lastXChanges.add(voices).keep(-5);
};
genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLast = false, isLastOrder = false;
var sus, prog, silent, flatOrder, res, isInChord, allowChord, pad, lastXChangesHold, voices, adder;
# sus, prog, silent = order;
flatOrder = silent ++ sus ++ prog;
lastXChangesHold = lastXChanges.deepCopy;
voices = lastState.deepCopy;
isInChord = popSize.collect({false});
allowChord = false;
pad = false;
res = [];
"------generating motif".postln;
//need to figure out here if voices move between motifs
flatOrder.do({arg ins, i;
if(prog.includes(ins) && repeatLast.not, {updateVoices.value(ins, sus)});
adder = if(silent.includes(ins), {["Rest"]}, {lastXChanges.last.deepCopy[ins]});
if(voices[ins] != adder, {
var dur;
if((sus ++ silent).includes(ins), {
allowChord = (ins != sus.last);
pad = (ins == sus.last);
}, {
if(i < (flatOrder.size - 1), {
allowChord = (isInChord[flatOrder[i + 1]] || (ins == flatOrder[i + 1])).not;
pad = false;
}, {
allowChord = false;
pad = true
});
});
if((orderIndex == 0) && sus.includes(ins), {
dur = entrancesDurFunc.value(allowChord, pad);
}, {
dur = passagesDurFunc.value(allowChord, pad);
});
if(dur == 0, {isInChord[ins] = true}, {isInChord = popSize.collect({false})});
voices[ins] = adder;
res = res.add([voices.deepCopy.postln, dur]);
});
});
// pad ending
if(orderIndex == (orders.size - 1), {
(0..(popSize-1)).scramble.do({arg ins;
if(res.last.first[ins] != ["Rest"], {
var dur;
voices[ins] = ["Rest"];
allowChord = (voices != popSize.collect({["Rest"]}));
pad = allowChord.not;
dur = exitsDurFunc.value(allowChord, pad);
res = res.add([voices.deepCopy.postln, dur]);
});
});
});
//format and return
if(startFromLast, {lastXChanges = lastXChangesHold});
res;
};
//------primary routines
genMotif = {
var repeats, fSeq;
repeats = 1;
fSeq = [];
repeats.do({arg index;
var motif;
motif = [];
orders.do({arg order, o;
var lastState, subMotif;
lastState = if(o == 0, {popSize.collect({["Rest"]})}, {motif.last.last.first});
subMotif = genSubMotif.value(order, o, lastState, isLastOrder: o == (orders.size - 1));
motif = motif.add(subMotif);
});
sanityCheck.value(motif, index);
fSeq = fSeq.add(motif);
});
fSeq
};
genSecondarySeq = {arg seq;
var curdles, fSeq;
curdles = [];
while({curdles.sum < seq.size}, {curdles = curdles ++ [3.rand + 1]});
fSeq = seq.clumps(curdles).collect({arg clump, m;
var repeats, paddedSeq;
//add rest
paddedSeq = clump.add([[[popSize.collect({["Rest"]}), 0.5.rand]]]);
//implement repeats
repeats = [0.rand + 1, 1].wchoose([1, 0].normalizeSum);
repeats.collect({paddedSeq});
});
fSeq
};
//------audition funcs
/*
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~addr.sendMsg(~indexPath, ~indexMsg);
~addr.sendMsg(~seqPath, stringifyToDepth.value(~seqMsg, 3));
//~addr.sendMsg("/STATE/OPEN", (dir.replace("supercollider", "resources") +/+ ~idMsg +/+ ~idMsg ++ "_gui_state" ++ ".state").standardizePath.postln);
};
});
*/
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~msg.postln;
~addr.sendMsg(~path, *~msg);
};
});
genPatterns = {arg inSeq, addr, oneShot = false;
var voices, durs, pbinds, res, indices, sectionDurs, msg, ids, seq;
seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
pbinds = voices.flop.collect({arg voice;
var clumps, hdScores, freqs, fDurs;
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\instrument, \test,
\group, group,
\freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1),
\sustain, Pseq(fDurs, 1)
)
});
if(oneShot.not, {
msg = inSeq.collect({arg mSeq, m; mSeq[1..]});
//ids = inSeq.collect({arg mSeq, m; mSeq[2]});
sectionDurs = seq.collect({arg mSeq; mSeq.flatten2(mSeq.maxDepth - 5).flop[1].sum});
pbinds = pbinds ++
[
Pbind(
\type, \osc,
\addr, addr,
\path, "/playing",
\msg, Pseq(msg, 1),
\dur, Pseq(sectionDurs, 1)
);
]
});
res = Ppar(pbinds);
res
};
/*
genMidiPatterns = {arg seq;
var voices, durs, patterns, res, mOut, pbRange;
pbRange = 1; //semitones - change this as needed for your situation
mOut = MIDIOut.newByName("TiMidity", "TiMidity port 0").latency_(Server.default.latency);
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
res = Ppar(
voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs;
mOut.program(v, 70);
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\type, \midi,
\chan, v,
\noteval, Pseq(freqs.cpsmidi - 24, 1),
\note, Pfunc({ | event | event[\noteval].floor }),
\dur, Pseq(fDurs, 1),
\midiout, mOut,
\amp, 1,
\bend, Pfunc({
| event |
if (event[\note].isRest.not) {
var pitchbendvalue = event[\noteval].frac.linlin(0, pbRange, 8192, 8192*2).asInteger;
m.bend(v, pitchbendvalue);
};
0; // return something other than nil to avoid stopping the pattern
}),
);
});
);
res
};
*/
//------resource management funcs
genUID = {Date.seed.asHexString.toLower};
seedFunc = {arg func, seed;
var funcArgs, next;
next = Routine({loop{func.valueArray(funcArgs).yield }});
next.randSeed_(seed);
{arg ...args; funcArgs = args; next.value}
};
stringifyToDepth = {arg data, maxDepth = 1;
var prettyString = "", rCount = 0, writeArray, indent;
if(maxDepth == 0, {
data.asCompileString
}, {
indent = {arg size; size.collect({" "}).join("")};
writeArray = {arg array;
prettyString = prettyString ++ indent.value(rCount) ++ "[\n";
rCount = rCount + 1;
if(rCount < maxDepth, {
array.do({arg subArray; writeArray.value(subArray)});
}, {
prettyString = prettyString ++ array.collect({arg subArray;
indent.value(rCount + 1) ++ subArray.asCompileString
}).join(",\n");
});
rCount = rCount - 1;
prettyString = prettyString ++ "\n" ++ indent.value(rCount) ++ "],\n";
};
writeArray.value(data);
prettyString.replace(",\n\n", "\n").drop(-2);
})
};
sanityCheck = {arg motif, index;
//print functions = very helpful
("----------" + index + "------------").postln;
motif.flatten.do({arg val, v;
if(v > 0, {
if(motif.flatten[v-1][0].hammingDistance(val[0]) > 1, {"problem 1".postln});
if(motif.flatten[v-1][0].hammingDistance(val[0]) == 0, {"problem 2".postln});
});
val.postln
});
"***********".postln;
};
msgInterpret = {arg in, escapeDoubleQuotes = true, escapeSingleQuotes = true;
var res;
res = in;
if(res.isNil.not, {
if((res.isArray && res.isString.not), {
res = res.asCompileString;
res = res.replace(" ", "").replace("\n", "").replace("\t", "");
if(escapeSingleQuotes, {res = res.replace("\'", "")});
if(escapeDoubleQuotes, {res = res.replace("\"", "")});
res = res.replace("Rest", "\"Rest\"");
res = res.interpret;
}, {
//res.postln;
if(res.every({arg char; char.isDecDigit}), {res = res.asInteger});
});
});
res
};
writeResources = {arg path, dict;
var file, modelItems, resString;
file = File(path,"w");
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
resString = nameSpaces.collect({arg nameSpace;
var depth = 0, insert = " ";
if(nameSpace == "music_data", {depth = 3; insert = "\n"});
if(nameSpace == "last_changes", {depth = 1; insert = "\n"});
if(nameSpace == "order", {depth = 1; insert = "\n"});
if((nameSpace == "ref_uid") && (dict[nameSpace] == nil), {dict[nameSpace] = "nil"});
"\"" ++ nameSpace ++ "\":" ++ insert ++ stringifyToDepth.value(dict[nameSpace], depth)
}).join(",\n");
resString = "{\n" ++ resString ++ "\n}";
file.write(resString);
file.close;
resString
};
loadModelFile = {arg path; loadModelJSON.value(File(path, "r").readAllString.parseJSON)};
loadModelJSON = {arg jsonObject;
var dict;
dict = Dictionary.with(*nameSpaces.collect({arg nS; nS->msgInterpret.value(jsonObject[nS])}));
dict
};
setGlobalVars = {arg dict;
// order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
dict
};
globalVarsToDict = {
var modelItems, dict;
// order really matters!!!!
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
dict = Dictionary.with(*nameSpaces.collect({arg nS, n; nS->modelItems[n]}));
};
loadLedgerFile = {arg path;
ledgerPath = path;
loadLedgerJSON.value(File(ledgerPath, "r").readAllString.parseJSON)
};
loadLedgerJSON = {arg jsonObject; ledger = jsonObject["ledger"]};
saveLedger = {arg ledger, path;
var file;
file = File(path, "w");
file.write("{\n\"ledger\":\n" ++ stringifyToDepth.value(ledger, 1) ++ "\n}");
file.close;
};
//------global vars
primes = [[2, 1], [3, 2], [5, 4], [7, 4], [11, 8], [13, 8]];
//ranges = [[-2400, 0], [-1200, 1200], [0, 2400], [0, 2400]];
exPath = thisProcess.nowExecutingPath;
dir = exPath.dirname;
//popSize = 4;
dims = primes.size;
tuples = genTuples.value();
//refUID = nil;
group = Group.new;
loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json");
//passagesWeights = [1, 1, 1, 1, 1];
//susWeights = [1, 1, 1];
// order really matters!!!!
nameSpaces = [
"music_data", "last_changes", "cur_uid", "ref_uid", "order_seed", "dur_seed", "motifs_seed",
"entrances_probs_vals","passages_probs_vals", "exits_probs_vals",
"ranges", "passages_weights", "order", "sus_weights", "order_size", "passages_size",
"motif_edited", "order_edited"
];
//------OSC funcs
OSCdef(\load_ledger, {arg msg, time, addr, port;
loadLedgerFile.value(msg[1].asString);
}, \load_ledger);
OSCdef(\load_model, {arg msg, time, addr, port;
var dict;
dict = loadModelFile.value(msg[1].asString);
setGlobalVars.value(dict);
}, \load_model);
OSCdef(\save_ledger, {arg msg, time, addr, port;
msg.postln;
ledger = msgInterpret.value(msg[1].asString.parseJSON["ledger"], false).postln;
//loadLedgerJSON.value(msg[0])
saveLedger.value(ledger, msg[2].asString);
//loadLedgerFile.value(msg[1].asString);
}, \save_ledger);
OSCdef(\generate, {arg msg, time, addr, port;
var path, dict, durSeeds, musPath, modelString;
msg.postln;
path = msg[1].asString;
dict = loadModelFile.value(path);
setGlobalVars.value(dict);
popSize = ranges.size;
//refUID.postln;
loadLedgerFile.value(ledgerPath);
if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, {
[initVoices.value().deepCopy];
}, {
var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
exitsDurFunc = genDurFunc.valueArray(exitsProbVals[..4] ++ [exitsProbVals[5..]] ++ [durSeeds[2]]);
if(orders == nil, {
orders = seedFunc.value(genOrders, orderSeed).valueArray(orderSize ++ passagesSize);
//addr.sendMsg("/order", stringifyToDepth.value(orders, 1));
});
seq = seedFunc.value(genMotif, motifSeed).value;
dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict);
//addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3));
addr.sendMsg("/generated", path, modelString);
}, \generate);
OSCdef(\commit, {arg msg, time, addr, port;
var musicData, musicChanged, dict, newLedger, modelPath, musString, musFile, test1, test2;
//msg.postln;
/*
test1 = msg[1].asString.parseJSON;
test2 = (dir +/+ ".." +/+ "resources/tmp/tmp_music" ++ ".json").standardizePath.parseJSONFile;
msgInterpret.value(test1["music"])[0][0][0][1].class.postln;
msgInterpret.value(test2["music_data"])[0][0][0][1].class.postln;
(test1["music"] == test2["music_data"]).postln;
*/
musicData = loadModelJSON.value(msg[1].asString.parseJSON)["music_data"].postln;
musicChanged = (musicData != seq).postln;
curUID = genUID.value;
File.mkdir((dir +/+ ".." +/+ "resources" +/+ curUID).standardizePath);
File.copy(exPath, (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_code" ++ ".scd").standardizePath);
modelPath = (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_mus_model" ++ ".json").standardizePath;
dict = globalVarsToDict.value;
if(musicChanged, {
seq = musicData;
dict["music_data"] = seq;
dict["motif_edited"] = "true"
});
dict["cur_uid"] = curUID;
writeResources.value(modelPath, dict);
File.delete(ledgerPath ++ "_bak");
File.copy(ledgerPath, ledgerPath ++ "_bak");
File.delete(ledgerPath);
ledger = ledger.drop(-1).add(curUID);
saveLedger.value(ledger, ledgerPath);
addr.sendMsg("/committed", curUID, ledgerPath);
//refUID = curUID;
}, \commit);
OSCdef(\transport, {arg msg, time, addr, port;
msg.postln;
if(msg[1] == 0, {
player.stop;
group.set(\gate, 0);
}, {
// the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
if(msg[1] == 1, {
pSeq = [];
cuedSeek = (seq != nil);
indexStart = msg[2].asInteger;
indexEnd = ledger.size - if(cuedSeek, {2}, {1});
//ledger.postln;
if(((indexStart == (ledger.size - 1)) && cuedSeek).not, {
ledger[indexStart..indexEnd].do({arg uid, index;
var path, file;
path = (dir +/+ ".." +/+ "resources" +/+ uid +/+ uid ++ "_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.postln.parseJSON["music_data"]), path, indexStart + index, uid]);
file.close;
});
});
if(cuedSeek, {
var path, file;
path = (dir +/+ ".." +/+ "resources/tmp/tmp_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.parseJSON["music_data"]), path, ledger.size - 1, "tmp"]);
file.close;
});
}, {
"here".postln;
pSeq = [loadModelJSON.value(msg[2].asString.parseJSON)["music_data"].postln];
});
patterns = genPatterns.value(pSeq, addr);
player = Pfset(pattern: patterns, cleanupFunc: {
addr.sendMsg("/transport", 0);
});
player = player.play
});
}, \transport);
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms;
noHarms = 30;
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add;
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms, freqFinal, start, end;
noHarms = 30;
freq = WhiteNoise.ar * 3 + freq;
freqFinal = Duty.ar((1/freq), 0, freq);
trig = Changed.ar(freqFinal);
start = Demand.ar(trig, 0, Dwhite(-1, -0.75));
end = Demand.ar(trig, 0, Dwhite(0.75, 1));
exc = Phasor.ar(trig, (end - start) * freqFinal / SampleRate.ir, start, end, 0) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(2, 3)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
}).add;
)
"{\"a\": 1}".parseYAML["a"].asInteger;
"{\"a\": 1}".parseJSON["a"].isNumber;
1223423434123.asHexString.toLower
Date.getDate.rawSeconds
Date.seed.asHexString.toLower
n = NetAddr("localhost", 8080);
n.sendMsg("/GET/#", (NetAddr.localAddr.hostname ++ ":" ++ NetAddr.localAddr.port), "/passage_probs_vals");

@ -1,55 +0,0 @@
{
"music_data":
[
[
[
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 0 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 7.125 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 1, 0, 0, 0 ], [ "Rest" ] ], 0.25 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 1, -1, 0, 0, 0, 0 ], [ "Rest" ] ], 0.375 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 1, 0, 0, 0, 0 ], [ "Rest" ] ], 0.125 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ "Rest" ] ], 7.25 ]
],
[
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ "Rest" ] ], 0.125 ],
[ [ [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 5 ],
[ [ [ "Rest" ], [ 0, 0, 0, -1, 0, 1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 0.25 ],
[ [ [ "Rest" ], [ -1, 0, 1, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 0 ],
[ [ [ "Rest" ], [ 1, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 0.125 ],
[ [ [ "Rest" ], [ 1, -1, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 0.5 ],
[ [ [ "Rest" ], [ 1, 0, 0, 0, 0, -1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ], 10.25 ],
[ [ [ "Rest" ], [ 1, 0, 0, 0, 0, -1 ], [ 0, 0, 0, 0, 0, 1 ], [ "Rest" ] ], 0 ],
[ [ [ "Rest" ], [ "Rest" ], [ 0, 0, 0, 0, 0, 1 ], [ "Rest" ] ], 0 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 6.125 ]
]
]
],
"last_changes":
[
[ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, -1, 0, 1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ -1, 0, 1, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, -1, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, 0, -1 ], [ 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0 ] ]
],
"cur_uid": "661a850b",
"ref_uid": "nil",
"order_seed": 815237,
"dur_seed": 146432,
"motifs_seed": 680955,
"entrances_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.26424870466321, 0.75675675675676, 0.5, 0.5, 0.58549222797927, 0.72635135135135, 1, 0.5 ],
"passages_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0.75, 0, 10, 0, 0.5, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ -384, 2400 ], [ -507, 2400 ], [ -282, 2237 ], [ -1200, 2053 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ],
"order":
[
[ [ 1, 0 ], [ 2, 2, 2, 2 ], [ 3 ] ],
[ [ 2, 3 ], [ 1, 1, 1, 1, 1 ], [ 0 ] ]
],
"sus_weights": [ 0.75, 0.69, 0.75 ],
"order_size": [ 2, 6 ],
"passages_size": [ 0, 10 ],
"motif_edited": "false",
"order_edited": "false"
}

@ -1,51 +0,0 @@
{
"music_data":
[
[
[
[ [ [ -1, 1, 0, 0, 1, 0 ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 0.875 ],
[ [ [ -1, 1, 0, 0, 1, 0 ], [ "Rest" ], [ "Rest" ], [ 0, 1, 0, 0, 0, 0 ] ], 5.125 ],
[ [ [ -1, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 1, -1 ], [ "Rest" ], [ 0, 1, 0, 0, 0, 0 ] ], 0.875 ],
[ [ [ -1, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, -1, 0 ], [ "Rest" ], [ 0, 1, 0, 0, 0, 0 ] ], 4.625 ]
],
[
[ [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 1, 0, 0, -1, 0 ], [ "Rest" ], [ 0, 1, 0, 0, 0, 0 ] ], 0.375 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ -1, 1, 0, 0, 1, 0 ], [ "Rest" ], [ 0, 1, 0, 0, 0, 0 ] ], 0.875 ],
[ [ [ 0, 0, 0, 0, 0, 0 ], [ -1, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 0, 0 ] ], 0.5 ],
[ [ [ -1, 1, 1, 0, 0, 0 ], [ -1, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 0, 0 ] ], 3.75 ],
[ [ [ -1, 1, 1, 0, 0, 0 ], [ "Rest" ], [ 0, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 0, 0 ] ], 0.375 ],
[ [ [ "Rest" ], [ "Rest" ], [ 0, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 0, 0 ] ], 0.625 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ 0, 1, 0, 0, 0, 0 ] ], 0.125 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 4.875 ]
]
]
],
"last_changes":
[
[ [ -1, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, -1, 0 ], [ 0, 1, 1, 0, 0, 0 ], [ 0, 1, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 0, 1, 0, 0, -1, 0 ], [ 0, 1, 1, 0, 0, 0 ], [ 0, 1, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ -1, 1, 0, 0, 1, 0 ], [ 0, 1, 1, 0, 0, 0 ], [ 0, 1, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ -1, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 0, 0 ] ],
[ [ -1, 1, 1, 0, 0, 0 ], [ -1, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 0, 0 ] ]
],
"cur_uid": "6a3271c4",
"ref_uid": "50fec831",
"order_seed": 982967,
"dur_seed": 234868,
"motifs_seed": 131634,
"entrances_probs_vals": [ 0, 1.67, 4.8015873015873, 0.24725274725275, 1.15, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"passages_probs_vals": [ 0, 1.67, 4.8015873015873, 0.24725274725275, 1.15, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0, 1.83, 4.8809523809524, 0, 0.93406593406593, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ -1100, 460.68111455108 ], [ -507, 1084.8297213622 ], [ 884.21052631579, 2237 ], [ 1040.2476780186, 2053 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ],
"order":
[
[ [ 0, 3 ], [ 1, 1 ], [ 2 ] ],
[ [ 3 ], [ 0, 1, 2, 0 ], [ ] ]
],
"sus_weights": [ 0.73, 0.23, 0 ],
"order_size": [ 1, 3 ],
"passages_size": [ 0, 2 ],
"motif_edited": "false",
"order_edited": "false"
}

@ -283,7 +283,7 @@ genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLa
}); });
//format and return //format and return
if(startFromLast, {lastXChanges = lastXChangesHold}); if(startFromLast, {lastXChanges = lastXChangesHold.deepCopy});
res; res;
}; };
@ -358,20 +358,42 @@ genPatterns = {arg inSeq, addr, oneShot = false;
var voices, durs, pbinds, res, indices, sectionDurs, msg, ids, seq; var voices, durs, pbinds, res, indices, sectionDurs, msg, ids, seq;
seq = inSeq.collect({arg mSeq; mSeq[0]}); seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop; # voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
pbinds = voices.flop.collect({arg voice; pbinds = voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs; var clumps, hdScores, freqs, fDurs, attacks, rels, amps;
clumps = voice.separate({arg a, b; a != b }); clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})}); freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum}); fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
//attacks = 2.collect({rrand(1, 3)}) ++ freqs.drop(2).collect({rrand(0.3, 0.5)});
attacks = fDurs.collect({arg dur; dur * rrand(0.2, 0.4)});
//rels = freqs.drop(2).collect({rrand(0.3, 0.5)}) ++ 2.collect({rrand(1, 3)});
rels = (clumps.size - 1).collect({arg c;
if(clumps[c + 1][0] == ["Rest"], {rrand(1, 3)}, {rrand(0.3, 0.5)});
});
amps = freqs.collect({rrand(0.6, 0.99)});
[
Pbind(
\instrument, \string_model,
\group, group,
\freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1),
\attack, Pseq(attacks, 1),
\sustain, Pseq(fDurs, 1),
\release, Pseq(rels, 1),
//\amp, Pseq(amps, 1),
\amp, Pbrown(0.5, 1, 0.5),
\busIndex, v
),
Pbind( Pbind(
\instrument, \test, \instrument, \sine,
\group, group, \group, group,
\freq, Pseq(freqs, 1), \freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1), \dur, Pseq(fDurs, 1),
\sustain, Pseq(fDurs, 1) \sustain, Pseq(fDurs, 1),
\busIndex, v
) )
}); ]
}).flatten;
if(oneShot.not, { if(oneShot.not, {
msg = inSeq.collect({arg mSeq, m; mSeq[1..]}); msg = inSeq.collect({arg mSeq, m; mSeq[1..]});
//ids = inSeq.collect({arg mSeq, m; mSeq[2]}); //ids = inSeq.collect({arg mSeq, m; mSeq[2]});
@ -538,12 +560,15 @@ loadModelJSON = {arg jsonObject;
dict dict
}; };
setGlobalVars = {arg dict; setGlobalVars = {arg dict, skipLastXChanges = false;
var tmpLastXChanges;
tmpLastXChanges = lastXChanges.deepCopy;
// order really matters!!!! // order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed, # seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals, entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize, ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]}); motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
if(skipLastXChanges, {lastXChanges = tmpLastXChanges});
dict dict
}; };
@ -585,6 +610,7 @@ dims = primes.size;
tuples = genTuples.value(); tuples = genTuples.value();
//refUID = nil; //refUID = nil;
group = Group.new; group = Group.new;
~group = group;
loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json"); loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json");
//passagesWeights = [1, 1, 1, 1, 1]; //passagesWeights = [1, 1, 1, 1, 1];
//susWeights = [1, 1, 1]; //susWeights = [1, 1, 1];
@ -624,7 +650,7 @@ OSCdef(\generate, {arg msg, time, addr, port;
path = msg[1].asString; path = msg[1].asString;
dict = loadModelFile.value(path); dict = loadModelFile.value(path);
setGlobalVars.value(dict); setGlobalVars.value(dict, true);
popSize = ranges.size; popSize = ranges.size;
@ -634,14 +660,16 @@ OSCdef(\generate, {arg msg, time, addr, port;
if(ledger == nil, {ledger = ["tmp"]}); if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")}); if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, { if(refUID == nil, {lastXChanges = [initVoices.value().deepCopy]});
[initVoices.value().deepCopy]; if((refUID != nil) && (refUID != "tmp"), {
}, {
var file; var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r"); file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]); lastXChanges = msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
}); });
refUID.postln;
lastXChanges.collect({arg item; item.postln});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln; durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]); entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]); passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
@ -653,11 +681,13 @@ OSCdef(\generate, {arg msg, time, addr, port;
}); });
seq = seedFunc.value(genMotif, motifSeed).value; seq = seedFunc.value(genMotif, motifSeed).value;
lastXChanges.collect({arg item; item.postln});
dict = globalVarsToDict.value; dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict); modelString = writeResources.value(path, dict);
//addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3)); //addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3));
addr.sendMsg("/generated", path, modelString); addr.sendMsg("/generated", path, modelString, ledgerPath);
}, \generate); }, \generate);
@ -707,8 +737,9 @@ OSCdef(\commit, {arg msg, time, addr, port;
OSCdef(\transport, {arg msg, time, addr, port; OSCdef(\transport, {arg msg, time, addr, port;
msg.postln; msg.postln;
if(msg[1] == 0, { if(msg[1] == 0, {
player.stop; group.set(\release, 2);
group.set(\gate, 0); group.set(\gate, 0);
player.stop;
}, { }, {
// the cued sequence can now be read from file, so this can be cleaned up // the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger; var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
@ -734,14 +765,14 @@ OSCdef(\transport, {arg msg, time, addr, port;
pSeq = pSeq.add([msgInterpret.value(file.readAllString.parseJSON["music_data"]), path, ledger.size - 1, "tmp"]); pSeq = pSeq.add([msgInterpret.value(file.readAllString.parseJSON["music_data"]), path, ledger.size - 1, "tmp"]);
file.close; file.close;
}); });
patterns = genPatterns.value(pSeq, addr);
}, { }, {
"here".postln;
pSeq = [loadModelJSON.value(msg[2].asString.parseJSON)["music_data"].postln]; pSeq = [loadModelJSON.value(msg[2].asString.parseJSON)["music_data"].postln];
patterns = genPatterns.value(pSeq, addr, true);
}); });
patterns = genPatterns.value(pSeq, addr);
player = Pfset(pattern: patterns, cleanupFunc: { player = Pfset(pattern: patterns, cleanupFunc: {
addr.sendMsg("/transport", 0); addr.sendMsg("/transport", 0);
addr.sendMsg("/one_shot", 0);
}); });
player = player.play player = player.play
}); });
@ -750,19 +781,110 @@ OSCdef(\transport, {arg msg, time, addr, port;
) )
( (
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur; //synthdefs
~stringModelBusArray = 4.collect({Bus.audio(s, 1)});
~sineBusArray = 4.collect({Bus.audio(s, 1)});
~bassBusArray = 1.collect({Bus.audio(s, 1)});
~hdustBusArray = 1.collect({Bus.audio(s, 1)});
~samplerBusArray = 2.collect({Bus.audio(s, 1)});
~sBuf = Buffer.alloc(s, 10, 2);
SynthDef(\string_model, {arg freq, gate = 1, sustain, amp, dur, attack, release = 1, busIndex = 0;
var trig, exc, sig1, sig2, noHarms; var trig, exc, sig1, sig2, noHarms;
noHarms = 30; noHarms = rrand(20, 40);
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01); exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq), sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}), Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.5).softclip; Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.8).softclip;
sig1 = HPF.ar(sig1, 300); //sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2)); Out.ar(Select.kr(busIndex, ~stringModelBusArray), sig1 * amp * EnvGen.kr(Env.adsr(attack, 0.3, 0.9, release, 0.9, -3), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2)); //Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add; }).add;
SynthDef(\sine, {arg freq, gate = 1, sustain, amp, dur, busIndex = 0;
var sig;
sig = SinOsc.ar(freq);
Out.ar(Select.kr(busIndex, ~sineBusArray), sig * EnvGen.kr(Env.asr(0.3, 0.4, 0.3), gate, timeScale: dur, doneAction: 2));
//Out.ar(Select.kr(busIndex, ~sineBusArray), sig * EnvGen.kr(Env.sine(dur), gate, doneAction: 2));
}).add;
SynthDef(\mixer, {arg freq, gate = 1, sustain, amp, dur, out;
var nameSpaces, sigs, hierarchicalDust;
hierarchicalDust = (
TIRand.kr(0, 1, Impulse.kr(100)) *
TIRand.kr(0, 1, Impulse.kr(10)) *
TIRand.kr(0, 1, Impulse.kr(1))
);
sigs = [~stringModelBusArray, ~sineBusArray, ~bassBusArray, ~hdustBusArray, ~samplerBusArray].collect({arg busArray, i;
var nameSpace, sig;
nameSpace = ['string', 'sine', 'bass', 'hdust', 'sampler'][i];
sig = busArray.collect({arg bus, c; In.ar(bus, 1) * NamedControl.kr(\ ++ nameSpace ++ '_volume_' ++ c, 1, 0.1)});
sig = sig.collect({arg channel, c; Pan2.ar(channel, NamedControl.kr(\ ++ nameSpace ++ '_pan_' ++ c, i / (busArray.size - 1), 0.1) * 2 - 1)});
sig = sig.collect({arg channel, c; channel * NamedControl.kr(\ ++ nameSpace ++ '_mute_' ++ c, 1, 0.1)});
sig = Mix.ar(sig) * pow(NamedControl.kr(\ ++ nameSpace ++ '_volume_master', 1, 0.1), 2);
});
sigs = Mix.ar(sigs / 4);
Out.ar(0, sigs)
}).add;
SynthDef(\bass, {
var switches, drone;
switches = {|i| Dust.kr(0.1)} ! 9;
drone = {|i| var harm = pow(2, 2 - (i / 3).trunc), amp = (1 / pow(harm, 2));
SinOsc.ar(60 * harm + TRand.kr(-3, 3, switches[i]), 0, amp)} ! 9;
Out.ar(~bassBusArray[0], Mix.new(drone) * 0.2);
}).add;
SynthDef(\sampler, {
Out.ar(~samplerBusArray, PlayBuf.ar(2, ~sBuf, BufRateScale.kr(~sBuf), doneAction: 2))
}).add;
// main routine
SynthDef(\hdust, {
arg gate = 0;
var hierarchical_dust, low_sine, high_sine, brown_noise, white_noise;
// this triggers the combinations of sources
// it is similar to the Supercollider UGen called dust but with a hierarchical structure
hierarchical_dust = (
TIRand.kr(0, 1, Impulse.kr(100)) *
TIRand.kr(0, 1, Impulse.kr(10)) *
TIRand.kr(0, 1, Impulse.kr(1)) *
TIRand.kr(0, 1, Impulse.kr(0.1))
);
// adjust the multiplier at the end of each line for adjusting levels
// note with each trigger, each source has a 1 in 3 chance of sounding
low_sine = SinOsc.ar(76.midicps / 16) * (TIRand.kr(0, 2, hierarchical_dust) < 1) * 0.1;
high_sine = SinOsc.ar(76.midicps * 8) * (TIRand.kr(0, 2, hierarchical_dust) < 1) * 0.01;
brown_noise = BrownNoise.ar() * (TIRand.kr(0, 2, hierarchical_dust) < 1) * 0.025;
white_noise = WhiteNoise.ar() * (TIRand.kr(0, 2, hierarchical_dust) < 1) * 0.02;
Out.ar(~hdustBusArray[0],
((low_sine + high_sine + brown_noise + white_noise) )
);
}).add;
)
(
var bass, hdust, sampler, mixer;
bass = Synth.tail(~group, \bass);
hdust = Synth.tail(~group, \hdust);
sampler = Synth.head(~group, \sampler);
mixer = Synth.tail(~group, \mixer);
OSCdef(\mixer, {arg msg, time, addr, port;
mixer.set((msg[1] ++ '_' ++ msg[2] ++ '_' ++ msg[3]), msg[4])
}, \mixer);
OSCdef(\sampler, {arg msg, time, addr, port;
msg.postln;
sampler.free;
~sBuf.free;
~sBuf = Buffer.read(s, msg[1].asString.postln, action: {sampler = Synth.head(~group, \sampler)});
}, \sampler);
) )
/* old something
( (
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur; SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms, freqFinal, start, end; var trig, exc, sig1, sig2, noHarms, freqFinal, start, end;
@ -781,16 +903,5 @@ SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2)); Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
}).add; }).add;
) )
*/
"{\"a\": 1}".parseYAML["a"].asInteger;
"{\"a\": 1}".parseJSON["a"].isNumber;
1223423434123.asHexString.toLower
Date.getDate.rawSeconds
Date.seed.asHexString.toLower
n = NetAddr("localhost", 8080);
n.sendMsg("/GET/#", (NetAddr.localAddr.hostname ++ ":" ++ NetAddr.localAddr.port), "/passage_probs_vals");

@ -0,0 +1,48 @@
{
"music_data":
[
[
[
[ [ [ "Rest" ], [ "Rest" ], [ 6, -5, -4, 0, -1, -2 ], [ "Rest" ] ], 0.875 ],
[ [ [ "Rest" ], [ "Rest" ], [ 6, -5, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 3 ],
[ [ [ 8, -6, -4, 0, -1, -2 ], [ "Rest" ], [ 6, -5, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 1.25 ],
[ [ [ 8, -6, -4, 0, -1, -2 ], [ 6, -5, -4, 0, -1, -3 ], [ 6, -5, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 2 ]
],
[
[ [ [ 8, -6, -4, 0, -1, -2 ], [ "Rest" ], [ 6, -5, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 0 ],
[ [ [ 8, -6, -4, 0, -1, -2 ], [ "Rest" ], [ 7, -7, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ], 2.375 ],
[ [ [ 8, -6, -4, 0, -1, -2 ], [ "Rest" ], [ 7, -7, -4, 0, -1, -2 ], [ "Rest" ] ], 0.875 ],
[ [ [ "Rest" ], [ "Rest" ], [ 7, -7, -4, 0, -1, -2 ], [ "Rest" ] ], 0 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 1.625 ]
]
]
],
"last_changes":
[
[ [ 7, -5, -3, 0, -1, -2 ], [ 5, -5, -2, 0, -2, -2 ], [ 5, -5, -2, 0, 0, -2 ], [ 7, -5, -2, 0, -1, -2 ] ],
[ [ 7, -5, -3, 0, -1, -2 ], [ 5, -5, -2, 0, -2, -2 ], [ 6, -5, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ],
[ [ 8, -6, -4, 0, -1, -2 ], [ 5, -5, -2, 0, -2, -2 ], [ 6, -5, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ],
[ [ 8, -6, -4, 0, -1, -2 ], [ 6, -5, -4, 0, -1, -3 ], [ 6, -5, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ],
[ [ 8, -6, -4, 0, -1, -2 ], [ 6, -5, -4, 0, -1, -3 ], [ 7, -7, -4, 0, -1, -2 ], [ 7, -5, -2, 0, -1, -2 ] ]
],
"cur_uid": "703e109b",
"ref_uid": "tmp",
"order_seed": 550421,
"dur_seed": 315472,
"motifs_seed": 675194,
"entrances_probs_vals": [ 0.52, 0.56, 2.4206349206349, 0.25, 1.24, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"passages_probs_vals": [ 0.52, 0.56, 2.4206349206349, 0.25, 1.24, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0.52, 0.56, 2.4206349206349, 0.25, 1.24, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ 1211.1455108359, 2400 ], [ -1650, 450 ], [ -405, 1137 ], [ 951.08359133127, 2053 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ],
"order":
[
[ [ 2, 3 ], [ 0, 1 ], [ ] ],
[ [ 3, 0 ], [ 2 ], [ 1 ] ]
],
"sus_weights": [ 0.73, 0.49, 0 ],
"order_size": [ 1, 3 ],
"passages_size": [ 0, 0 ],
"motif_edited": "false",
"order_edited": "false"
}

@ -1,40 +0,0 @@
{
"music_data":
[
[
[
[ [ [ "Rest" ], [ 1, -1, 0, 0, 0, 0 ], [ "Rest" ], [ "Rest" ] ], 4.125 ],
[ [ [ "Rest" ], [ 1, -1, 0, 0, 0, 0 ], [ 1, -1, 1, 0, 0, 0 ], [ "Rest" ] ], 2.125 ],
[ [ [ "Rest" ], [ "Rest" ], [ 1, -1, 1, 0, 0, 0 ], [ "Rest" ] ], 1.125 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 2.25 ]
]
]
],
"last_changes":
[
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, -1, 0, 0, 0, 0 ], [ 0, 1, -1, 0, 0, 0 ], [ 0, 1, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, -1, 0, 0, 0, 0 ], [ 0, 1, 0, 0, -1, 0 ], [ 0, 1, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, -1, 0, 0, 0, 0 ], [ 0, -1, 0, 0, 0, 1 ], [ 0, 1, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, -1, 0, 0, 0, 0 ], [ 0, 1, 0, 0, 0, -1 ], [ 0, 1, 0, 0, 0, 0 ] ],
[ [ 0, 0, 0, 0, 0, 0 ], [ 1, -1, 0, 0, 0, 0 ], [ 1, -1, 1, 0, 0, 0 ], [ 0, 1, 0, 0, 0, 0 ] ]
],
"cur_uid": "7264e3ac",
"ref_uid": "628d5c8b",
"order_seed": 503958,
"dur_seed": 954013,
"motifs_seed": 406284,
"entrances_probs_vals": [ 0, 1.67, 4.8015873015873, 0.24725274725275, 1.15, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"passages_probs_vals": [ 0, 1.67, 4.8015873015873, 0.24725274725275, 1.15, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0, 1.67, 4.8015873015873, 0.24725274725275, 1.15, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ -1100, 460.68111455108 ], [ -507, 1084.8297213622 ], [ 884.21052631579, 2237 ], [ 1040.2476780186, 2053 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ],
"order":
[
[ [ 1 ], [ 2 ], [ 3, 0 ] ]
],
"sus_weights": [ 0.73, 0.23, 0 ],
"order_size": [ 1, 3 ],
"passages_size": [ 0, 2 ],
"motif_edited": "false",
"order_edited": "false"
}

@ -1,794 +0,0 @@
(
// helper funcs
var hsArrayToCents, pDist, hdSum, hsChordalDistance, hsArrayToFreq;
// score funcs
var isInRange, spacingScore, rangeScore, intervalScore, inclusionScore;
// subroutines
var genTuples, initVoices, genOrders, genSubMotif, updateVoices, genDurFunc;
// primary routines
var genMotif, genSecondarySeq;
// audition funcs
var genPatterns, genMidiPatterns;
// resource management funcs
var seedFunc, genUID, writeResources, stringifyToDepth, setSeeds, sanityCheck,
msgInterpret, loadLedgerFile, loadLedgerJSON, loadModelFile, loadModelJSON,
setGlobalVars, globalVarsToDict, saveLedger;
// model vars
//(model and global vars mostly set by OSC funcs
var seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited;
// model aux vars
var entrancesDurFunc, passagesDurFunc, exitsDurFunc;
// other global vars
var popSize, exPath, dir, primes, dims, tuples,
group, player, ledgerPath, ledger, currentlyPlayingUID,
nameSpaces;
// install JSON quark
if(Quarks.isInstalled("JSONlib").not, {
Quarks.install("https://github.com/musikinformatik/JSONlib.git");
thisProcess.recompile;
//HelpBrowser.openHelpFor("Classes/JSONlib");
});
//------helper funcs
hsArrayToCents = {
arg hsArray;
hsArray.collect({arg dist, p; dist * 1200 * log2(primes[p][0]/primes[p][1])}).sum
};
pDist = {
arg array1, array2, signed = false;
var pDistance;
pDistance = hsArrayToCents.value(array1) - hsArrayToCents.value(array2);
if(signed, {pDistance}, {abs(pDistance)})
};
hdSum = {
arg hsArrays;
var size, distances, mean;
size = hsArrays.size;
distances = (size - 1).collect({arg i;
((i + 1)..(size - 1)).collect({arg j;
abs(hsArrays[i] - hsArrays[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsChordalDistance = {
arg hsArrays1, hsArrays2;
var size, distances, mean;
size = hsArrays1.size;
distances = hsArrays1.size.collect({arg i;
hsArrays2.size.collect({arg j;
abs(hsArrays1[i] - hsArrays2[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsArrayToFreq = {
arg array;
array.collect({arg dim, d; pow(primes[d][0]/primes[d][1], dim)}).product
};
//------score funcs
/*
isInRange = {
arg hsArray, min, max;
var cents;
cents = hsArrayToCents.value(hsArray);
(cents >= min) && (cents <= max)
};
*/
spacingScore = {
arg hsArrays, min;
var centsArray;
centsArray = hsArrays.collect({arg hsArray; hsArrayToCents.value(hsArray)}).sort({arg a, b; a < b});
centsArray.differentiate.drop(1).collect({arg pDistance; if(pDistance >= min, {1}, {0.01})}).sum;
};
rangeScore = {
arg hsArray1, hsArray2, min, max, low, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
if((pDistance >= min) && (pDistance <= max), {1}, {low});
};
intervalScore = {
arg hsArray1, hsArray2, mean, sd, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
pDistance.gaussCurve(1, mean, sd)
};
inclusionScore = {
arg array, test, min = 0.01;
if(array.collect({arg v; v.hash}).includes(test.hash), {min}, {1});
};
//------subroutines
genTuples = {
var tuples;
tuples = dims.collect({[-1, 0, 1]}).allTuples.select({arg tuple; (abs(tuple.drop(1)).sum <= 1) && (tuple[0] == 0)});
tuples = tuples ++ tuples.collect({arg tuple; [-3, -2, -1, 1, 2, 3].collect({arg octTrans; tuple.deepCopy.put(0, octTrans)})}).flatten;
};
initVoices = {
var init, voicesInit;
voicesInit = popSize.collect({dims.collect({0})});
/*
voicesInit = [dims.collect({0})];
(popSize - 1).do({
arg rep, new;
rep = dims.rand;
new = voicesInit.last.deepCopy;
new[rep] = new[rep] + [-1, 1].choose();
voicesInit = voicesInit.add(new);
});
*/
voicesInit.deepCopy;
};
genDurFunc = {arg chordProb, minPad, maxPad, minDur, maxDur, envData, seed;
var env, pTable, durFunc;
env = Env.pairs([[0, 0]] ++ envData.clump(2) ++ [[1, 0]]).asSignal(256).asList.asArray;
pTable = env.asRandomTable;
[chordProb, minPad, maxPad, minDur, maxDur, envData].postln;
durFunc = {arg allowChord, pad = false;
var res;
res = if(allowChord.not, {
pTable.tableRand * (maxDur - minDur) + minDur
}, {
if(1.0.rand < chordProb, {0}, {pTable.tableRand * (maxDur - minDur) + minDur});
}).round(0.125);
if(pad, {res = res + rrand(minPad.asFloat, maxPad.asFloat).round(0.125)});
if(res.asInteger == res, {res = res.asInteger});
res
};
seedFunc.value(durFunc, seed);
};
genOrders = {arg minMotifLength = 1, maxMotifLength = 5, minProgLength = 0, maxProgLength = 5;
((maxMotifLength - minMotifLength).rand + minMotifLength).collect({
var noProgIns, noSusIns, noSilentIns, prog, sus, silent, order;
noSusIns = [1, 2, 3].wchoose(susWeights.normalizeSum);
noProgIns = (popSize - noSusIns).rand + 1;
noSilentIns = popSize - noSusIns - noProgIns;
# prog, sus, silent = (0..(popSize-1)).scramble.clumps([noProgIns, noSusIns, noSilentIns]);
prog = (prog.scramble ++ ((maxProgLength - minProgLength).rand + minProgLength).collect({prog.choose}).scramble);
if(silent == nil, {silent = []});
[sus.scramble, prog, silent.scramble]
});
};
updateVoices = {arg ins, sus;
var voices, candidates, nWeights, nProbs, sel;
voices = lastXChanges.deepCopy.last;
candidates = sus.collect({arg v; tuples.collect({arg t; voices[v] + t})}).flatten;
candidates = difference(candidates.asSet, voices.asSet).asList;
nProbs = candidates.collect({arg candidate;
var stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore;
//stepScore = intervalScore.value(voices[ins], candidate, 30, 400, 0.1);
stepScore = intervalScore.value(voices[ins], candidate, 100, 100);
recentlySoundedScore = inclusionScore.value(lastXChanges.flop[ins], candidate, 0);
isInRangeScore = rangeScore.value(candidate, candidate.collect({0}), ranges[ins][0], ranges[ins][1], 0, true);
regScore = spacingScore.value(voices.deepCopy.put(ins, candidate), 300);
hdScore = 1/pow(hdSum.value(voices.deepCopy.put(ins, candidate)), 2);
//maybe what you want here is a vector to another root and then favoring movement towards it.
//distScore = pow(hsChordalDistance.value(voices, voices.put(ins, candidate)), 2);
[stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore]
});
nWeights = passagesWeights;
//this handles nWeights of 0; mainly for testing
nProbs = nProbs.flop.select({arg scores, s; nWeights[s] != 0}).flop;
nWeights = nWeights.select({arg weight; weight != 0});
nProbs = nProbs.flop.collect({arg scores, s;
if(scores.sum == 0, {scores}, {scores.normalizeSum * nWeights[s]})
});
nProbs = nProbs.flop.collect({arg scores, s; scores.product}).normalizeSum;
sel = candidates.wchoose(nProbs);
voices[ins] = sel;
lastXChanges = lastXChanges.add(voices).keep(-5);
};
genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLast = false, isLastOrder = false;
var sus, prog, silent, flatOrder, res, isInChord, allowChord, pad, lastXChangesHold, voices, adder;
# sus, prog, silent = order;
flatOrder = silent ++ sus ++ prog;
lastXChangesHold = lastXChanges.deepCopy;
voices = lastState.deepCopy;
isInChord = popSize.collect({false});
allowChord = false;
pad = false;
res = [];
"------generating motif".postln;
//need to figure out here if voices move between motifs
flatOrder.do({arg ins, i;
if(prog.includes(ins) && repeatLast.not, {updateVoices.value(ins, sus)});
adder = if(silent.includes(ins), {["Rest"]}, {lastXChanges.last.deepCopy[ins]});
if(voices[ins] != adder, {
var dur;
if((sus ++ silent).includes(ins), {
allowChord = (ins != sus.last);
pad = (ins == sus.last);
}, {
if(i < (flatOrder.size - 1), {
allowChord = (isInChord[flatOrder[i + 1]] || (ins == flatOrder[i + 1])).not;
pad = false;
}, {
allowChord = false;
pad = true
});
});
if((orderIndex == 0) && sus.includes(ins), {
dur = entrancesDurFunc.value(allowChord, pad);
}, {
dur = passagesDurFunc.value(allowChord, pad);
});
if(dur == 0, {isInChord[ins] = true}, {isInChord = popSize.collect({false})});
voices[ins] = adder;
res = res.add([voices.deepCopy.postln, dur]);
});
});
// pad ending
if(orderIndex == (orders.size - 1), {
(0..(popSize-1)).scramble.do({arg ins;
if(res.last.first[ins] != ["Rest"], {
var dur;
voices[ins] = ["Rest"];
allowChord = (voices != popSize.collect({["Rest"]}));
pad = allowChord.not;
dur = exitsDurFunc.value(allowChord, pad);
res = res.add([voices.deepCopy.postln, dur]);
});
});
});
//format and return
if(startFromLast, {lastXChanges = lastXChangesHold});
res;
};
//------primary routines
genMotif = {
var repeats, fSeq;
repeats = 1;
fSeq = [];
repeats.do({arg index;
var motif;
motif = [];
orders.do({arg order, o;
var lastState, subMotif;
lastState = if(o == 0, {popSize.collect({["Rest"]})}, {motif.last.last.first});
subMotif = genSubMotif.value(order, o, lastState, isLastOrder: o == (orders.size - 1));
motif = motif.add(subMotif);
});
sanityCheck.value(motif, index);
fSeq = fSeq.add(motif);
});
fSeq
};
genSecondarySeq = {arg seq;
var curdles, fSeq;
curdles = [];
while({curdles.sum < seq.size}, {curdles = curdles ++ [3.rand + 1]});
fSeq = seq.clumps(curdles).collect({arg clump, m;
var repeats, paddedSeq;
//add rest
paddedSeq = clump.add([[[popSize.collect({["Rest"]}), 0.5.rand]]]);
//implement repeats
repeats = [0.rand + 1, 1].wchoose([1, 0].normalizeSum);
repeats.collect({paddedSeq});
});
fSeq
};
//------audition funcs
/*
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~addr.sendMsg(~indexPath, ~indexMsg);
~addr.sendMsg(~seqPath, stringifyToDepth.value(~seqMsg, 3));
//~addr.sendMsg("/STATE/OPEN", (dir.replace("supercollider", "resources") +/+ ~idMsg +/+ ~idMsg ++ "_gui_state" ++ ".state").standardizePath.postln);
};
});
*/
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~msg.postln;
~addr.sendMsg(~path, *~msg);
};
});
genPatterns = {arg inSeq, addr, oneShot = false;
var voices, durs, pbinds, res, indices, sectionDurs, msg, ids, seq;
seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
pbinds = voices.flop.collect({arg voice;
var clumps, hdScores, freqs, fDurs;
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\instrument, \test,
\group, group,
\freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1),
\sustain, Pseq(fDurs, 1)
)
});
if(oneShot.not, {
msg = inSeq.collect({arg mSeq, m; mSeq[1..]});
//ids = inSeq.collect({arg mSeq, m; mSeq[2]});
sectionDurs = seq.collect({arg mSeq; mSeq.flatten2(mSeq.maxDepth - 5).flop[1].sum});
pbinds = pbinds ++
[
Pbind(
\type, \osc,
\addr, addr,
\path, "/playing",
\msg, Pseq(msg, 1),
\dur, Pseq(sectionDurs, 1)
);
]
});
res = Ppar(pbinds);
res
};
/*
genMidiPatterns = {arg seq;
var voices, durs, patterns, res, mOut, pbRange;
pbRange = 1; //semitones - change this as needed for your situation
mOut = MIDIOut.newByName("TiMidity", "TiMidity port 0").latency_(Server.default.latency);
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
res = Ppar(
voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs;
mOut.program(v, 70);
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\type, \midi,
\chan, v,
\noteval, Pseq(freqs.cpsmidi - 24, 1),
\note, Pfunc({ | event | event[\noteval].floor }),
\dur, Pseq(fDurs, 1),
\midiout, mOut,
\amp, 1,
\bend, Pfunc({
| event |
if (event[\note].isRest.not) {
var pitchbendvalue = event[\noteval].frac.linlin(0, pbRange, 8192, 8192*2).asInteger;
m.bend(v, pitchbendvalue);
};
0; // return something other than nil to avoid stopping the pattern
}),
);
});
);
res
};
*/
//------resource management funcs
genUID = {Date.seed.asHexString.toLower};
seedFunc = {arg func, seed;
var funcArgs, next;
next = Routine({loop{func.valueArray(funcArgs).yield }});
next.randSeed_(seed);
{arg ...args; funcArgs = args; next.value}
};
stringifyToDepth = {arg data, maxDepth = 1;
var prettyString = "", rCount = 0, writeArray, indent;
if(maxDepth == 0, {
data.asCompileString
}, {
indent = {arg size; size.collect({" "}).join("")};
writeArray = {arg array;
prettyString = prettyString ++ indent.value(rCount) ++ "[\n";
rCount = rCount + 1;
if(rCount < maxDepth, {
array.do({arg subArray; writeArray.value(subArray)});
}, {
prettyString = prettyString ++ array.collect({arg subArray;
indent.value(rCount + 1) ++ subArray.asCompileString
}).join(",\n");
});
rCount = rCount - 1;
prettyString = prettyString ++ "\n" ++ indent.value(rCount) ++ "],\n";
};
writeArray.value(data);
prettyString.replace(",\n\n", "\n").drop(-2);
})
};
sanityCheck = {arg motif, index;
//print functions = very helpful
("----------" + index + "------------").postln;
motif.flatten.do({arg val, v;
if(v > 0, {
if(motif.flatten[v-1][0].hammingDistance(val[0]) > 1, {"problem 1".postln});
if(motif.flatten[v-1][0].hammingDistance(val[0]) == 0, {"problem 2".postln});
});
val.postln
});
"***********".postln;
};
msgInterpret = {arg in, escapeDoubleQuotes = true, escapeSingleQuotes = true;
var res;
res = in;
if(res.isNil.not, {
if((res.isArray && res.isString.not), {
res = res.asCompileString;
res = res.replace(" ", "").replace("\n", "").replace("\t", "");
if(escapeSingleQuotes, {res = res.replace("\'", "")});
if(escapeDoubleQuotes, {res = res.replace("\"", "")});
res = res.replace("Rest", "\"Rest\"");
res = res.interpret;
}, {
//res.postln;
if(res.every({arg char; char.isDecDigit}), {res = res.asInteger});
});
});
res
};
writeResources = {arg path, dict;
var file, modelItems, resString;
file = File(path,"w");
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
resString = nameSpaces.collect({arg nameSpace;
var depth = 0, insert = " ";
if(nameSpace == "music_data", {depth = 3; insert = "\n"});
if(nameSpace == "last_changes", {depth = 1; insert = "\n"});
if(nameSpace == "order", {depth = 1; insert = "\n"});
if((nameSpace == "ref_uid") && (dict[nameSpace] == nil), {dict[nameSpace] = "nil"});
"\"" ++ nameSpace ++ "\":" ++ insert ++ stringifyToDepth.value(dict[nameSpace], depth)
}).join(",\n");
resString = "{\n" ++ resString ++ "\n}";
file.write(resString);
file.close;
resString
};
loadModelFile = {arg path; loadModelJSON.value(File(path, "r").readAllString.parseJSON)};
loadModelJSON = {arg jsonObject;
var dict;
dict = Dictionary.with(*nameSpaces.collect({arg nS; nS->msgInterpret.value(jsonObject[nS])}));
dict
};
setGlobalVars = {arg dict;
// order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
dict
};
globalVarsToDict = {
var modelItems, dict;
// order really matters!!!!
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
dict = Dictionary.with(*nameSpaces.collect({arg nS, n; nS->modelItems[n]}));
};
loadLedgerFile = {arg path;
ledgerPath = path;
loadLedgerJSON.value(File(ledgerPath, "r").readAllString.parseJSON)
};
loadLedgerJSON = {arg jsonObject; ledger = jsonObject["ledger"]};
saveLedger = {arg ledger, path;
var file;
file = File(path, "w");
file.write("{\n\"ledger\":\n" ++ stringifyToDepth.value(ledger, 1) ++ "\n}");
file.close;
};
//------global vars
primes = [[2, 1], [3, 2], [5, 4], [7, 4], [11, 8], [13, 8]];
//ranges = [[-2400, 0], [-1200, 1200], [0, 2400], [0, 2400]];
exPath = thisProcess.nowExecutingPath;
dir = exPath.dirname;
//popSize = 4;
dims = primes.size;
tuples = genTuples.value();
//refUID = nil;
group = Group.new;
loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json");
//passagesWeights = [1, 1, 1, 1, 1];
//susWeights = [1, 1, 1];
// order really matters!!!!
nameSpaces = [
"music_data", "last_changes", "cur_uid", "ref_uid", "order_seed", "dur_seed", "motifs_seed",
"entrances_probs_vals","passages_probs_vals", "exits_probs_vals",
"ranges", "passages_weights", "order", "sus_weights", "order_size", "passages_size",
"motif_edited", "order_edited"
];
//------OSC funcs
OSCdef(\load_ledger, {arg msg, time, addr, port;
loadLedgerFile.value(msg[1].asString);
}, \load_ledger);
OSCdef(\load_model, {arg msg, time, addr, port;
var dict;
dict = loadModelFile.value(msg[1].asString);
setGlobalVars.value(dict);
}, \load_model);
OSCdef(\save_ledger, {arg msg, time, addr, port;
msg.postln;
ledger = msgInterpret.value(msg[1].asString.parseJSON["ledger"], false).postln;
//loadLedgerJSON.value(msg[0])
saveLedger.value(ledger, msg[2].asString);
//loadLedgerFile.value(msg[1].asString);
}, \save_ledger);
OSCdef(\generate, {arg msg, time, addr, port;
var path, dict, durSeeds, musPath, modelString;
msg.postln;
path = msg[1].asString;
dict = loadModelFile.value(path);
setGlobalVars.value(dict);
popSize = ranges.size;
//refUID.postln;
loadLedgerFile.value(ledgerPath);
if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, {
[initVoices.value().deepCopy];
}, {
var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
exitsDurFunc = genDurFunc.valueArray(exitsProbVals[..4] ++ [exitsProbVals[5..]] ++ [durSeeds[2]]);
if(orders == nil, {
orders = seedFunc.value(genOrders, orderSeed).valueArray(orderSize ++ passagesSize);
//addr.sendMsg("/order", stringifyToDepth.value(orders, 1));
});
seq = seedFunc.value(genMotif, motifSeed).value;
dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict);
//addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3));
addr.sendMsg("/generated", path, modelString);
}, \generate);
OSCdef(\commit, {arg msg, time, addr, port;
var musicData, musicChanged, dict, newLedger, modelPath, musString, musFile, test1, test2;
//msg.postln;
/*
test1 = msg[1].asString.parseJSON;
test2 = (dir +/+ ".." +/+ "resources/tmp/tmp_music" ++ ".json").standardizePath.parseJSONFile;
msgInterpret.value(test1["music"])[0][0][0][1].class.postln;
msgInterpret.value(test2["music_data"])[0][0][0][1].class.postln;
(test1["music"] == test2["music_data"]).postln;
*/
musicData = loadModelJSON.value(msg[1].asString.parseJSON)["music_data"].postln;
musicChanged = (musicData != seq).postln;
curUID = genUID.value;
File.mkdir((dir +/+ ".." +/+ "resources" +/+ curUID).standardizePath);
File.copy(exPath, (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_code" ++ ".scd").standardizePath);
modelPath = (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_mus_model" ++ ".json").standardizePath;
dict = globalVarsToDict.value;
if(musicChanged, {
seq = musicData;
dict["music_data"] = seq;
dict["motif_edited"] = "true"
});
dict["cur_uid"] = curUID;
writeResources.value(modelPath, dict);
File.delete(ledgerPath ++ "_bak");
File.copy(ledgerPath, ledgerPath ++ "_bak");
File.delete(ledgerPath);
ledger = ledger.drop(-1).add(curUID);
saveLedger.value(ledger, ledgerPath);
addr.sendMsg("/committed", curUID, ledgerPath);
//refUID = curUID;
}, \commit);
OSCdef(\transport, {arg msg, time, addr, port;
msg.postln;
if(msg[1] == 0, {
player.stop;
group.set(\gate, 0);
}, {
// the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
if(msg[1] == 1, {
pSeq = [];
cuedSeek = (seq != nil);
indexStart = msg[2].asInteger;
indexEnd = ledger.size - if(cuedSeek, {2}, {1});
//ledger.postln;
if(((indexStart == (ledger.size - 1)) && cuedSeek).not, {
ledger[indexStart..indexEnd].do({arg uid, index;
var path, file;
path = (dir +/+ ".." +/+ "resources" +/+ uid +/+ uid ++ "_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.postln.parseJSON["music_data"]), path, indexStart + index, uid]);
file.close;
});
});
if(cuedSeek, {
var path, file;
path = (dir +/+ ".." +/+ "resources/tmp/tmp_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.parseJSON["music_data"]), path, ledger.size - 1, "tmp"]);
file.close;
});
}, {
pSeq = [loadModelJSON.value(msg[2].asString.parseJSON)["music_data"].postln];
});
patterns = genPatterns.value(pSeq, addr);
player = Pfset(pattern: patterns, cleanupFunc: {
addr.sendMsg("/transport", 0);
});
player = player.play
});
}, \transport);
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms;
noHarms = 30;
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add;
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms, freqFinal, start, end;
noHarms = 30;
freq = WhiteNoise.ar * 3 + freq;
freqFinal = Duty.ar((1/freq), 0, freq);
trig = Changed.ar(freqFinal);
start = Demand.ar(trig, 0, Dwhite(-1, -0.75));
end = Demand.ar(trig, 0, Dwhite(0.75, 1));
exc = Phasor.ar(trig, (end - start) * freqFinal / SampleRate.ir, start, end, 0) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(2, 3)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
}).add;
)
"{\"a\": 1}".parseYAML["a"].asInteger;
"{\"a\": 1}".parseJSON["a"].isNumber;
1223423434123.asHexString.toLower
Date.getDate.rawSeconds
Date.seed.asHexString.toLower
n = NetAddr("localhost", 8080);
n.sendMsg("/GET/#", (NetAddr.localAddr.hostname ++ ":" ++ NetAddr.localAddr.port), "/passage_probs_vals");

@ -1,794 +0,0 @@
(
// helper funcs
var hsArrayToCents, pDist, hdSum, hsChordalDistance, hsArrayToFreq;
// score funcs
var isInRange, spacingScore, rangeScore, intervalScore, inclusionScore;
// subroutines
var genTuples, initVoices, genOrders, genSubMotif, updateVoices, genDurFunc;
// primary routines
var genMotif, genSecondarySeq;
// audition funcs
var genPatterns, genMidiPatterns;
// resource management funcs
var seedFunc, genUID, writeResources, stringifyToDepth, setSeeds, sanityCheck,
msgInterpret, loadLedgerFile, loadLedgerJSON, loadModelFile, loadModelJSON,
setGlobalVars, globalVarsToDict, saveLedger;
// model vars
//(model and global vars mostly set by OSC funcs
var seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited;
// model aux vars
var entrancesDurFunc, passagesDurFunc, exitsDurFunc;
// other global vars
var popSize, exPath, dir, primes, dims, tuples,
group, player, ledgerPath, ledger, currentlyPlayingUID,
nameSpaces;
// install JSON quark
if(Quarks.isInstalled("JSONlib").not, {
Quarks.install("https://github.com/musikinformatik/JSONlib.git");
thisProcess.recompile;
//HelpBrowser.openHelpFor("Classes/JSONlib");
});
//------helper funcs
hsArrayToCents = {
arg hsArray;
hsArray.collect({arg dist, p; dist * 1200 * log2(primes[p][0]/primes[p][1])}).sum
};
pDist = {
arg array1, array2, signed = false;
var pDistance;
pDistance = hsArrayToCents.value(array1) - hsArrayToCents.value(array2);
if(signed, {pDistance}, {abs(pDistance)})
};
hdSum = {
arg hsArrays;
var size, distances, mean;
size = hsArrays.size;
distances = (size - 1).collect({arg i;
((i + 1)..(size - 1)).collect({arg j;
abs(hsArrays[i] - hsArrays[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsChordalDistance = {
arg hsArrays1, hsArrays2;
var size, distances, mean;
size = hsArrays1.size;
distances = hsArrays1.size.collect({arg i;
hsArrays2.size.collect({arg j;
abs(hsArrays1[i] - hsArrays2[j]).collect({arg dist, p; dist * log2(primes[p].product)}).sum
});
}).flat;
mean = distances.sum / distances.size;
distances.sum
//mean + ((1 / sqrt((pow(distances - mean, 2)).sum / distances.size)) * mean)
};
hsArrayToFreq = {
arg array;
array.collect({arg dim, d; pow(primes[d][0]/primes[d][1], dim)}).product
};
//------score funcs
/*
isInRange = {
arg hsArray, min, max;
var cents;
cents = hsArrayToCents.value(hsArray);
(cents >= min) && (cents <= max)
};
*/
spacingScore = {
arg hsArrays, min;
var centsArray;
centsArray = hsArrays.collect({arg hsArray; hsArrayToCents.value(hsArray)}).sort({arg a, b; a < b});
centsArray.differentiate.drop(1).collect({arg pDistance; if(pDistance >= min, {1}, {0.01})}).sum;
};
rangeScore = {
arg hsArray1, hsArray2, min, max, low, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
if((pDistance >= min) && (pDistance <= max), {1}, {low});
};
intervalScore = {
arg hsArray1, hsArray2, mean, sd, signed = false;
var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed);
pDistance.gaussCurve(1, mean, sd)
};
inclusionScore = {
arg array, test, min = 0.01;
if(array.collect({arg v; v.hash}).includes(test.hash), {min}, {1});
};
//------subroutines
genTuples = {
var tuples;
tuples = dims.collect({[-1, 0, 1]}).allTuples.select({arg tuple; (abs(tuple.drop(1)).sum <= 1) && (tuple[0] == 0)});
tuples = tuples ++ tuples.collect({arg tuple; [-3, -2, -1, 1, 2, 3].collect({arg octTrans; tuple.deepCopy.put(0, octTrans)})}).flatten;
};
initVoices = {
var init, voicesInit;
voicesInit = popSize.collect({dims.collect({0})});
/*
voicesInit = [dims.collect({0})];
(popSize - 1).do({
arg rep, new;
rep = dims.rand;
new = voicesInit.last.deepCopy;
new[rep] = new[rep] + [-1, 1].choose();
voicesInit = voicesInit.add(new);
});
*/
voicesInit.deepCopy;
};
genDurFunc = {arg chordProb, minPad, maxPad, minDur, maxDur, envData, seed;
var env, pTable, durFunc;
env = Env.pairs([[0, 0]] ++ envData.clump(2) ++ [[1, 0]]).asSignal(256).asList.asArray;
pTable = env.asRandomTable;
[chordProb, minPad, maxPad, minDur, maxDur, envData].postln;
durFunc = {arg allowChord, pad = false;
var res;
res = if(allowChord.not, {
pTable.tableRand * (maxDur - minDur) + minDur
}, {
if(1.0.rand < chordProb, {0}, {pTable.tableRand * (maxDur - minDur) + minDur});
}).round(0.125);
if(pad, {res = res + rrand(minPad.asFloat, maxPad.asFloat).round(0.125)});
if(res.asInteger == res, {res = res.asInteger});
res
};
seedFunc.value(durFunc, seed);
};
genOrders = {arg minMotifLength = 1, maxMotifLength = 5, minProgLength = 0, maxProgLength = 5;
((maxMotifLength - minMotifLength).rand + minMotifLength).collect({
var noProgIns, noSusIns, noSilentIns, prog, sus, silent, order;
noSusIns = [1, 2, 3].wchoose(susWeights.normalizeSum);
noProgIns = (popSize - noSusIns).rand + 1;
noSilentIns = popSize - noSusIns - noProgIns;
# prog, sus, silent = (0..(popSize-1)).scramble.clumps([noProgIns, noSusIns, noSilentIns]);
prog = (prog.scramble ++ ((maxProgLength - minProgLength).rand + minProgLength).collect({prog.choose}).scramble);
if(silent == nil, {silent = []});
[sus.scramble, prog, silent.scramble]
});
};
updateVoices = {arg ins, sus;
var voices, candidates, nWeights, nProbs, sel;
voices = lastXChanges.deepCopy.last;
candidates = sus.collect({arg v; tuples.collect({arg t; voices[v] + t})}).flatten;
candidates = difference(candidates.asSet, voices.asSet).asList;
nProbs = candidates.collect({arg candidate;
var stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore;
//stepScore = intervalScore.value(voices[ins], candidate, 30, 400, 0.1);
stepScore = intervalScore.value(voices[ins], candidate, 100, 100);
recentlySoundedScore = inclusionScore.value(lastXChanges.flop[ins], candidate, 0);
isInRangeScore = rangeScore.value(candidate, candidate.collect({0}), ranges[ins][0], ranges[ins][1], 0, true);
regScore = spacingScore.value(voices.deepCopy.put(ins, candidate), 300);
hdScore = 1/pow(hdSum.value(voices.deepCopy.put(ins, candidate)), 2);
//maybe what you want here is a vector to another root and then favoring movement towards it.
//distScore = pow(hsChordalDistance.value(voices, voices.put(ins, candidate)), 2);
[stepScore, recentlySoundedScore, isInRangeScore, regScore, hdScore]
});
nWeights = passagesWeights;
//this handles nWeights of 0; mainly for testing
nProbs = nProbs.flop.select({arg scores, s; nWeights[s] != 0}).flop;
nWeights = nWeights.select({arg weight; weight != 0});
nProbs = nProbs.flop.collect({arg scores, s;
if(scores.sum == 0, {scores}, {scores.normalizeSum * nWeights[s]})
});
nProbs = nProbs.flop.collect({arg scores, s; scores.product}).normalizeSum;
sel = candidates.wchoose(nProbs);
voices[ins] = sel;
lastXChanges = lastXChanges.add(voices).keep(-5);
};
genSubMotif = {arg order, orderIndex, lastState, repeatLast = false, startFromLast = false, isLastOrder = false;
var sus, prog, silent, flatOrder, res, isInChord, allowChord, pad, lastXChangesHold, voices, adder;
# sus, prog, silent = order;
flatOrder = silent ++ sus ++ prog;
lastXChangesHold = lastXChanges.deepCopy;
voices = lastState.deepCopy;
isInChord = popSize.collect({false});
allowChord = false;
pad = false;
res = [];
"------generating motif".postln;
//need to figure out here if voices move between motifs
flatOrder.do({arg ins, i;
if(prog.includes(ins) && repeatLast.not, {updateVoices.value(ins, sus)});
adder = if(silent.includes(ins), {["Rest"]}, {lastXChanges.last.deepCopy[ins]});
if(voices[ins] != adder, {
var dur;
if((sus ++ silent).includes(ins), {
allowChord = (ins != sus.last);
pad = (ins == sus.last);
}, {
if(i < (flatOrder.size - 1), {
allowChord = (isInChord[flatOrder[i + 1]] || (ins == flatOrder[i + 1])).not;
pad = false;
}, {
allowChord = false;
pad = true
});
});
if((orderIndex == 0) && sus.includes(ins), {
dur = entrancesDurFunc.value(allowChord, pad);
}, {
dur = passagesDurFunc.value(allowChord, pad);
});
if(dur == 0, {isInChord[ins] = true}, {isInChord = popSize.collect({false})});
voices[ins] = adder;
res = res.add([voices.deepCopy.postln, dur]);
});
});
// pad ending
if(orderIndex == (orders.size - 1), {
(0..(popSize-1)).scramble.do({arg ins;
if(res.last.first[ins] != ["Rest"], {
var dur;
voices[ins] = ["Rest"];
allowChord = (voices != popSize.collect({["Rest"]}));
pad = allowChord.not;
dur = exitsDurFunc.value(allowChord, pad);
res = res.add([voices.deepCopy.postln, dur]);
});
});
});
//format and return
if(startFromLast, {lastXChanges = lastXChangesHold});
res;
};
//------primary routines
genMotif = {
var repeats, fSeq;
repeats = 1;
fSeq = [];
repeats.do({arg index;
var motif;
motif = [];
orders.do({arg order, o;
var lastState, subMotif;
lastState = if(o == 0, {popSize.collect({["Rest"]})}, {motif.last.last.first});
subMotif = genSubMotif.value(order, o, lastState, isLastOrder: o == (orders.size - 1));
motif = motif.add(subMotif);
});
sanityCheck.value(motif, index);
fSeq = fSeq.add(motif);
});
fSeq
};
genSecondarySeq = {arg seq;
var curdles, fSeq;
curdles = [];
while({curdles.sum < seq.size}, {curdles = curdles ++ [3.rand + 1]});
fSeq = seq.clumps(curdles).collect({arg clump, m;
var repeats, paddedSeq;
//add rest
paddedSeq = clump.add([[[popSize.collect({["Rest"]}), 0.5.rand]]]);
//implement repeats
repeats = [0.rand + 1, 1].wchoose([1, 0].normalizeSum);
repeats.collect({paddedSeq});
});
fSeq
};
//------audition funcs
/*
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~addr.sendMsg(~indexPath, ~indexMsg);
~addr.sendMsg(~seqPath, stringifyToDepth.value(~seqMsg, 3));
//~addr.sendMsg("/STATE/OPEN", (dir.replace("supercollider", "resources") +/+ ~idMsg +/+ ~idMsg ++ "_gui_state" ++ ".state").standardizePath.postln);
};
});
*/
Event.addEventType(\osc, {
if (~addr.postln.notNil) {
~msg.postln;
~addr.sendMsg(~path, *~msg);
};
});
genPatterns = {arg inSeq, addr, oneShot = false;
var voices, durs, pbinds, res, indices, sectionDurs, msg, ids, seq;
seq = inSeq.collect({arg mSeq; mSeq[0]});
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
pbinds = voices.flop.collect({arg voice;
var clumps, hdScores, freqs, fDurs;
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\instrument, \test,
\group, group,
\freq, Pseq(freqs, 1),
\dur, Pseq(fDurs, 1),
\sustain, Pseq(fDurs, 1)
)
});
if(oneShot.not, {
msg = inSeq.collect({arg mSeq, m; mSeq[1..]});
//ids = inSeq.collect({arg mSeq, m; mSeq[2]});
sectionDurs = seq.collect({arg mSeq; mSeq.flatten2(mSeq.maxDepth - 5).flop[1].sum});
pbinds = pbinds ++
[
Pbind(
\type, \osc,
\addr, addr,
\path, "/playing",
\msg, Pseq(msg, 1),
\dur, Pseq(sectionDurs, 1)
);
]
});
res = Ppar(pbinds);
res
};
/*
genMidiPatterns = {arg seq;
var voices, durs, patterns, res, mOut, pbRange;
pbRange = 1; //semitones - change this as needed for your situation
mOut = MIDIOut.newByName("TiMidity", "TiMidity port 0").latency_(Server.default.latency);
# voices, durs = seq.flatten2(seq.maxDepth - 5).flop;
res = Ppar(
voices.flop.collect({arg voice, v;
var clumps, hdScores, freqs, fDurs;
mOut.program(v, 70);
clumps = voice.separate({arg a, b; a != b });
freqs = clumps.collect({arg clump; if(clump[0] != ["Rest"], {(60.midicps * hsArrayToFreq.value(clump[0]))}, {Rest(0)})});
fDurs = durs.clumps(clumps.collect({arg clump; clump.size})).collect({arg clump; clump.sum});
Pbind(
\type, \midi,
\chan, v,
\noteval, Pseq(freqs.cpsmidi - 24, 1),
\note, Pfunc({ | event | event[\noteval].floor }),
\dur, Pseq(fDurs, 1),
\midiout, mOut,
\amp, 1,
\bend, Pfunc({
| event |
if (event[\note].isRest.not) {
var pitchbendvalue = event[\noteval].frac.linlin(0, pbRange, 8192, 8192*2).asInteger;
m.bend(v, pitchbendvalue);
};
0; // return something other than nil to avoid stopping the pattern
}),
);
});
);
res
};
*/
//------resource management funcs
genUID = {Date.seed.asHexString.toLower};
seedFunc = {arg func, seed;
var funcArgs, next;
next = Routine({loop{func.valueArray(funcArgs).yield }});
next.randSeed_(seed);
{arg ...args; funcArgs = args; next.value}
};
stringifyToDepth = {arg data, maxDepth = 1;
var prettyString = "", rCount = 0, writeArray, indent;
if(maxDepth == 0, {
data.asCompileString
}, {
indent = {arg size; size.collect({" "}).join("")};
writeArray = {arg array;
prettyString = prettyString ++ indent.value(rCount) ++ "[\n";
rCount = rCount + 1;
if(rCount < maxDepth, {
array.do({arg subArray; writeArray.value(subArray)});
}, {
prettyString = prettyString ++ array.collect({arg subArray;
indent.value(rCount + 1) ++ subArray.asCompileString
}).join(",\n");
});
rCount = rCount - 1;
prettyString = prettyString ++ "\n" ++ indent.value(rCount) ++ "],\n";
};
writeArray.value(data);
prettyString.replace(",\n\n", "\n").drop(-2);
})
};
sanityCheck = {arg motif, index;
//print functions = very helpful
("----------" + index + "------------").postln;
motif.flatten.do({arg val, v;
if(v > 0, {
if(motif.flatten[v-1][0].hammingDistance(val[0]) > 1, {"problem 1".postln});
if(motif.flatten[v-1][0].hammingDistance(val[0]) == 0, {"problem 2".postln});
});
val.postln
});
"***********".postln;
};
msgInterpret = {arg in, escapeDoubleQuotes = true, escapeSingleQuotes = true;
var res;
res = in;
if(res.isNil.not, {
if((res.isArray && res.isString.not), {
res = res.asCompileString;
res = res.replace(" ", "").replace("\n", "").replace("\t", "");
if(escapeSingleQuotes, {res = res.replace("\'", "")});
if(escapeDoubleQuotes, {res = res.replace("\"", "")});
res = res.replace("Rest", "\"Rest\"");
res = res.interpret;
}, {
//res.postln;
if(res.every({arg char; char.isDecDigit}), {res = res.asInteger});
});
});
res
};
writeResources = {arg path, dict;
var file, modelItems, resString;
file = File(path,"w");
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
resString = nameSpaces.collect({arg nameSpace;
var depth = 0, insert = " ";
if(nameSpace == "music_data", {depth = 3; insert = "\n"});
if(nameSpace == "last_changes", {depth = 1; insert = "\n"});
if(nameSpace == "order", {depth = 1; insert = "\n"});
if((nameSpace == "ref_uid") && (dict[nameSpace] == nil), {dict[nameSpace] = "nil"});
"\"" ++ nameSpace ++ "\":" ++ insert ++ stringifyToDepth.value(dict[nameSpace], depth)
}).join(",\n");
resString = "{\n" ++ resString ++ "\n}";
file.write(resString);
file.close;
resString
};
loadModelFile = {arg path; loadModelJSON.value(File(path, "r").readAllString.parseJSON)};
loadModelJSON = {arg jsonObject;
var dict;
dict = Dictionary.with(*nameSpaces.collect({arg nS; nS->msgInterpret.value(jsonObject[nS])}));
dict
};
setGlobalVars = {arg dict;
// order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
dict
};
globalVarsToDict = {
var modelItems, dict;
// order really matters!!!!
modelItems = [
seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited
];
dict = Dictionary.with(*nameSpaces.collect({arg nS, n; nS->modelItems[n]}));
};
loadLedgerFile = {arg path;
ledgerPath = path;
loadLedgerJSON.value(File(ledgerPath, "r").readAllString.parseJSON)
};
loadLedgerJSON = {arg jsonObject; ledger = jsonObject["ledger"]};
saveLedger = {arg ledger, path;
var file;
file = File(path, "w");
file.write("{\n\"ledger\":\n" ++ stringifyToDepth.value(ledger, 1) ++ "\n}");
file.close;
};
//------global vars
primes = [[2, 1], [3, 2], [5, 4], [7, 4], [11, 8], [13, 8]];
//ranges = [[-2400, 0], [-1200, 1200], [0, 2400], [0, 2400]];
exPath = thisProcess.nowExecutingPath;
dir = exPath.dirname;
//popSize = 4;
dims = primes.size;
tuples = genTuples.value();
//refUID = nil;
group = Group.new;
loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json");
//passagesWeights = [1, 1, 1, 1, 1];
//susWeights = [1, 1, 1];
// order really matters!!!!
nameSpaces = [
"music_data", "last_changes", "cur_uid", "ref_uid", "order_seed", "dur_seed", "motifs_seed",
"entrances_probs_vals","passages_probs_vals", "exits_probs_vals",
"ranges", "passages_weights", "order", "sus_weights", "order_size", "passages_size",
"motif_edited", "order_edited"
];
//------OSC funcs
OSCdef(\load_ledger, {arg msg, time, addr, port;
loadLedgerFile.value(msg[1].asString);
}, \load_ledger);
OSCdef(\load_model, {arg msg, time, addr, port;
var dict;
dict = loadModelFile.value(msg[1].asString);
setGlobalVars.value(dict);
}, \load_model);
OSCdef(\save_ledger, {arg msg, time, addr, port;
msg.postln;
ledger = msgInterpret.value(msg[1].asString.parseJSON["ledger"], false).postln;
//loadLedgerJSON.value(msg[0])
saveLedger.value(ledger, msg[2].asString);
//loadLedgerFile.value(msg[1].asString);
}, \save_ledger);
OSCdef(\generate, {arg msg, time, addr, port;
var path, dict, durSeeds, musPath, modelString;
msg.postln;
path = msg[1].asString;
dict = loadModelFile.value(path);
setGlobalVars.value(dict);
popSize = ranges.size;
//refUID.postln;
loadLedgerFile.value(ledgerPath);
if(ledger == nil, {ledger = ["tmp"]});
if(ledger.last != "tmp", {ledger = ledger.add("tmp")});
lastXChanges = if(refUID == nil, {
[initVoices.value().deepCopy];
}, {
var file;
file = File((dir +/+ ".." +/+ "resources" +/+ refUID +/+ refUID ++ "_mus_model" ++ ".json").standardizePath, "r");
msgInterpret.value(file.readAllString.parseJSON["last_changes"]);
});
durSeeds = seedFunc.value({3.collect({rrand(100000, 999999)})}, durSeed).value.postln;
entrancesDurFunc = genDurFunc.valueArray(entrancesProbVals[..4] ++ [entrancesProbVals[5..]] ++ [durSeeds[0]]);
passagesDurFunc = genDurFunc.valueArray(passagesProbVals[..4] ++ [passagesProbVals[5..]] ++ [durSeeds[1]]);
exitsDurFunc = genDurFunc.valueArray(exitsProbVals[..4] ++ [exitsProbVals[5..]] ++ [durSeeds[2]]);
if(orders == nil, {
orders = seedFunc.value(genOrders, orderSeed).valueArray(orderSize ++ passagesSize);
//addr.sendMsg("/order", stringifyToDepth.value(orders, 1));
});
seq = seedFunc.value(genMotif, motifSeed).value;
dict = globalVarsToDict.value;
modelString = writeResources.value(path, dict);
//addr.sendMsg("/generated", musPath, stringifyToDepth.value(seq, 3));
addr.sendMsg("/generated", path, modelString);
}, \generate);
OSCdef(\commit, {arg msg, time, addr, port;
var musicData, musicChanged, dict, newLedger, modelPath, musString, musFile, test1, test2;
//msg.postln;
/*
test1 = msg[1].asString.parseJSON;
test2 = (dir +/+ ".." +/+ "resources/tmp/tmp_music" ++ ".json").standardizePath.parseJSONFile;
msgInterpret.value(test1["music"])[0][0][0][1].class.postln;
msgInterpret.value(test2["music_data"])[0][0][0][1].class.postln;
(test1["music"] == test2["music_data"]).postln;
*/
musicData = loadModelJSON.value(msg[1].asString.parseJSON)["music_data"].postln;
musicChanged = (musicData != seq).postln;
curUID = genUID.value;
File.mkdir((dir +/+ ".." +/+ "resources" +/+ curUID).standardizePath);
File.copy(exPath, (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_code" ++ ".scd").standardizePath);
modelPath = (dir +/+ ".." +/+ "resources" +/+ curUID +/+ curUID ++ "_mus_model" ++ ".json").standardizePath;
dict = globalVarsToDict.value;
if(musicChanged, {
seq = musicData;
dict["music_data"] = seq;
dict["motif_edited"] = "true"
});
dict["cur_uid"] = curUID;
writeResources.value(modelPath, dict);
File.delete(ledgerPath ++ "_bak");
File.copy(ledgerPath, ledgerPath ++ "_bak");
File.delete(ledgerPath);
ledger = ledger.drop(-1).add(curUID);
saveLedger.value(ledger, ledgerPath);
addr.sendMsg("/committed", curUID, ledgerPath);
//refUID = curUID;
}, \commit);
OSCdef(\transport, {arg msg, time, addr, port;
msg.postln;
if(msg[1] == 0, {
player.stop;
group.set(\gate, 0);
}, {
// the cued sequence can now be read from file, so this can be cleaned up
var cSize, patterns, pSeq, cuedSeek, indexStart, indexEnd, tmpLedger;
if(msg[1] == 1, {
pSeq = [];
cuedSeek = (seq != nil);
indexStart = msg[2].asInteger;
indexEnd = ledger.size - if(cuedSeek, {2}, {1});
//ledger.postln;
if(((indexStart == (ledger.size - 1)) && cuedSeek).not, {
ledger[indexStart..indexEnd].do({arg uid, index;
var path, file;
path = (dir +/+ ".." +/+ "resources" +/+ uid +/+ uid ++ "_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.postln.parseJSON["music_data"]), path, indexStart + index, uid]);
file.close;
});
});
if(cuedSeek, {
var path, file;
path = (dir +/+ ".." +/+ "resources/tmp/tmp_mus_model" ++ ".json").standardizePath;
file = File(path, "r");
pSeq = pSeq.add([msgInterpret.value(file.readAllString.parseJSON["music_data"]), path, ledger.size - 1, "tmp"]);
file.close;
});
}, {
pSeq = [loadModelJSON.value(msg[2].asString.parseJSON)["music_data"].postln];
});
patterns = genPatterns.value(pSeq, addr);
player = Pfset(pattern: patterns, cleanupFunc: {
addr.sendMsg("/transport", 0);
});
player = player.play
});
}, \transport);
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms;
noHarms = 30;
exc = Saw.ar(freq, TRand.ar(0.5, 1, Impulse.ar(freq))) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(1, 2)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
//Out.ar([0, 1], sig1 * EnvGen.kr(Env.asr(dur, 0.3, 1), gate, doneAction: 2));
}).add;
)
(
SynthDef(\test, {arg freq, gate = 1, sustain, amp, dur;
var trig, exc, sig1, sig2, noHarms, freqFinal, start, end;
noHarms = 30;
freq = WhiteNoise.ar * 3 + freq;
freqFinal = Duty.ar((1/freq), 0, freq);
trig = Changed.ar(freqFinal);
start = Demand.ar(trig, 0, Dwhite(-1, -0.75));
end = Demand.ar(trig, 0, Dwhite(0.75, 1));
exc = Phasor.ar(trig, (end - start) * freqFinal / SampleRate.ir, start, end, 0) * 0.001 + Dust.ar(10000, 0.01);
sig1 = (Klank.ar(`[ Array.series(noHarms, freq, freq),
Array.geom(noHarms, 1, 0.2) + Array.fill(noHarms, {rrand(0.01, 0.03)}),
Array.fill(noHarms, {rrand(2, 3)}) ], exc) * 0.5).softclip;
sig1 = HPF.ar(sig1, 300);
Out.ar([0, 1], sig1 * EnvGen.kr(Env.adsr(0.3, 0.3, 0.9, 0.5, 0.9), gate, doneAction: 2));
}).add;
)
"{\"a\": 1}".parseYAML["a"].asInteger;
"{\"a\": 1}".parseJSON["a"].isNumber;
1223423434123.asHexString.toLower
Date.getDate.rawSeconds
Date.seed.asHexString.toLower
n = NetAddr("localhost", 8080);
n.sendMsg("/GET/#", (NetAddr.localAddr.hostname ++ ":" ++ NetAddr.localAddr.port), "/passage_probs_vals");

@ -12,14 +12,16 @@
"6a3f7c7c", "6a3f7c7c",
"6d0c2f19", "6d0c2f19",
"7bf874ce", "7bf874ce",
"7264e3ac",
"50fec831", "50fec831",
"6a3271c4",
"7fd4d544", "7fd4d544",
"6f1305ed", "6f1305ed",
"7c7a96a2", "7c7a96a2",
"7c8bc6df", "7c8bc6df",
"46210507", "46210507",
"74faf83f" "74faf83f",
"703e109b",
"4b96f62d",
"449aeaa6",
"6409252e"
] ]
} }

@ -12,13 +12,15 @@
"6a3f7c7c", "6a3f7c7c",
"6d0c2f19", "6d0c2f19",
"7bf874ce", "7bf874ce",
"7264e3ac",
"50fec831", "50fec831",
"6a3271c4",
"7fd4d544", "7fd4d544",
"6f1305ed", "6f1305ed",
"7c7a96a2", "7c7a96a2",
"7c8bc6df", "7c8bc6df",
"46210507" "46210507",
"74faf83f",
"703e109b",
"4b96f62d",
"449aeaa6"
] ]
} }

@ -3,81 +3,60 @@
[ [
[ [
[ [
[ [ [ "Rest" ], [ "Rest" ], [ 0, 2, 0, 1, -2, 0 ], [ "Rest" ] ], 1.625 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 1.5 ],
[ [ [ "Rest" ], [ "Rest" ], [ 0, 2, 0, 1, -2, 0 ], [ 0, 2, 0, 2, -2, -1 ] ], 1.625 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ "Rest" ], [ "Rest" ], [ 0, -1, 0, 0, 0, 1 ] ], 0 ],
[ [ [ -3, 2, 0, 2, -2, -2 ], [ "Rest" ], [ 0, 2, 0, 1, -2, 0 ], [ 0, 2, 0, 2, -2, -1 ] ], 2.75 ] [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 0, 0, 1, 1 ], [ "Rest" ], [ 0, -1, 0, 0, 0, 1 ] ], 1.625 ],
], [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 0, 0, 1, 1 ], [ -1, 0, 0, 0, 0, 2 ], [ 0, -1, 0, 0, 0, 1 ] ], 1.25 ],
[ [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 0, 0, 1, 1 ], [ -1, 0, 0, 1, 0, 1 ], [ 0, -1, 0, 0, 0, 1 ] ], 1.25 ],
[ [ [ -3, 2, 0, 2, -2, -2 ], [ "Rest" ], [ 0, 2, 0, 1, -2, 0 ], [ "Rest" ] ], 0.75 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 0, 0, 1, 1 ], [ 0, 0, -1, 0, 0, 1 ], [ 0, -1, 0, 0, 0, 1 ] ], 0 ],
[ [ [ -3, 2, 0, 2, -2, -2 ], [ -2, 3, 0, 1, -2, -1 ], [ 0, 2, 0, 1, -2, 0 ], [ "Rest" ] ], 2.75 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, -1, 1 ], [ 0, 0, -1, 0, 0, 1 ], [ 0, -1, 0, 0, 0, 1 ] ], 1.375 ],
[ [ [ -3, 3, 0, 1, -3, -1 ], [ -2, 3, 0, 1, -2, -1 ], [ 0, 2, 0, 1, -2, 0 ], [ "Rest" ] ], 1.25 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 0, 0, 0, 2 ], [ 0, 0, -1, 0, 0, 1 ], [ 0, -1, 0, 0, 0, 1 ] ], 0 ],
[ [ [ -3, 3, 0, 1, -3, -1 ], [ -2, 3, 0, 1, -2, -1 ], [ 1, 3, 0, 0, -2, -1 ], [ "Rest" ] ], 2.5 ] [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 0, 0, 0, 2 ], [ 0, 0, 0, 0, -1, 1 ], [ 0, -1, 0, 0, 0, 1 ] ], 3.125 ]
], ],
[ [
[ [ [ -3, 3, 0, 1, -3, -1 ], [ -2, 3, 0, 1, -2, -1 ], [ "Rest" ], [ "Rest" ] ], 0.75 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 0, 0, 0, 2 ], [ "Rest" ], [ 0, -1, 0, 0, 0, 1 ] ], 0 ],
[ [ [ -3, 3, 0, 1, -3, -1 ], [ -2, 3, 0, 1, -2, -1 ], [ "Rest" ], [ 0, 2, 0, 2, -2, -1 ] ], 3.25 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 0, 0, 0, 2 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ] ], 1.5 ],
[ [ [ -3, 3, 0, 1, -3, -1 ], [ -2, 2, -1, 2, -2, -1 ], [ "Rest" ], [ 0, 2, 0, 2, -2, -1 ] ], 0.75 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 1, 0, 0, 0, 1 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ] ], 1.625 ],
[ [ [ -3, 1, 0, 2, -2, -1 ], [ -2, 2, -1, 2, -2, -1 ], [ "Rest" ], [ 0, 2, 0, 2, -2, -1 ] ], 1.625 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 0, 0, 1, 1 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ] ], 1.25 ],
[ [ [ -3, 1, 0, 2, -2, -1 ], [ -3, 3, 0, 2, -2, -1 ], [ "Rest" ], [ 0, 2, 0, 2, -2, -1 ] ], 1 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 1, 0, 0, 1 ], [ "Rest" ], [ 0, 0, 0, 0, 0, 0 ] ], 1.375 ],
[ [ [ -3, 1, 0, 2, -2, -1 ], [ -2, 1, 0, 2, -2, -1 ], [ "Rest" ], [ 0, 2, 0, 2, -2, -1 ] ], 1.25 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 1, 0, 0, 1 ], [ "Rest" ], [ -1, 0, 0, 0, 1, 1 ] ], 1.375 ],
[ [ [ -3, 2, 0, 1, -2, -1 ], [ -2, 1, 0, 2, -2, -1 ], [ "Rest" ], [ 0, 2, 0, 2, -2, -1 ] ], 0.875 ], [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 1, 0, 0, 1 ], [ "Rest" ], [ -1, 1, 0, 0, 0, 1 ] ], 0.75 ],
[ [ [ -3, 2, 0, 2, -2, -2 ], [ -2, 1, 0, 2, -2, -1 ], [ "Rest" ], [ 0, 2, 0, 2, -2, -1 ] ], 1.625 ] [ [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 1, 0, 0, 1 ], [ "Rest" ], [ 0, -1, 0, 0, 0, 1 ] ], 2.875 ],
], [ [ [ -1, 0, 0, 0, 0, 1 ], [ "Rest" ], [ "Rest" ], [ 0, -1, 0, 0, 0, 1 ] ], 0 ],
[ [ [ [ -1, 0, 0, 0, 0, 1 ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 0 ],
[ [ [ "Rest" ], [ -2, 1, 0, 2, -2, -1 ], [ "Rest" ], [ 0, 2, 0, 2, -2, -1 ] ], 0.75 ], [ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 3.5 ]
[ [ [ "Rest" ], [ -2, 1, 0, 2, -2, -1 ], [ 1, 3, 0, 0, -2, -1 ], [ 0, 2, 0, 2, -2, -1 ] ], 2.625 ],
[ [ [ "Rest" ], [ -2, 4, 0, 0, -2, -1 ], [ 1, 3, 0, 0, -2, -1 ], [ 0, 2, 0, 2, -2, -1 ] ], 0.75 ],
[ [ [ "Rest" ], [ -2, 4, 0, 0, -2, -1 ], [ 1, 3, 0, 0, -2, -1 ], [ 0, 3, 0, 1, -2, -1 ] ], 0.875 ],
[ [ [ "Rest" ], [ -2, 4, 0, 0, -2, -1 ], [ 1, 3, 0, 0, -2, -1 ], [ 0, 3, 0, 0, -2, 0 ] ], 2.375 ]
],
[
[ [ [ "Rest" ], [ "Rest" ], [ 1, 3, 0, 0, -2, -1 ], [ 0, 3, 0, 0, -2, 0 ] ], 1.625 ],
[ [ [ -3, 2, 0, 2, -2, -2 ], [ "Rest" ], [ 1, 3, 0, 0, -2, -1 ], [ 0, 3, 0, 0, -2, 0 ] ], 2.5 ],
[ [ [ -3, 2, 0, 2, -2, -2 ], [ "Rest" ], [ 0, 3, 0, 2, -2, -2 ], [ 0, 3, 0, 0, -2, 0 ] ], 1.25 ],
[ [ [ -3, 2, 0, 2, -2, -2 ], [ "Rest" ], [ 0, 3, 0, 2, -2, -2 ], [ 0, 2, 0, 2, -1, -2 ] ], 2.75 ]
],
[
[ [ [ -3, 2, 0, 2, -2, -2 ], [ -2, 4, 0, 0, -2, -1 ], [ 0, 3, 0, 2, -2, -2 ], [ 0, 2, 0, 2, -1, -2 ] ], 1.75 ],
[ [ [ -3, 2, 0, 2, -2, -2 ], [ -2, 4, 0, 0, -2, -1 ], [ 0, 4, 1, 0, -2, -1 ], [ 0, 2, 0, 2, -1, -2 ] ], 1.25 ],
[ [ [ -3, 2, 0, 2, -2, -2 ], [ -2, 4, 0, 0, -2, -1 ], [ 0, 4, 1, 0, -2, -1 ], [ 1, 4, 0, 0, -2, -2 ] ], 1.625 ],
[ [ [ -4, 4, 0, 1, -2, -1 ], [ -2, 4, 0, 0, -2, -1 ], [ 0, 4, 1, 0, -2, -1 ], [ 1, 4, 0, 0, -2, -2 ] ], 2.125 ],
[ [ [ "Rest" ], [ -2, 4, 0, 0, -2, -1 ], [ 0, 4, 1, 0, -2, -1 ], [ 1, 4, 0, 0, -2, -2 ] ], 1.375 ],
[ [ [ "Rest" ], [ "Rest" ], [ 0, 4, 1, 0, -2, -1 ], [ 1, 4, 0, 0, -2, -2 ] ], 1 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ 1, 4, 0, 0, -2, -2 ] ], 0.875 ],
[ [ [ "Rest" ], [ "Rest" ], [ "Rest" ], [ "Rest" ] ], 3 ]
] ]
] ]
], ],
"last_changes": "last_changes":
[ [
[ [ -3, 2, 0, 2, -2, -2 ], [ -2, 4, 0, 0, -2, -1 ], [ 0, 3, 0, 2, -2, -2 ], [ 0, 3, 0, 0, -2, 0 ] ], [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 0, 0, 1, 1 ], [ 0, 0, 0, 0, -1, 1 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ -3, 2, 0, 2, -2, -2 ], [ -2, 4, 0, 0, -2, -1 ], [ 0, 3, 0, 2, -2, -2 ], [ 0, 2, 0, 2, -1, -2 ] ], [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 1, 0, 0, 1 ], [ 0, 0, 0, 0, -1, 1 ], [ 0, 0, 0, 0, 0, 0 ] ],
[ [ -3, 2, 0, 2, -2, -2 ], [ -2, 4, 0, 0, -2, -1 ], [ 0, 4, 1, 0, -2, -1 ], [ 0, 2, 0, 2, -1, -2 ] ], [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 1, 0, 0, 1 ], [ 0, 0, 0, 0, -1, 1 ], [ -1, 0, 0, 0, 1, 1 ] ],
[ [ -3, 2, 0, 2, -2, -2 ], [ -2, 4, 0, 0, -2, -1 ], [ 0, 4, 1, 0, -2, -1 ], [ 1, 4, 0, 0, -2, -2 ] ], [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 1, 0, 0, 1 ], [ 0, 0, 0, 0, -1, 1 ], [ -1, 1, 0, 0, 0, 1 ] ],
[ [ -4, 4, 0, 1, -2, -1 ], [ -2, 4, 0, 0, -2, -1 ], [ 0, 4, 1, 0, -2, -1 ], [ 1, 4, 0, 0, -2, -2 ] ] [ [ -1, 0, 0, 0, 0, 1 ], [ -1, 0, 1, 0, 0, 1 ], [ 0, 0, 0, 0, -1, 1 ], [ 0, -1, 0, 0, 0, 1 ] ]
], ],
"cur_uid": "tmp", "cur_uid": "tmp",
"ref_uid": "tmp", "ref_uid": "46a0e6a8",
"order_seed": 329828, "order_seed": 148912,
"dur_seed": 441173, "dur_seed": 424128,
"motifs_seed": 330575, "motifs_seed": 531913,
"entrances_probs_vals": [ 0, 0.48, 1.7460317460317, 0.58, 1.68, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ], "entrances_probs_vals": [ 0.75, 0, 2.26, 0.47, 1.73, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"passages_probs_vals": [ 0, 0.48, 1.7460317460317, 0.58, 1.68, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ], "passages_probs_vals": [ 0.75, 0, 2.26, 0.47, 1.73, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"exits_probs_vals": [ 0, 0.48, 1.7460317460317, 0.58, 1.68, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ], "exits_probs_vals": [ 0.75, 0, 2.26, 0.47, 1.73, 0.20725388601036, 0.68581081081081, 0.24093264248705, 0.34121621621622, 0.5, 0.5, 0.67616580310881, 0.81081081081081, 1, 0.5 ],
"ranges": [ [ -3600, -1408.0495356037 ], [ -3600, -609.2879256966 ], [ 858.20433436532, 2066 ], [ 951.08359133127, 2053 ] ], "ranges": [ [ -384, 2400 ], [ -507, 2400 ], [ -282, 2237 ], [ -1200, 2053 ] ],
"passages_weights": [ 0.75, 0.75, 0.75, 0.75, 0.75 ], "step_probs_vals": [ 0, 1200, 0, 0.017045454545454, 0.11316872427984, 0.78409090909091, 0.21604938271605, 0, 0.32304526748971, 0, 0.4238683127572, 0, 0.68312757201646, 0, 0.83539094650206, 0, 1, 0 ],
"passages_weights": [ 0.75, 0.74, 0.75, 0, 0.75 ],
"hd_exp": 2,
"hd_invert": 0,
"order": "order":
[ [
[ [ 2, 3 ], [ 0 ], [ 1 ] ], [ [ 0 ], [ 3, 1, 2, 2, 2, 1, 1, 2 ], [ ] ],
[ [ 1 ], [ 0, 2 ], [ 3 ] ], [ [ 0 ], [ 3, 1, 1, 1, 3, 3, 3 ], [ 2 ] ]
[ [ 3 ], [ 1, 0, 1, 1, 0, 0 ], [ 2 ] ],
[ [ 2 ], [ 1, 3, 3 ], [ 0 ] ],
[ [ 0 ], [ 2, 3 ], [ 1 ] ],
[ [ 1 ], [ 2, 3, 0 ], [ ] ]
], ],
"sus_weights": [ 0.73, 0.49, 0 ], "sus_weights": [ 0.75, 0.69, 0.75 ],
"order_size": [ 1, 7 ], "order_size": [ 2, 6 ],
"passages_size": [ 0, 5 ], "passages_size": [ 0, 10 ],
"motif_edited": "false", "motif_edited": "false",
"order_edited": "false" "order_edited": "false"
} }

@ -6,7 +6,7 @@ var hsArrayToCents, pDist, hdSum, hsChordalDistance, hsArrayToFreq;
var isInRange, spacingScore, rangeScore, intervalScore, inclusionScore; var isInRange, spacingScore, rangeScore, intervalScore, inclusionScore;
// subroutines // subroutines
var genTuples, initVoices, genOrders, genSubMotif, updateVoices, genDurFunc; var genTuples, initVoices, genOrders, genSubMotif, updateVoices, genDurFunc, genStepFunc;
// primary routines // primary routines
var genMotif, genSecondarySeq; var genMotif, genSecondarySeq;
@ -24,11 +24,12 @@ setGlobalVars, globalVarsToDict, saveLedger;
var seq, lastXChanges, var seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals, entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize, ranges, stepProbsVals, passagesWeights, hdExp, hdInvert,
orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited; motifEdited, orderEdited;
// model aux vars // model aux vars
var entrancesDurFunc, passagesDurFunc, exitsDurFunc; var entrancesDurFunc, passagesDurFunc, exitsDurFunc, stepFunc;
// other global vars // other global vars
var popSize, exPath, dir, primes, dims, tuples, var popSize, exPath, dir, primes, dims, tuples,
@ -119,7 +120,8 @@ intervalScore = {
arg hsArray1, hsArray2, mean, sd, signed = false; arg hsArray1, hsArray2, mean, sd, signed = false;
var pDistance; var pDistance;
pDistance = pDist.value(hsArray1, hsArray2, signed); pDistance = pDist.value(hsArray1, hsArray2, signed);
pDistance.gaussCurve(1, mean, sd) //pDistance.gaussCurve(1, mean, sd)
stepFunc.value(pDistance);
}; };
inclusionScore = { inclusionScore = {
@ -171,6 +173,18 @@ genDurFunc = {arg chordProb, minPad, maxPad, minDur, maxDur, envData, seed;
seedFunc.value(durFunc, seed); seedFunc.value(durFunc, seed);
}; };
genStepFunc = {arg minStep, maxStep, envData, seed;
var envDataNorm, env, pTable, stepFunc;
[minStep, maxStep, envData].postln;
envDataNorm = ([[0, 0]] ++ envData.clump(2) ++ [[1, 0]]).flop;
envDataNorm = [envDataNorm[0].normalize(minStep, maxStep), envDataNorm[1]].flop;
env = Env.pairs(envDataNorm);
stepFunc = {arg pDist;
env.at(pDist).clip(0.001, 1);
};
seedFunc.value(stepFunc, seed);
};
genOrders = {arg minMotifLength = 1, maxMotifLength = 5, minProgLength = 0, maxProgLength = 5; genOrders = {arg minMotifLength = 1, maxMotifLength = 5, minProgLength = 0, maxProgLength = 5;
((maxMotifLength - minMotifLength).rand + minMotifLength).collect({ ((maxMotifLength - minMotifLength).rand + minMotifLength).collect({
var noProgIns, noSusIns, noSilentIns, prog, sus, silent, order; var noProgIns, noSusIns, noSilentIns, prog, sus, silent, order;
@ -201,7 +215,8 @@ updateVoices = {arg ins, sus;
recentlySoundedScore = inclusionScore.value(lastXChanges.flop[ins], candidate, 0); recentlySoundedScore = inclusionScore.value(lastXChanges.flop[ins], candidate, 0);
isInRangeScore = rangeScore.value(candidate, candidate.collect({0}), ranges[ins][0], ranges[ins][1], 0, true); isInRangeScore = rangeScore.value(candidate, candidate.collect({0}), ranges[ins][0], ranges[ins][1], 0, true);
regScore = spacingScore.value(voices.deepCopy.put(ins, candidate), 300); regScore = spacingScore.value(voices.deepCopy.put(ins, candidate), 300);
hdScore = 1/pow(hdSum.value(voices.deepCopy.put(ins, candidate)), 2); hdScore = pow(hdSum.value(voices.deepCopy.put(ins, candidate)), hdExp.postln);
if(hdInvert == 0, {hdScore = 1/hdScore});
//maybe what you want here is a vector to another root and then favoring movement towards it. //maybe what you want here is a vector to another root and then favoring movement towards it.
//distScore = pow(hsChordalDistance.value(voices, voices.put(ins, candidate)), 2); //distScore = pow(hsChordalDistance.value(voices, voices.put(ins, candidate)), 2);
@ -367,8 +382,9 @@ genPatterns = {arg inSeq, addr, oneShot = false;
attacks = fDurs.collect({arg dur; dur * rrand(0.2, 0.4)}); attacks = fDurs.collect({arg dur; dur * rrand(0.2, 0.4)});
//rels = freqs.drop(2).collect({rrand(0.3, 0.5)}) ++ 2.collect({rrand(1, 3)}); //rels = freqs.drop(2).collect({rrand(0.3, 0.5)}) ++ 2.collect({rrand(1, 3)});
rels = (clumps.size - 1).collect({arg c; rels = (clumps.size - 1).collect({arg c;
if(clumps[c + 1][0] == ["Rest"], {rrand(1, 3)}, {rrand(0.3, 0.5)}); if(clumps[c + 1][0] == ["Rest"], {rrand(1.0, 3.0)}, {rrand(0.3, 0.5)});
}); });
rels = rels.add(rrand(1.0, 3.0));
amps = freqs.collect({rrand(0.6, 0.99)}); amps = freqs.collect({rrand(0.6, 0.99)});
[ [
@ -395,6 +411,7 @@ genPatterns = {arg inSeq, addr, oneShot = false;
] ]
}).flatten; }).flatten;
if(oneShot.not, { if(oneShot.not, {
"here".postln;
msg = inSeq.collect({arg mSeq, m; mSeq[1..]}); msg = inSeq.collect({arg mSeq, m; mSeq[1..]});
//ids = inSeq.collect({arg mSeq, m; mSeq[2]}); //ids = inSeq.collect({arg mSeq, m; mSeq[2]});
sectionDurs = seq.collect({arg mSeq; mSeq.flatten2(mSeq.maxDepth - 5).flop[1].sum}); sectionDurs = seq.collect({arg mSeq; mSeq.flatten2(mSeq.maxDepth - 5).flop[1].sum});
@ -517,8 +534,10 @@ msgInterpret = {arg in, escapeDoubleQuotes = true, escapeSingleQuotes = true;
res = res.replace("Rest", "\"Rest\""); res = res.replace("Rest", "\"Rest\"");
res = res.interpret; res = res.interpret;
}, { }, {
//res.postln; var tmpRes;
if(res.every({arg char; char.isDecDigit}), {res = res.asInteger}); if(res.every({arg char; char.isDecDigit}), {tmpRes = res.asInteger});
if(res.contains("."), {tmpRes = res.asFloat});
if(tmpRes != nil, {res = tmpRes});
}); });
}); });
res res
@ -532,7 +551,8 @@ writeResources = {arg path, dict;
seq, lastXChanges, seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals, entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize, ranges, stepProbsVals, passagesWeights, hdExp, hdInvert,
orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited motifEdited, orderEdited
]; ];
@ -566,7 +586,8 @@ setGlobalVars = {arg dict, skipLastXChanges = false;
// order really matters!!!! // order really matters!!!!
# seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed, # seq, lastXChanges, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals, entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize, ranges, stepProbsVals, passagesWeights, hdExp, hdInvert,
orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]}); motifEdited, orderEdited = nameSpaces.collect({arg nS; dict[nS]});
if(skipLastXChanges, {lastXChanges = tmpLastXChanges}); if(skipLastXChanges, {lastXChanges = tmpLastXChanges});
dict dict
@ -579,7 +600,8 @@ globalVarsToDict = {
seq, lastXChanges, seq, lastXChanges,
curUID, refUID, orderSeed, durSeed, motifSeed, curUID, refUID, orderSeed, durSeed, motifSeed,
entrancesProbVals, passagesProbVals, exitsProbVals, entrancesProbVals, passagesProbVals, exitsProbVals,
ranges, passagesWeights, orders, susWeights, orderSize, passagesSize, ranges, stepProbsVals, passagesWeights, hdExp, hdInvert,
orders, susWeights, orderSize, passagesSize,
motifEdited, orderEdited motifEdited, orderEdited
]; ];
dict = Dictionary.with(*nameSpaces.collect({arg nS, n; nS->modelItems[n]})); dict = Dictionary.with(*nameSpaces.collect({arg nS, n; nS->modelItems[n]}));
@ -618,7 +640,8 @@ loadLedgerFile.value(dir +/+ ".." +/+ "resources" +/+ "piece_ledger.json");
nameSpaces = [ nameSpaces = [
"music_data", "last_changes", "cur_uid", "ref_uid", "order_seed", "dur_seed", "motifs_seed", "music_data", "last_changes", "cur_uid", "ref_uid", "order_seed", "dur_seed", "motifs_seed",
"entrances_probs_vals","passages_probs_vals", "exits_probs_vals", "entrances_probs_vals","passages_probs_vals", "exits_probs_vals",
"ranges", "passages_weights", "order", "sus_weights", "order_size", "passages_size", "ranges", "step_probs_vals", "passages_weights", "hd_exp", "hd_invert",
"order", "sus_weights", "order_size", "passages_size",
"motif_edited", "order_edited" "motif_edited", "order_edited"
]; ];
@ -679,6 +702,8 @@ OSCdef(\generate, {arg msg, time, addr, port;
orders = seedFunc.value(genOrders, orderSeed).valueArray(orderSize ++ passagesSize); orders = seedFunc.value(genOrders, orderSeed).valueArray(orderSize ++ passagesSize);
//addr.sendMsg("/order", stringifyToDepth.value(orders, 1)); //addr.sendMsg("/order", stringifyToDepth.value(orders, 1));
}); });
stepFunc = genStepFunc.valueArray(stepProbsVals[..1] ++ [stepProbsVals[2..]] ++ [motifSeed]);
seq = seedFunc.value(genMotif, motifSeed).value; seq = seedFunc.value(genMotif, motifSeed).value;
lastXChanges.collect({arg item; item.postln}); lastXChanges.collect({arg item; item.postln});

Loading…
Cancel
Save