Source

sc_learning_diary / bevolver.scd

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
(
SynthDef(\agc_2, {
	|i_in, i_out, threshold=0.05, slope=0.5, clampTime=0.1, relaxTime=0.3|
	Limiter.ar(
		Compander.ar( i_in*50, Mix(i_in).max(0.0001), threshold, 1.0, slope, clampTime, relaxTime ),
	0.999)
}).send(s);

SynthDef(\jack_1, {
	|i_in,
	 i_out|
	Out.ar(i_out, In.ar(i_in, 1));
}).send(s);

SynthDef(\jack_2, {
	|i_in,
	 i_out|
	Out.ar(i_out, In.ar(i_in, 2));
}).send(s);

SynthDef(\jack_3, {
	|i_in,
	 i_out|
	Out.ar(i_out, In.ar(i_in, 3));
}).send(s);

SynthDef(\jack_4, {
	|i_in,
	 i_out|
	Out.ar(i_out, In.ar(i_in, 4));
}).send(s);

SynthDef(\cage, { //a container for agents
	|in,  //ext in
	 out, //their little voices
	 middlein,
	 //middleout,
	 extGain=1.0| //The group that contains them
	 //Should this be LocalFeedback?
	 Out.ar(middlein, In.ar(out) + extGain*InFeedback.ar(out));
//	 Out.ar(out, In.ar(middleout));
}).send(s);

SynthDef(\particle, {
	|cacophonyInToMe,
	 out = 0,
	 discernmentTime=10,	//resp time in seconds
	 buffer = 0,
	 gate = 1,
	 pitch = 1,  //first of the synth parameters
	 pointer = 0.0,
	 gain = -12.0,
	 pan = 0.0,
	 windowSize = 0.1,
	 filtFreq = 600.0,		
	 rQ = 0.5|
	//synth vars
	var env, outMix, outMono;
	//analysis vars
	var iSaid, weSaid, discernibility, crossPresence, myPresence, overallPresence, riseTime, fallTime;
	var eps = 2.0e-07;
	discernmentTime = discernmentTime; 
	env = EnvGen.kr(
	  Env.asr(discernmentTime/2, 1, discernmentTime/2, 'linear'),
	  gate: gate,
	  doneAction: 2);
	outMono = Resonz.ar(
		Warp1.ar(
		    1,			// num channels (Class docs claim only mono works)
		    buffer,		// buffer
		    pointer,		// start pos
		    pitch,			// pitch shift
		    windowSize,	// window size (sec?)
		    -1,			// envbufnum (-1=Hanning)
		    4,				// overlap
		    0.1,			// rand ratio
		    2,				// interp (2=linear)
		    gain.dbamp	// mul
		),
		filtFreq,
		rQ
	);
	outMix = Pan2.ar(
		in: outMono,	// in
		pos: pan,		// field pos
		level: env		// level
	);
	iSaid = DelayN.ar(outMono, ControlRate.ir.reciprocal, ControlRate.ir.reciprocal); //This is my voice (delayed by a vector). I will look for it in the output.
	Out.ar(out, outMix);		//I output it panned
	weSaid = In.ar(cacophonyInToMe);
	riseTime = discernmentTime/8;
	fallTime = discernmentTime;
	myPresence = A2K.kr(LagUD.ar(iSaid*iSaid, riseTime, fallTime));
//	myPresence.poll(Impulse.kr(discernmentTime.reciprocal), \me);
//	overallPresence = A2K.kr(LagUD.ar(Mix.ar(weSaid*weSaid), riseTime, fallTime));
//	overallPresence.poll(Impulse.kr(discernmentTime.reciprocal), \overall);
	crossPresence = A2K.kr(LagUD.ar(Mix.ar(iSaid*weSaid), riseTime, fallTime)); //correlate.
//	crossPresence.poll(Impulse.kr(discernmentTime.reciprocal), \cross);
	discernibility = 0.0.max(1.0 - (((crossPresence - myPresence)/(crossPresence)).squared));//scale by overallPresence?
//	discernibility.poll(Impulse.kr(discernmentTime.reciprocal), \disc).abs;
	SendTrig.kr(LFPulse.kr((discernmentTime.reciprocal)/2),0,discernibility); //FASTER than discernment time to reduce jitter worries.
}, [\ir, \ir, \ir, nil, nil, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]).send(s);

o=Proto({
	~synth = nil;
	~myServer = nil;
	~myBuf = nil;
	~mainOut = nil;
	~myCacophonyInBus = nil;
	~discernibility = 0.0;
	~responder = 0;
	~chromosome = nil;
	~particleGroup=nil;
	~discernmentTime=10;
	~discernmentChecker = nil;
	~age=0;

	~updateChromosome = { |chrom=nil|
		if (chrom.isNil()) {chrom = Array.fill(7, {1.0.rand2});};
		//["chrom", chrom, chrom[0], chrom[0].linexp(0.0,  1.0,   0.1,     10.0)].postln;
		~chromosome = chrom;
		~synthesize.(
			chrom[0].linexp(-1.0,  1.0,   0.1,     10.0), //pitch
			chrom[1].linlin(-1.0,  1.0,   0.0,      1.0), //pointer
			chrom[2].linlin(-1.0,  1.0, -36.0,      0.0), //gain
			chrom[3].linlin(-1.0,  1.0,  -1.0,      1.0), //pan
			chrom[4].linexp(-1.0,  1.0,   0.01,    10.0), //windowSize
			chrom[5].linexp(-1.0,  1.0,  40.0,  12000.0), //filtFreq
			chrom[6].linexp(-1.0,  1.0,   0.01,     1.0)  //rQ
		);
		//return self, or we get the synthdef back
		currentEnvironment;
	};
	/* This as a constructor. See
	http://article.gmane.org/gmane.comp.audio.supercollider.user/71449 */
	~setUp = {|server,
			myCacophonyInBus,
			out,
			particleGroup,
			buffer,
			chromosome,
			discernmentTime=10|
		~myServer=server;
		~mainOut=out;
		~myBuf=buffer;
		~myCacophonyInBus=myCacophonyInBus;
		~particleGroup=particleGroup;
		~discernmentTime=discernmentTime;
		~age=0;
		~synth=Synth.new(\particle, [\myCacophonyInBus, ~myCacophonyInBus, \out, ~mainOut, \discernmentTime, ~discernmentTime], ~particleGroup);
		NodeWatcher.register(~synth, true);
		/* how you set up callbacks with sane binding:
		http://new-supercollider-mailing-lists-forums-use-these.2681727.n2.nabble.com/Event-and-prototypes-tp6208222p6226707.html */
		~responder = OSCpathResponder(
			~myServer.addr,
			['/tr', ~synth.nodeID, 0],
			inEnvir { |t,r,msg| msg[3].isNaN.not.if({~discernibility=msg[3];});}
		);
		~responder.add();
		~updateChromosome.(chromosome);
		currentEnvironment;
	};
	~synthesize = { |pitch = 1,
			pointer = 0.0,
			gain = -12.0,
			pan=0.0,
			windowSize=0.1,
			filtFreq=64.0,
			rQ=0.5|
		//["pitch, pointer, gain, pan, windowSize, filtFreq, rQ", pitch, pointer, gain, pan, windowSize, filtFreq, rQ].postln;
		~synth.set(
			\pitch, pitch,
			\pointer, pointer,
			\gain, gain,
			\pan, pan,
			\windowSize, windowSize,
			\filtFreq, filtFreq,
			\rQ, rQ
		);
//		~synth.run(true);
	};
	~tearDown = {
		~synth.release();
		~responder.remove();
	};
	~tick = {
		~age= ~age+1;
	};
	~mutated = { |chromosome|
		//a mutation function. this feels like it should be set from a library of mutators. one day.
		// it returns a perturbed chromosome, but does not modify this in place.
		(chromosome.isNil()).if({chromosome = ~chromosome;});
		~chromosome.collect({|v| (v + gauss(0.0, 0.1)).softclip(); });
	}
});

n=Proto({
	//A factory and manager for a bunch of particles
	~particles = nil;
	~population = nil;
	~myServer = nil;
	~myBuf = nil;
	~mainOut = nil;
	~myCacophonyInBus = nil;
	~cacophonyOut = nil;
     ~particleGroup=nil;
	~discernmentTime=10;
	~myIn = nil;
	~myCage = nil;
	~extGain = 1.0;
	~setUp = {|server,
			in,
			out,
			buffer=nil,
			population=10,
			discernmentTime=10|
		~myServer=server;
		~myIn = in;
		~mainOut=out;
		~particles=List();
		~population=population;
		~myCacophonyInBus = Bus.audio(s, 2);
		~particleGroup=Group.new(~myServer);
		~myCage = Synth.after(~particleGroup, \cage, [
			\in, ~myIn,
			\out, ~mainOut,
			\middlein, ~myCacophonyInBus
		]);
		if (buffer.isNil()) {
			buffer = Buffer.read(s, "/Users/dan/Library/Application Support/Ableton/Library/Samples/tests/cariboutesque.aif");};
		~myBuf = buffer;
		~discernmentTime=discernmentTime;
		while ({~particles.size<~population}, {~addParticle.();});
		SystemClock.sched(discernmentTime,
			inEnvir {
				~tend.();
				"tending".postln;
				~discernmentTime;
			}
		);
		currentEnvironment;
	};
	~tearDown = {
		//first, free particles
		while ({~particles.size>0}, {~removeParticle.();});
		//now, free everything else
		SystemClock.sched(~discernmentTime*2,
			inEnvir {
				//envelopes finished-ish by now
				~freeResources.();
			}
		);
	};
	~freeResources = {
		~particleGroup.free();
		~myCacophonyInBus.free();
		~myBuf.free();
		~myCage.free()
	};
	~addParticle = {|chromosome|
		var particle;
		["creating new particle with discernmentTime", ~discernmentTime];
		particle = o.copy.setUp(
		  ~myServer,
		  ~myCacophonyInBus,
		  ~outs,
		  ~particleGroup,
		  ~myBuf,
		  nil, //chromosome
		  ~discernmentTime
		);
		~particles.add(particle);
		particle.updateChromosome(chromosome);
	};
	~randomizeAll = {|indices=nil|
		if (indices.isNil()) {indices=(0..(~particles.size-1));};
		indices.do({|idx|
			(~particles[idx]).postln;
			(~particles[idx]).updateChromosome(nil);});
	};
	~removeParticle = {|idx=0|
		["remove", idx, ~particles[idx]];
		(~particles[idx]).tearDown();
		~particles.removeAt(idx);
	};
	~tend = {
		var weakestLinks, mean, survivableDiscernability, newChromosome, discernibilities;
		~particles.do({|p| p.tick();});
		//survivableDiscernability = (~particles.size * 2).reciprocal;
		survivableDiscernability = (~particles.size).reciprocal;
		["survivableDiscernability", survivableDiscernability].postln;

		//indices of killable, unfit particles
		weakestLinks = ~particles.collect({|p, i|
			((p.age > 5).and(p.discernibility < survivableDiscernability)).if(i);
		}).removeEvery([nil]).reverse;
		["weakestLinks", weakestLinks].postln;
		weakestLinks.do({|i|
			["killing", i, ~particles[i].discernibility].postln;
			~removeParticle.(i);
		});
		discernibilities = ~particles.collect({|p| p.discernibility;});
		["mean", discernibilities.mean(), "stddev", discernibilities.stdDev()].postln;
		//add an even chance of getting a random mutant
		discernibilities = discernibilities.add(survivableDiscernability);		discernibilities = discernibilities/(discernibilities.sum);
		{~particles.size<~population}.while({
			var parent, parentChromosome, newParticle;
			var exNihilo = false;
			//this will always choose an existing one, since the new particles go at the end
			parent = ~particles.wchoose(discernibilities);
			if (parent.isNil(), {
				parentChromosome=nil; exNihilo=true;
			}, {
				parentChromosome = parent.mutated();
			});
			["birthing", discernibilities, exNihilo].postln;
			newParticle = ~addParticle.(parentChromosome);
			//["new", newParticle.chromosome, "old", parentChromosome].postln;
		});
	};
	//setter for gain has to delegate to cage synth.
	~extGain_ = {|gain|
		~myCage.set(\extGain, gain);
		~gain = gain;
	};
});


~swarmController = Proto({
	~guiWindow = nil;
	~sliderbank = nil;
	~setUp = {|swarm|
		var sliderSize = Rect(0,0,35,75);
		~guiWindow = Window.new;
		~sliderbank = HLayoutView(~guiWindow, Rect(0,0,300,300));
		//~guiWindow.onClose_{};
		EZSlider(
			~sliderbank,
			sliderSize,
			label: "minDiscern",
			initVal: 0.5,
			layout: \vert,
			action: {|slider| swarm.extGain = slider.value;}
		);
		EZSlider(
			~sliderbank,
			sliderSize,
			controlSpec: ControlSpec(2, 80, step: 1, default: swarm.population),
			label: "population",
			initVal: swarm.population,
			layout: \vert,
			action: {|slider| swarm.population = slider.value;}
		);
		~guiWindow.front;
		currentEnvironment;
	};
});
)

