aboutsummaryrefslogtreecommitdiffstats
path: root/src/cxvec_math.c
blob: 45df8d2fcd94df15404ead7c241cce86409279da (plain)
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/*
 * cxvec_math.c
 *
 * Complex vectors math and signal processing
 *
 * Copyright (C) 2011  Sylvain Munaut <tnt@246tNt.com>
 *
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/*! \addtogroup cxvec_math
 *  @{
 */

/*! \file cxvec_math.c
 *  \brief Osmocom Complex vectors math implementation
 */

#include <complex.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#include <osmocom/dsp/cxvec.h>
#include <osmocom/dsp/cxvec_math.h>

/*! \brief Scale a complex vector (multiply by a constant)
 *  \param[in] in Input complex vector
 *  \param[in] scale Factor to apply to each sample
 *  \param[out] out Output complex vector
 *  \returns The output complex vector (or NULL if error)
 *
 * \f$out(k) = in(k) \cdot scale\f$
 *
 * The output vector parameter 'out' can be NULL to allocate a new
 * vector, or can be equal to the 'in' input vector to perform the
 * transform in-place. If it's different, it must be long enough
 * to contain the result (i.e. in->len)
 */
struct osmo_cxvec *
osmo_cxvec_scale(struct osmo_cxvec *in, float complex scale,
                 struct osmo_cxvec *out)
{
	int i;
	int seq_real;

	seq_real = !!(in->flags & CXVEC_FLG_REAL_ONLY);

	if (!out)
		out = osmo_cxvec_alloc(in->len);
	else if (out->max_len < in->len)
		return NULL;

	if (cimagf(scale) == 0.0f)
	{
		float scalef = crealf(scale);

		if (seq_real) {
			for (i=0; i<in->len; i++)
				out->data[i] = crealf(in->data[i]) * scalef;
		} else {
			for (i=0; i<in->len; i++)
				out->data[i] = in->data[i] * scalef;
		}
	}
	else
	{
		if (seq_real) {
			for (i=0; i<in->len; i++)
				out->data[i] = crealf(in->data[i]) * scale;
		} else {
			for (i=0; i<in->len; i++)
				out->data[i] = in->data[i] * scale;
		}

		out->flags &= ~CXVEC_FLG_REAL_ONLY;
	}

	out->len = in->len;

	return out;
}

/*! \brief Rotate a complex vector (frequency shift)
 *  \param[in] in Input complex vector
 *  \param[in] rps Rotation to apply in radian per sample
 *  \param[out] out Output complex vector
 *  \returns The output complex vector (or NULL if error)
 *
 * \f$out(k) = in(k) \cdot e^{j \cdot rps \cdot k}\f$
 *
 * The output vector parameter 'out' can be NULL to allocate a new
 * vector, or can be equal to the 'in' input vector to perform the
 * transform in-place. If it's different, it must be long enough
 * to contain the result (i.e. in->len)
 */
struct osmo_cxvec *
osmo_cxvec_rotate(struct osmo_cxvec *in, float rps,
                  struct osmo_cxvec *out)
{
	int i;

	if (!out)
		out = osmo_cxvec_alloc(in->len);
	else if (out->max_len < in->len)
		return NULL;

	for (i=0; i<in->len; i++)
		out->data[i] = in->data[i] * cexpf(I*(rps*i));

	out->len = in->len;
	out->flags &= ~CXVEC_FLG_REAL_ONLY;

	return out;
}

/*! \brief Convolve two complex vectors
 *  \param[in] f First input complex vector
 *  \param[in] g Second input complex vector
 *  \param[in] type The convolution span type
 *  \returns The output complex vector (or NULL if error)
 *
 * The convolution of discrete sequences is defined as :
 *
 * \f$(f * g)[n] = \sum_{m=-\infty}^{\infty} f[m] \; g[n-m]\f$
 *
 * Altough the mathematical operation is commutative, the constraint
 * of implementation limit this method. Depending on the type of span
 * chosen, it might not be and it's always recommended that 'g' be the longer
 * sequence. It should not be much of a limitation when this methos is used
 * for filtering or pulseshaping : use 'f' as the filter and 'g' as the
 * signal.
 *
 * The output vector parameter 'out' can be NULL to allocate a new
 * vector. If it's not NULL, it must be long enough to contain the result
 * (length depends on the exact convolution type)
 */
