Debian Codegraph @

src/libsyn123/geiger.c

raw
1 /*
2 Geiger-Mueller counter simulator.
3 (c)2016-2018 Thomas Orgis <[email protected]>, licensed MIT-style.
4 Essentially: This is just a bit of code that you can use as you please.
5 See full license text at the bottom. As part of the mpg123 distribution,
6 the GNU LPGL version 2.1 can be used instead.
7
8 This generates random pulses with a configured likelihood (event
9 activity) that drive a simulated speaker to emit the characteristic
10 ticking sound (as opposed to a perfect digital click).
11
12 This is adapted from a stand-alone demonstration program to be
13 directly available to out123 and others via libsyn123.
14 */
15
16 #include "config.h"
17
18 #define FILL_PERIOD
19 #define RAND_XORSHIFT32
20 #define NO_SMAX
21 #define NO_SMIN
22 #include "syn123_int.h"
23
24 static void white_generator(syn123_handle *sh, int samples)
25 {
26 for(int i=0; i<samples; ++i)
27 sh->workbuf.f64[1][i] = 2*rand_xorshift32(&sh->seed);
28 }
29
30 int attribute_align_arg
31 syn123_setup_white(syn123_handle *sh, unsigned long seed, size_t *period)
32 {
33 if(!sh)
34 return SYN123_BAD_HANDLE;
35 syn123_setup_silence(sh);
36 sh->seed = seed;
37 sh->generator = white_generator;
38 int ret = fill_period(sh);
39 sh->seed = seed;
40 if(ret != SYN123_OK)
41 syn123_setup_silence(sh);
42 if(period)
43 *period = sh->samples;
44 return ret;
45 }
46
47 /*
48 Brain dump for the speaker model:
49
50 Simulating a simple speaker as dampened oscillator.
51 This should result in somewhat interesting impulse response.
52 I do not bother with a lower frequency bound (people may wish to
53 apply a highpass filter to simulate a small tinny speaker).
54
55 F = - k x
56
57 There is a mass attached, carrying the momentum. A new Geiger
58 impulse just adds a big load of momentum and the oscillator
59 works with that. A simple Euler scheme should be enough here.
60
61 dx = v dt
62 dv = F/m dt
63
64 We need some friction here. Let's use simple quadratic (air)
65 friction with coefficient r, (r v^2) being a force opposing the
66 current movement.
67
68 dv = - (k x + sign(v) r v^2) / m dt
69
70 About the impulse from the counter ... it needs to be incorporated
71 as an additional force G that is applied over a certain time period.
72 I need an impulse shape. How does the cascade look again?
73 Does a gauss curve do the trick? Or a jump with linear decay? Or simply
74 a box impulse? I'll try with a box impulse, relating to a certain
75 energy of a gas discharge. then, there's a dead time interval where
76 new particles are not detected at all. After that, a time period where
77 new discharges are weaker (linear ramp as simplest model).
78
79 Let's use that model and solve it in the simplest manner:
80
81 dx = v dt
82 dv = (G(t) - k x(t) - sign(v(t)) r v(t)^2) / m dt
83
84 Some fixed friction goes on top to bring the speaker really down to
85 zero.
86 */
87
88 struct geigerspace
89 {
90 // Time is counted in sampling intervals of this size.
91 // (inverse of sampling rate).
92 double time_interval;
93 // Strength of the last event, compared to full scale.
94 // This is for capturing an event detected in the
95 // recovery period.
96 double event_strength;
97 // Age of last event in intervals. Based on this, the discharge
98 // force is applied or not, strength of a new discharge computed
99 // (if event_age > dead time).
100 // Scaling of discharge force, in relation to speaker movement.
101 double force_scale;
102 // Intervals since last event, if it is recent.
103 long event_age;
104 // Number of intervals for that a new event is not detected.
105 // This is also the duration of the discharge.
106 double dead_s;
107 long dead_time;
108 // Number of intervals till recovery after dead time.
109 long recover_time;
110 // Threshold for random value to jump over.
111 float thres;
112
113 // Oscillator properties.
114 double mass; // mass (inertia) of speaker in kg
115 double spring; // spring constant k in N/m
116 double friction; // friction coefficient in kg/(s m)
117 double friction_fixed; // Speed-independent friction.
118
119 // State variables.
120 double pos; // position of speaker [-1:1]
121 double speed; // speed of speaker movement
122 };
123
124 static double sign(double val)
125 {
126 return val < 0 ? -1. : +1;
127 }
128
129 // Advance speaker position by one time interval, applying the given force.
130 static double speaker(struct geigerspace *gs, double force)
131 {
132 double dx, dv;
133 // Some maximal numeric time step to work nicely for small sampling
134 // rates. Unstable numerics make a sound, too.
135 double euler_step = 1e-5;
136 long steps = 0;
137 do
138 {
139 double step = gs->time_interval-steps*euler_step;
140 if(step > euler_step)
141 step = euler_step;
142 // dx = v dt
143 // dv = (G(t) - k x(t) - sign(v(t)) r v(t)^2) / m dt
144 dx = gs->speed*step;
145 dv = ( force - gs->spring*gs->pos
146 - sign(gs->speed)*gs->friction*gs->speed*gs->speed )
147 / gs->mass * step;
148 gs->pos += dx;
149 gs->speed += dv;
150 // Apply some fixed friction to get down to zero.
151 if(gs->speed)
152 {
153 double ff = -sign(gs->speed)*gs->friction_fixed/gs->mass*step;
154 if(sign(gs->speed+ff) == sign(gs->speed))
155 gs->speed += ff;
156 else
157 gs->speed /= 2;
158 }
159 } while(++steps*euler_step < gs->time_interval);
160 return gs->pos;
161 }
162
163 // The logic of the Geiger-Mueller counter.
164 // Given an event (or absence of) for this time interval, return
165 // the discharge force to apply to the speaker.
166 static double discharge_force(struct geigerspace *gs, int event)
167 {
168 double strength = 0.;
169 if(gs->event_age >= 0) // If there was a recent event.
170 {
171 // Apply current event force until dead time is reached.
172 if(++gs->event_age > gs->dead_time)
173 {
174 long newtime = gs->event_age - gs->dead_time;
175 if(newtime < gs->recover_time)
176 {
177 gs->event_strength = 1.*newtime/gs->recover_time;
178 }
179 else // Possible event after full recovery.
180 {
181 gs->event_age = -1;
182 gs->event_strength = 1.;
183 }
184 }
185 else // Still serving the old event.
186 {
187 strength = gs->event_strength;
188 event = 0;
189 }
190 }
191 if(event)
192 {
193 gs->event_age = 0;
194 strength = gs->event_strength;
195 }
196 return strength*gs->force_scale;
197 }
198
199 static void geiger_init(struct geigerspace *gs, double activity, long rate)
200 {
201 if(activity < 0)
202 activity = 0.;
203 gs->time_interval = 1./rate;
204 gs->event_strength = 1.;
205 gs->event_age = -1;
206 // In the order of 100 us. Chose a large time to produce sensible results down
207 // to 8000 Hz sampling rate.
208 gs->dead_s = 0.0002;
209 gs->dead_time = (long)(gs->dead_s*rate+0.5);
210 gs->recover_time = 2*gs->dead_time;
211 // Let's artitrarily define maximum speaker displacement
212 // as 1 mm and specify values accordingly.
213 gs->pos = 0.;
214 gs->speed = 0.;
215 // Mass and spring control the self-oscillation frequency.
216 gs->mass = 0.02;
217 gs->spring = 1000000;
218 // Some dynamic friction is necessary to keep the unstable numeric
219 // solution in check. A kind of lowpass filter, too, of course.
220 gs->friction = 0.02;
221 // Some hefty fixed friction prevents self-oscillation of speaker
222 // (background sine wave). But you want _some_ of it.
223 gs->friction_fixed = 20000;
224 // Experimenting, actually. Some relation to the speaker.
225 gs->force_scale = 50000.*gs->mass*0.001/(4.*gs->dead_s*gs->dead_s);
226
227 float event_likelihood = (float)(activity*gs->time_interval);
228 if(event_likelihood > 1.f)
229 event_likelihood = 1.f;
230 gs->thres = 1.f-event_likelihood;
231 }
232
233 static void geiger_generator(syn123_handle *sh, int samples)
234 {
235 struct geigerspace *gs = sh->handle;
236 for(int i=0; i<samples; ++i)
237 sh->workbuf.f64[1][i] = speaker( gs
238 , discharge_force(gs, (rand_xorshift32(&sh->seed)+0.5)>gs->thres) );
239 // Soft clipping as speaker property. It can only move so far.
240 // Of course this could be produced by a nicely nonlinear force, too.
241 syn123_soft_clip( sh->workbuf.f64[1], MPG123_ENC_FLOAT_64, samples
242 , 1., 0.1, NULL );
243 }
244
245 int attribute_align_arg
246 syn123_setup_geiger( syn123_handle *sh, double activity, unsigned long seed
247 , size_t *period )
248 {
249 int ret = SYN123_OK;
250 if(!sh)
251 return SYN123_BAD_HANDLE;
252 syn123_setup_silence(sh);
253 struct geigerspace *handle = malloc(sizeof(*handle));
254 if(!handle)
255 return SYN123_DOOM;
256 sh->seed = seed;
257 geiger_init(handle, activity, sh->fmt.rate);
258 sh->handle = handle;
259 sh->generator = geiger_generator;
260 // Fill period buffer, re-init generator for cleanliness.
261 ret = fill_period(sh);
262 if(ret)
263 goto setup_geiger_end;
264 if(sh->samples)
265 {
266 sh->seed = seed;
267 geiger_init(handle, activity, sh->fmt.rate);
268 }
269
270 setup_geiger_end:
271 if(ret != SYN123_OK)
272 syn123_setup_silence(sh);
273 if(period)
274 *period = sh->samples;
275 return ret;
276 }
277
278 // Full license text:
279 // Copyright (c) 2016-2018 Thomas Orgis
280 //
281 // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
282 //
283 // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
284 //
285 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.