(
s.boot;
s.options.numOutputBusChannels;
s.options.numInputBusChannels;
~globalOuts = Bus.new(\audio, 0, 2);
~globalIns = Bus.new(\audio, s.options.numOutputBusChannels, 2);//better way to get first audio in?
//~swarmOuts = Bus.audio(s, 2); //compress swarm separately?
q=n.copy.setUp(s, ~globalIns, ~globalOuts, nil, 20, 1);
~qController = ~swarmController.copy.setUp(q);
//~comp = Synth.after(q.particleGroup, \agc_2, [\i_in, ~globalOuts, \i_out, ~swarmOuts]);
//~jack.free;
q=n.copy.setUp(s, ~globalIns, ~swarmOuts, nil, 1);
q=n.copy.setUp(s, ~globalIns, ~swarmOuts, nil, 100, 1);
q=n.copy.setUp(s, ~globalIns, ~swarmOuts, nil, 20, 0.1);
q.randomizeAll();
q.particles[8].discernmentTime;
q.setExtGain(0.0);
q.myCage;
q.population;
q.particles.size;
q.discernmentTime;
q.particles.size;
q.discernmentTime;
q.tearDown();
)

(
s.scope;
Quarks.gui;
f.isNaN.not.if({'notNAN';}, {'NAN';});
)