struct osmo_cxvec *
osmo_cxvec_convolve(struct osmo_cxvec *f, struct osmo_cxvec *g,
                    enum osmo_cxvec_conv_type type, struct osmo_cxvec *out)
{
	int Lf, Lg, Lo, si, ei, i, jf, jg;
	int f_real, g_real;

	if (!f || !g)
		return NULL;

	f_real = !!(f->flags & CXVEC_FLG_REAL_ONLY);
	g_real = !!(g->flags & CXVEC_FLG_REAL_ONLY);

	/* index / size */
	Lf = f->len;
	Lg = g->len;

	switch (type) {
	case CONV_FULL_SPAN:
		si = 0;
		Lo = Lf + Lg - 1;
		break;
	case CONV_OVERLAP_ONLY:
		si = Lf;
		Lo = abs(Lf-Lg) + 1;
		break;
	case CONV_NO_DELAY:
		si = (Lf >> 1) - ((Lf & 1) ^ 1);
		Lo = Lg;
		break;
	default:
		return NULL;
	}

	ei = si + Lo;

	/* Output vector */
	if (!out)
		out = osmo_cxvec_alloc(Lo);
	else if (out->max_len < Lo)
		return NULL;

	out->flags = 0;

	/* Do the math */
	if (f_real && g_real) {
		for (i=si; i<ei; i++) {
			float sum = 0.0f;
			for (jf=0,jg=i; jf<=Lf && jg>=0; jf++,jg--)
				if (jg < Lg)
					sum += crealf(f->data[jf]) * crealf(g->data[jg]);
			out->data[i-si] = sum;
		}
		out->flags |= CXVEC_FLG_REAL_ONLY;
	} else if (f_real) {
		for (i=si; i<ei; i++) {
			float complex sum = 0.0f;
			for (jf=0,jg=i; jf<Lf && jg>=0; jf++,jg--)
				if (jg < Lg)
					sum += crealf(f->data[jf]) * g->data[jg];
			out->data[i-si] = sum;
		}
	} else if (g_real) {
		for (i=si; i<ei; i++) {
			float complex sum = 0.0f;
			for (jf=0,jg=i; jf<Lf && jg>=0; jf++,jg--)
				if (jg < Lg)
					sum += f->data[jf] * crealf(g->data[jg]);
			out->data[i-si] = sum;
		}
	} else {
		for (i=si; i<ei; i++) {
			float complex sum = 0.0f;
			for (jf=0,jg=i; jf<Lf && jg>=0; jf++,jg--)
				if (jg < Lg)
					sum += f->data[jf] * g->data[jg];
			out->data[i-si] = sum;
		}
	}

	out->len = Lo;

	return out;
}

/*! \brief Cross-correlate two complex vectors
 *  \param[in] f First input complex vector
 *  \param[in] g Second input complex vector
 *  \param[in] g_corr_step Allow for oversampling of 'g' compared to 'f'
 *  \param[out] out Output complex vector
 *  \returns The output complex vector (or NULL if error)
 *
 * The cross-correlation of discrete sequences is defined as :
 *
 * \f$(f \star g)[n] = \sum_{m=-\infty}^{\infty} f^*[m] \; g[n+m]\f$
 *
 * In this implementation, the output vector will be for every n value
 * between 0 and (g->len - f->len + 1). This assumes that g is the longer
 * sequence and we 'fit' f at every positition inside it.
 *
 * With the parameter g_corr_step, it's also possible to have a g sequence
 * that is oversampled with regard to f. (if g_corr_step > 1)
 *
 * The output vector parameter 'out' can be NULL to allocate a new
 * vector. If it's not NULL, it must be long enough to contain the result
 * (i.e. g->len - f->len + 1)
 */
struct osmo_cxvec *
osmo_cxvec_correlate(struct osmo_cxvec *f, struct osmo_cxvec *g, int g_corr_step,
                     struct osmo_cxvec *out)
{
	int l, m, n, mn;
	int f_real, g_real;