/*
TODO
====

* discernment
  * spectral avoidance
    * find better autocorrelation that does not favour all converging to one thing.
    * think in terms of linear regression
  *spectral seeking
    * weight by my correlation to the team
    *calculate global fitness based on global similarity
    * need to compensate for different weighting of spectral bands in the autocorrelation thingy.
  * find a better survivable discernability heuristic
  * weight two different channels oppositely, as predator or prey signals
  * how can we favour bass?
  * how can we favour rhythmic evolution? (by favouring spectral variance over time?)
  * how can we not favour white noise? (see above)
  * allow different discernibilityTimes?
  * clip discernability function as a way of killing agents
  * consider doing everything in fourier space?
    * Or the cepstral domain?
  * visualise spectrograph, or signal scope or something to distinguish what discernment is doing
* optimisation
  * share global cacophony calcs across all voices
* style
  * go to IdentityDictionaries for particle storage and hash/counter-named particles
  * switch to generating iterator Routines instead of generating temporary collections
  * get rid of this "my" business with member names
* niceties
  * have a global TempoClock to keep triggering discernibility tests, and pause if necessary
  * make populations archivable, serialisable etc
* interface
  * have controls for survivability, max population etc
  * have feedback on mean discernability etc
* sound
  * go from stereo to ambisonic, or something
  * volume control, sensitive to number of agents
  * add in LFOs
    * which means pushing param mapping inside synthdef
    * normal sine or FBSineL-style semichaotic gens?
  * record into global buffers?
  * attach "species" to buffer
* evolution
  * peg global health to global volume and global curve following
  * automagically record loops and stick to those for the sound input.
  * crossover parentage
  * interpolate smoothly to new value (but do values update even?)
  * don't wait for death to reproduce, let the young drive out the old
  * give birth when sufficiently fit.
  * consider evolvability, and how to have a more robust chromosome.
  * evolve "evolvability" 
    * mutation rates per gene
    * or increments for offspring
  * create a library of crossover, selector and mutator functions
  * visualise chromosomes
  * have some chromosomes hide for a while, but return later.
*/