	f_real = !!(f->flags & CXVEC_FLG_REAL_ONLY);
	g_real = !!(g->flags & CXVEC_FLG_REAL_ONLY);

	l = g->len - (f->len * g_corr_step) + 1;

	if (l < 0)
		return NULL;

	if (!out)
		out = osmo_cxvec_alloc(l);
	else if (out->max_len < l)
		return NULL;

	out->flags = 0;

	if (f_real && g_real) {
		for (m=0; m<l; m++) {
			float v = 0.0f;
			for (n=0,mn=m; n<f->len; n++,mn+=g_corr_step)
				v += crealf(f->data[n]) * crealf(g->data[mn]);
			out->data[m] = v;
		}
		out->flags |= CXVEC_FLG_REAL_ONLY;
	} else if (f_real) {
		for (m=0; m<l; m++) {
			complex float v = 0.0f;
			for (n=0,mn=m; n<f->len; n++,mn+=g_corr_step)
				v += crealf(f->data[n]) * g->data[mn];
			out->data[m] = v;
		}
	} else if (g_real) {
		for (m=0; m<l; m++) {
			complex float v = 0.0f;
			for (n=0,mn=m; n<f->len; n++,mn+=g_corr_step)
				v += f->data[n] * crealf(g->data[mn]);
			out->data[m] = conj(v);
		}
	} else {
		for (m=0; m<l; m++) {
			complex float v = 0.0f;
			for (n=0,mn=m; n<f->len; n++,mn+=g_corr_step)
				v += conj(f->data[n]) * g->data[mn];
			out->data[m] = v;
		}
	}

	out->len = l;

	return out;
}

/*! \brief Interpolate any fractional position in a vector using sinc filtering
 *  \param[in] cv Input complex vector
 *  \param[in] pos Position to interpolate
 *
 * pos must be >= 0 and < cv->len
 */
float complex
osmo_cxvec_interpolate_point(struct osmo_cxvec *cv, float pos)
{
	const int N = 10;
	int b, e, i;
	float complex val;

	/* Index */
	i = (int)(floorf(pos));
	b = i - N;
	e = i + N + 1;

	if (b < 0)
		b = 0;

	if (e >= cv->len)
		e = cv->len - 1;

	/* Interpolate */
	if (cv->flags & CXVEC_FLG_REAL_ONLY) {
		float valf = 0.0f;
		for (i=b; i<e; i++)
			valf += crealf(cv->data[i]) * osmo_sinc(M_PIf * (i - pos));
		val = valf;
	} else {
		val = 0.0f;
		for (i=b; i<e; i++)
			val += cv->data[i] * osmo_sinc(M_PIf * (i - pos));
	}

	return val;
}

/*! \brief Find the maximum energy (\f$|x|^2\f$) peak in a sequence
 *  \param[in] cv Input complex vector
 *  \param[in] win_size Size of the window (for algorithms using windows)
 *  \param[in] alg Peak detection algorithm to use
 *  \param[out] peak_val_p Returns interpolated peak value if non-NULL
 *  \returns Peak position with sub-sample accuracy
 */
float
osmo_cxvec_peak_energy_find(struct osmo_cxvec *cv, int win_size,
                            enum osmo_cxvec_peak_alg alg,
                            float complex *peak_val_p)
{
	float val, max_val;
	int idx, max_idx, hi;
	float he[win_size];
	float peak_pos = 0.0f;

	/* Safety */
	if (cv->len < win_size)
		win_size = cv->len;

	/* Scan for the window */
		/* State init */
	val = 0.0f;
	max_val = 0.0f;
	max_idx = 0;

		/* Prefill energy history array */
	for (hi=0; hi<win_size; hi++)
		he[hi] =  osmo_normsqf(cv->data[hi]);

		/* Main scan */
	for (idx=0; idx<cv->len-win_size; idx++)
	{
		hi = idx % win_size;

		val -= he[hi];
		he[hi] = osmo_normsqf(cv->data[idx+win_size]);
		val += he[hi];

		if (val > max_val) {
			max_val = val;
			max_idx = idx + 1;
		}
	}

	/* Find maximum peak within the window */
	/* (for PEAK_WEIGH_WIN_CENTER & PEAK_EARLY_LATE */
	if (alg == PEAK_WEIGH_WIN_CENTER || alg == PEAK_EARLY_LATE)
	{
		int mwi = 0;
		float mwv = 0.0f;

		for (idx=max_idx; idx<(max_idx+win_size); idx++) {
			val = osmo_normsqf(cv->data[idx]);
			if (val > mwv) {
				mwv = val;
				mwi = idx;
			}
		}

		if (alg == PEAK_WEIGH_WIN_CENTER) {
			max_idx = mwi - (win_size >> 1);

			if (max_idx < 0)
				max_idx = 0;
			if (max_idx > (cv->len - win_size - 1))
				max_idx = cv->len - win_size - 1;
		} else {
			max_idx = mwi;
		}
	}

	/* Find the fractional position */
	if (alg == PEAK_WEIGH_WIN || alg == PEAK_WEIGH_WIN_CENTER)
	{
		float wes = 0.0f;
		float es = 0.0f;

		for (idx=max_idx; idx<(max_idx+win_size); idx++) {
			val = osmo_normsqf(cv->data[idx]);
			wes += val * idx;
			es += val;
		}

		peak_pos = wes / es;
	}
	else if (alg == PEAK_EARLY_LATE)
	{
		float early_idx = max_idx - 1.0f;
		float late_idx  = max_idx + 1.0f;
		float complex early_pt;
		float complex late_pt;
		float incr = 0.5f;

		while (incr > (1.0f/1024.0f))
		{
			early_pt = osmo_cxvec_interpolate_point(cv, early_idx);
			late_pt  = osmo_cxvec_interpolate_point(cv, late_idx);

			if (osmo_normsqf(early_pt) < osmo_normsqf(late_pt))
				early_idx += incr;
			else if (osmo_normsqf(early_pt) > osmo_normsqf(late_pt))
				early_idx -= incr;
			else
				break;

			incr /= 2.0f;
			late_idx = early_idx + 2.0f;
		}

		peak_pos = early_idx + 1.0f;
	}

	/* Interpolate peak (if asked to) */
	if (peak_val_p)
		*peak_val_p = osmo_cxvec_interpolate_point(cv, peak_pos);

	return peak_pos;
}

/*! \brief 'Normalize' an IQ signal and apply decimation/frequency shift
 *  \param[in] sig Input complex signal
 *  \param[in] decim Decimation factor
 *  \param[in] freq_shift Frequency shift in radian per output sample
 *  \param[out] out Output complex vector
 *  \returns The output complex vector (or NULL if error)
 *
 * The operation performed are DC removal, amplitude normalization (divided
 * by the standard deviation), decimation, frequency shift.
 *
 * The output vector parameter 'out' can be NULL to allocate a new
 * vector, or can be equal to the 'in' input vector to perform the
 * transform in-place. If it's different, it must be long enough to contain
 * the result (i.e. (sig->len + decim - 1) / decim)
 */
struct osmo_cxvec *
osmo_cxvec_sig_normalize(struct osmo_cxvec *sig, int decim, float freq_shift,
                         struct osmo_cxvec *out)
{
	float complex avg = 0.0f;
	float sigma = 0.0f, stddev;
	int l, i, j;

	l = sig->len / decim;

	if (!out)
		out = osmo_cxvec_alloc(l);
	else if (out->max_len < l)
		return NULL;

	for (i=0; i<sig->len; i++)
		avg += sig->data[i];
	avg /= sig->len;

	for (i=0; i<sig->len; i++)
		sigma += osmo_normsqf(sig->data[i] - avg);
	sigma /= sig->len;

	stddev = sqrtf(sigma);
	if (stddev == 0.0f)
		stddev = 1.0f;	/* Safety against constant signals */

	for (i=0, j=0; i<l; i++,j+=decim)
		out->data[i] = (sig->data[j] - avg) / stddev;

	out->len = l;
	out->flags = sig->flags;

	if (freq_shift != 0.0f)
		for (i=0; i<out->len; i++)
			out->data[i] *= cexpf( I * (freq_shift * i) );

	return out;
}

/*! @} */